File: socket_connection.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 (1500 lines) | stat: -rw-r--r-- 50,076 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
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
/*
   Copyright (c) 2013, 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/conn_handler/socket_connection.h"

#include "my_config.h"

#include <errno.h>
#include <fcntl.h>

#include <limits.h>
#ifndef _WIN32
#include <netdb.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#include <sys/stat.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <algorithm>
#include <atomic>
#include <memory>  // std::unique_ptr
#include <new>
#include <utility>

#include "m_string.h"
#include "my_dbug.h"
#include "my_io.h"
#include "my_loglevel.h"
#include "my_sys.h"
#include "my_thread.h"
#include "mysql/components/services/log_builtins.h"
#include "mysql/psi/mysql_thread.h"
#include "mysqld_error.h"
#include "sql-common/net_ns.h"
#include "sql/auth/sql_security_ctx.h"
#include "sql/conn_handler/channel_info.h"               // Channel_info
#include "sql/conn_handler/init_net_server_extension.h"  // init_net_server_extension
#include "sql/log.h"
#include "sql/mysqld.h"     // key_socket_tcpip
#include "sql/sql_class.h"  // THD
#include "sql/sql_const.h"
#include "violite.h"  // Vio
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#ifdef HAVE_LIBWRAP
#include <syslog.h>
#ifndef HAVE_LIBWRAP_PROTOTYPES
extern "C" {
#include <tcpd.h>
}
#else
#include <tcpd.h>
#endif
#endif
#include "connection_handler_manager.h"

using std::max;

// Test accept this many times
static constexpr const uint MAX_ACCEPT_RETRY{10};

/** Number of connection errors when selecting on the listening port */
static std::atomic<ulong> connection_errors_query_block{0};

/** Number of connection errors when accepting sockets in the listening port. */
static std::atomic<ulong> connection_errors_accept{0};

/** Number of connection errors from TCP wrappers. */
static std::atomic<ulong> connection_errors_tcpwrap{0};

namespace {
struct FreeAddrInfoDeleter {
  void operator()(addrinfo *ai) {
    if (ai != nullptr) {
      freeaddrinfo(ai);
    }
  }
};

using AddrInfoPtr = std::unique_ptr<addrinfo, FreeAddrInfoDeleter>;
AddrInfoPtr GetAddrInfoPtr(const char *node, const char *service,
                           const addrinfo *hints) {
  addrinfo *p = nullptr;
  int err = getaddrinfo(node, service, hints, &p);
  AddrInfoPtr nrv{p};
  return (err == 0 ? std::move(nrv) : nullptr);
}
}  // namespace

ulong get_connection_errors_query_block() {
  return connection_errors_query_block.load();
}

ulong get_connection_errors_accept() { return connection_errors_accept.load(); }

ulong get_connection_errors_tcpwrap() {
  return connection_errors_tcpwrap.load();
}

#ifdef HAVE_LIBWRAP
static const char *libwrap_name;
#endif

///////////////////////////////////////////////////////////////////////////
// Channel_info_local_socket implementation
///////////////////////////////////////////////////////////////////////////

/**
  This class abstracts the info. about local socket mode of communication with
  the server.
*/
class Channel_info_local_socket : public Channel_info {
  // connect socket object
  MYSQL_SOCKET m_connect_sock;

 protected:
  Vio *create_and_init_vio() const override {
    Vio *vio =
        mysql_socket_vio_new(m_connect_sock, VIO_TYPE_SOCKET, VIO_LOCALHOST);
#ifdef USE_PPOLL_IN_VIO
    if (vio != nullptr) {
      // Unset thread_id, to ensure that all shutdowns explicitly set the
      // current real_id from the THD.
      vio->thread_id.reset();
      vio->signal_mask = mysqld_signal_mask;
    }
#endif
    return vio;
  }

 public:
  /**
    Constructor that sets the connect socket.

    @param connect_socket set connect socket descriptor.
  */
  Channel_info_local_socket(MYSQL_SOCKET connect_socket)
      : m_connect_sock(connect_socket) {}

  THD *create_thd() override {
    THD *thd = Channel_info::create_thd();

    if (thd != nullptr) {
      init_net_server_extension(thd);
      thd->security_context()->set_host_ptr(my_localhost, strlen(my_localhost));
    }
    return thd;
  }

  void send_error_and_close_channel(uint errorcode, int error,
                                    bool senderror) override {
    Channel_info::send_error_and_close_channel(errorcode, error, senderror);

    mysql_socket_shutdown(m_connect_sock, SHUT_RDWR);
    mysql_socket_close(m_connect_sock);
  }
};

///////////////////////////////////////////////////////////////////////////
// Channel_info_tcpip_socket implementation
///////////////////////////////////////////////////////////////////////////

/**
  This class abstracts the info. about TCP/IP socket mode of communication with
  the server.
*/
class Channel_info_tcpip_socket : public Channel_info {
  // connect socket object
  MYSQL_SOCKET m_connect_sock;
  /*
    Flag specifying whether a connection is admin connection or
    ordinary connection.
  */
  bool m_is_admin_conn;
#ifdef HAVE_SETNS
  /*
    Network namespace associated with the socket.
  */
  std::string m_network_namespace;
#endif

 protected:
  Vio *create_and_init_vio() const override {
    Vio *vio = mysql_socket_vio_new(m_connect_sock, VIO_TYPE_TCPIP, 0);
#ifdef USE_PPOLL_IN_VIO
    if (vio != nullptr) {
      vio->thread_id.reset();
      vio->signal_mask = mysqld_signal_mask;
    }
#endif

#ifdef HAVE_SETNS
    strncpy(vio->network_namespace, m_network_namespace.c_str(),
            sizeof(vio->network_namespace) - 1);
    vio->network_namespace[sizeof(vio->network_namespace) - 1] = '\0';
#endif

    return vio;
  }

 public:
  /**
    Constructor that sets the connect socket.

    @param connect_socket set connect socket descriptor.
    @param is_admin_conn  flag specifying whether a connection is admin
                          connection.
  */
  Channel_info_tcpip_socket(MYSQL_SOCKET connect_socket, bool is_admin_conn)
      : m_connect_sock(connect_socket), m_is_admin_conn(is_admin_conn) {}

  THD *create_thd() override {
    THD *thd = Channel_info::create_thd();

    if (thd != nullptr) {
      thd->set_admin_connection(m_is_admin_conn);
      init_net_server_extension(thd);
    }
    return thd;
  }

  void send_error_and_close_channel(uint errorcode, int error,
                                    bool senderror) override {
    Channel_info::send_error_and_close_channel(errorcode, error, senderror);

    mysql_socket_shutdown(m_connect_sock, SHUT_RDWR);
    mysql_socket_close(m_connect_sock);
  }

  bool is_admin_connection() const override { return m_is_admin_conn; }

#ifdef HAVE_SETNS
  /**
    Set a network namespace for channel.

    @param network_namespace  Network namespace associated with a channel.
  */
  void set_network_namespace(const std::string &network_namespace) {
    m_network_namespace = network_namespace;
  }
#endif
};

///////////////////////////////////////////////////////////////////////////
// TCP_socket implementation
///////////////////////////////////////////////////////////////////////////
#ifdef _WIN32
using Socket_error_message_buf = TCHAR[1024];
#endif

/**
  MY_BIND_ALL_ADDRESSES defines a special value for the bind-address option,
  which means that the server should listen to all available network addresses,
  both IPv6 (if available) and IPv4.

  Basically, this value instructs the server to make an attempt to bind the
  server socket to '::' address, and rollback to '0.0.0.0' if the attempt fails.
*/
const char *MY_BIND_ALL_ADDRESSES = "*";

const char *ipv4_all_addresses = "0.0.0.0";

const char *ipv6_all_addresses = "::";

/**
  TCP_socket class represents the TCP sockets abstraction. It provides
  the get_listener_socket that setup a TCP listener socket to listen.
*/
class TCP_socket {
  std::string m_bind_addr_str;      // IP address as string.
  std::string m_network_namespace;  // Network namespace if specified
  uint m_tcp_port;                  // TCP port to bind to
  uint m_backlog;       // Backlog length for queue of pending connections.
  uint m_port_timeout;  // Port timeout

  MYSQL_SOCKET create_socket(const struct addrinfo *addrinfo_list,
                             int addr_family, struct addrinfo **use_addrinfo) {
    for (const struct addrinfo *cur_ai = addrinfo_list; cur_ai != nullptr;
         cur_ai = cur_ai->ai_next) {
      if (cur_ai->ai_family != addr_family) continue;

      MYSQL_SOCKET sock =
          mysql_socket_socket(key_socket_tcpip, cur_ai->ai_family,
                              cur_ai->ai_socktype, cur_ai->ai_protocol);

      char ip_addr[INET6_ADDRSTRLEN];

      if (vio_getnameinfo(cur_ai->ai_addr, ip_addr, sizeof(ip_addr), nullptr, 0,
                          NI_NUMERICHOST)) {
        ip_addr[0] = 0;
      }

      if (mysql_socket_getfd(sock) == INVALID_SOCKET) {
        LogErr(ERROR_LEVEL, ER_CONN_TCP_NO_SOCKET,
               (addr_family == AF_INET) ? "IPv4" : "IPv6",
               (const char *)ip_addr, (int)socket_errno);
      } else {
        LogErr(INFORMATION_LEVEL, ER_CONN_TCP_CREATED, (const char *)ip_addr);

        *use_addrinfo = const_cast<addrinfo *>(cur_ai);
        return sock;
      }
    }

    return MYSQL_INVALID_SOCKET;
  }

 public:
  /**
    Constructor that takes tcp port and ip address string and other
    related parameters to set up listener tcp to listen for connection
    events.

    @param  bind_addr_str  ip address as string value.
    @param  network_namespace_str  network namespace as string value
    @param  tcp_port  tcp port number.
    @param  backlog backlog specifying length of pending connection queue.
    @param  port_timeout port timeout value
  */
  TCP_socket(std::string bind_addr_str, std::string network_namespace_str,
             uint tcp_port, uint backlog, uint port_timeout)
      : m_bind_addr_str(bind_addr_str),
        m_network_namespace(network_namespace_str),
        m_tcp_port(tcp_port),
        m_backlog(backlog),
        m_port_timeout(port_timeout) {}

  /**
    Set up a listener to listen for connection events.

    @retval   valid socket if successful else MYSQL_INVALID_SOCKET on failure.
  */
  MYSQL_SOCKET get_listener_socket() {
    const char *bind_address_str = nullptr;

    LogErr(INFORMATION_LEVEL, ER_CONN_TCP_ADDRESS, m_bind_addr_str.c_str(),
           m_tcp_port);

    // Get list of IP-addresses associated with the bind-address.

    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_flags = AI_PASSIVE;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_family = AF_UNSPEC;

    char port_buf[NI_MAXSERV];
    snprintf(port_buf, NI_MAXSERV, "%d", m_tcp_port);

    if (!m_network_namespace.empty()) {
#ifdef HAVE_SETNS
      if (set_network_namespace(m_network_namespace))
        return MYSQL_INVALID_SOCKET;
#else
      LogErr(ERROR_LEVEL, ER_NETWORK_NAMESPACES_NOT_SUPPORTED);
      return MYSQL_INVALID_SOCKET;
#endif
    }

    // Create a RAII guard for addrinfo struct.
    AddrInfoPtr ai_ptr{nullptr};

    if (native_strcasecmp(m_bind_addr_str.c_str(), MY_BIND_ALL_ADDRESSES) ==
        0) {
      /*
        That's the case when bind-address is set to a special value ('*'),
        meaning "bind to all available IP addresses". If the box supports
        the IPv6 stack, that means binding to '::'. If only IPv4 is available,
        bind to '0.0.0.0'.
      */

      bool ipv6_available = false;
      ai_ptr = GetAddrInfoPtr(ipv6_all_addresses, port_buf, &hints);
      if (ai_ptr) {
        /*
          IPv6 might be available (the system might be able to resolve an IPv6
          address, but not be able to create an IPv6-socket). Try to create a
          dummy IPv6-socket. Do not instrument that socket by P_S.
        */

        MYSQL_SOCKET s = mysql_socket_socket(0, AF_INET6, SOCK_STREAM, 0);
        ipv6_available = mysql_socket_getfd(s) != INVALID_SOCKET;
        if (ipv6_available) mysql_socket_close(s);
      }
      if (ipv6_available &&
          DBUG_EVALUATE_IF("sim_ipv6_unavailable", false, true)) {
        LogErr(INFORMATION_LEVEL, ER_CONN_TCP_IPV6_AVAILABLE);

        // Address info (ai) for IPv6 address is already set.

        bind_address_str = ipv6_all_addresses;
      } else {
        LogErr(INFORMATION_LEVEL, ER_CONN_TCP_IPV6_UNAVAILABLE);

        // Retrieve address info (ai) for IPv4 address.
        ai_ptr = GetAddrInfoPtr(ipv4_all_addresses, port_buf, &hints);
        if (!ai_ptr) {
#ifdef _WIN32
          Socket_error_message_buf msg_buff;
          FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, socket_errno,
                        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                        (LPTSTR)msg_buff, sizeof(msg_buff), NULL);
          LogErr(ERROR_LEVEL, ER_CONN_TCP_ERROR_WITH_STRERROR, msg_buff);
#else
          LogErr(ERROR_LEVEL, ER_CONN_TCP_ERROR_WITH_STRERROR, strerror(errno));
#endif
          LogErr(ERROR_LEVEL, ER_CONN_TCP_CANT_RESOLVE_HOSTNAME);
#ifdef HAVE_SETNS
          if (!m_network_namespace.empty())
            (void)restore_original_network_namespace();
#endif
          return MYSQL_INVALID_SOCKET;
        }  // !ai_ptr
        bind_address_str = ipv4_all_addresses;
      }
    } else {
      ai_ptr = GetAddrInfoPtr(m_bind_addr_str.c_str(), port_buf, &hints);
      if (!ai_ptr) {
#ifdef _WIN32
        Socket_error_message_buf msg_buff;
        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, socket_errno,
                      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                      (LPTSTR)msg_buff, sizeof(msg_buff), NULL);
        LogErr(ERROR_LEVEL, ER_CONN_TCP_ERROR_WITH_STRERROR, msg_buff);
#else
        LogErr(ERROR_LEVEL, ER_CONN_TCP_ERROR_WITH_STRERROR, strerror(errno));
#endif
        LogErr(ERROR_LEVEL, ER_CONN_TCP_CANT_RESOLVE_HOSTNAME);
#ifdef HAVE_SETNS
        if (!m_network_namespace.empty())
          (void)restore_original_network_namespace();
#endif

        return MYSQL_INVALID_SOCKET;
      }  // !ai_ptr
      bind_address_str = m_bind_addr_str.c_str();
    }

    // Log all the IP-addresses
    for (struct addrinfo *cur_ai = ai_ptr.get(); cur_ai != nullptr;
         cur_ai = cur_ai->ai_next) {
      char ip_addr[INET6_ADDRSTRLEN];

      if (vio_getnameinfo(cur_ai->ai_addr, ip_addr, sizeof(ip_addr), nullptr, 0,
                          NI_NUMERICHOST)) {
        LogErr(ERROR_LEVEL, ER_CONN_TCP_IP_NOT_LOGGED);
        continue;
      }

      LogErr(INFORMATION_LEVEL, ER_CONN_TCP_RESOLVE_INFO, bind_address_str,
             ip_addr);
    }

    /*
      If the 'bind-address' option specifies the hostname, which resolves to
      multiple IP-address, use the following rule:
      - if there are IPv4-addresses, use the first IPv4-address
      returned by getaddrinfo();
      - if there are IPv6-addresses, use the first IPv6-address
      returned by getaddrinfo();
    */

    struct addrinfo *a = nullptr;

    MYSQL_SOCKET listener_socket = create_socket(ai_ptr.get(), AF_INET, &a);

    if (mysql_socket_getfd(listener_socket) == INVALID_SOCKET)
      listener_socket = create_socket(ai_ptr.get(), AF_INET6, &a);

#ifdef HAVE_SETNS
    if (!m_network_namespace.empty() && restore_original_network_namespace())
      return MYSQL_INVALID_SOCKET;
#endif

    // Report user-error if we failed to create a socket.
    if (mysql_socket_getfd(listener_socket) == INVALID_SOCKET) {
#ifdef _WIN32
      Socket_error_message_buf msg_buff;
      FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, socket_errno,
                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)msg_buff,
                    sizeof(msg_buff), NULL);
      LogErr(ERROR_LEVEL, ER_CONN_TCP_ERROR_WITH_STRERROR, msg_buff);
#else
      LogErr(ERROR_LEVEL, ER_CONN_TCP_ERROR_WITH_STRERROR, strerror(errno));
#endif
      return MYSQL_INVALID_SOCKET;
    }

    mysql_socket_set_thread_owner(listener_socket);

#ifndef _WIN32
    /*
      We should not use SO_REUSEADDR on windows as this would enable a
      user to open two mysqld servers with the same TCP/IP port.
    */
    {
      int option_flag = 1;
      (void)mysql_socket_setsockopt(listener_socket, SOL_SOCKET, SO_REUSEADDR,
                                    (char *)&option_flag, sizeof(option_flag));
    }
#endif
#ifdef IPV6_V6ONLY
    /*
      For interoperability with older clients, IPv6 socket should
      listen on both IPv6 and IPv4 wildcard addresses.
      Turn off IPV6_V6ONLY option.

      NOTE: this will work starting from Windows Vista only.
      On Windows XP dual stack is not available, so it will not
      listen on the corresponding IPv4-address.
    */
    if (a->ai_family == AF_INET6) {
      int option_flag = 0;

      if (mysql_socket_setsockopt(listener_socket, IPPROTO_IPV6, IPV6_V6ONLY,
                                  (char *)&option_flag, sizeof(option_flag))) {
        LogErr(WARNING_LEVEL, ER_CONN_TCP_CANT_RESET_V6ONLY, (int)socket_errno);
      }
    }
#endif
    /*
      Sometimes the port is not released fast enough when stopping and
      restarting the server. This happens quite often with the test suite
      on busy Linux systems. Retry to bind the address at these intervals:
      Sleep intervals: 1, 2, 4,  6,  9, 13, 17, 22, ...
      Retry at second: 1, 3, 7, 13, 22, 35, 52, 74, ...
      Limit the sequence by m_port_timeout (set --port-open-timeout=#).
    */
    uint this_wait = 0;
    int ret = 0;
    for (uint waited = 0, retry = 1;; retry++, waited += this_wait) {
      if (((ret = mysql_socket_bind(listener_socket, a->ai_addr,
                                    a->ai_addrlen)) >= 0) ||
          (socket_errno != SOCKET_EADDRINUSE) || (waited >= m_port_timeout))
        break;
      LogErr(INFORMATION_LEVEL, ER_CONN_TCP_BIND_RETRY, mysqld_port);
      this_wait = retry * retry / 3 + 1;
      sleep(this_wait);
    }

    if (ret < 0) {
      DBUG_PRINT("error", ("Got error: %d from bind", socket_errno));
#ifdef _WIN32
      Socket_error_message_buf msg_buff;
      FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, socket_errno,
                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)msg_buff,
                    sizeof(msg_buff), NULL);
      LogErr(ERROR_LEVEL, ER_CONN_TCP_BIND_FAIL, msg_buff);
#else
      LogErr(ERROR_LEVEL, ER_CONN_TCP_BIND_FAIL, strerror(socket_errno));
#endif
      LogErr(ERROR_LEVEL, ER_CONN_TCP_IS_THERE_ANOTHER_USING_PORT, m_tcp_port);
      mysql_socket_close(listener_socket);
      return MYSQL_INVALID_SOCKET;
    }

    if (mysql_socket_listen(listener_socket, static_cast<int>(m_backlog)) < 0) {
#ifdef _WIN32
      Socket_error_message_buf msg_buff;
      FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, socket_errno,
                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)msg_buff,
                    sizeof(msg_buff), NULL);
      LogErr(ERROR_LEVEL, ER_CONN_TCP_START_FAIL, msg_buff);
#else
      LogErr(ERROR_LEVEL, ER_CONN_TCP_START_FAIL, strerror(errno));
#endif

      LogErr(ERROR_LEVEL, ER_CONN_TCP_LISTEN_FAIL, socket_errno);
      mysql_socket_close(listener_socket);
      return MYSQL_INVALID_SOCKET;
    }

#if !defined(NO_FCNTL_NONBLOCK)
    (void)mysql_sock_set_nonblocking(listener_socket);
#endif

    return listener_socket;
  }
};

#if defined(HAVE_SYS_UN_H)
///////////////////////////////////////////////////////////////////////////
// Unix_socket implementation
///////////////////////////////////////////////////////////////////////////

/**
  The Unix_socket class represents an abstraction for creating a unix
  socket ready to listen for new connections from clients.
*/
class Unix_socket {
  std::string m_unix_sockname;  // pathname for socket to bind to.
  uint m_backlog;  // backlog specifying length of pending queue connection.
  /**
    Create a lockfile which contains the pid of the mysqld instance started
    and pathname as name of unix socket pathname appended with .lock

    @retval   False if lockfile creation is successful else true if lockfile
              file could not be created.

  */
  bool create_lockfile();

 public:
  /**
    Constructor that takes pathname for unix socket to bind to
    and backlog specifying the length of pending connection queue.

    @param  unix_sockname pointer to pathname for the created unix socket
            to bind.
    @param  backlog   specifying the length of pending connection queue.
  */
  Unix_socket(const std::string *unix_sockname, uint backlog)
      : m_unix_sockname(*unix_sockname), m_backlog(backlog) {}

  /**
    Set up a listener socket which is ready to listen for connection from
    clients.

    @retval   valid socket if successful else MYSQL_INVALID_SOCKET on failure.
  */
  MYSQL_SOCKET get_listener_socket() {
    struct sockaddr_un UNIXaddr;
    DBUG_PRINT("general", ("UNIX Socket is %s", m_unix_sockname.c_str()));

    // Check path length, probably move to set unix port?
    if (m_unix_sockname.length() > (sizeof(UNIXaddr.sun_path) - 1)) {
      LogErr(ERROR_LEVEL, ER_CONN_UNIX_PATH_TOO_LONG,
             (uint)sizeof(UNIXaddr.sun_path) - 1, m_unix_sockname.c_str());
      return MYSQL_INVALID_SOCKET;
    }

    if (create_lockfile() ||
        DBUG_EVALUATE_IF("simulate_create_socket_lockfile_error", true,
                         false)) {
      LogErr(ERROR_LEVEL, ER_CONN_UNIX_LOCK_FILE_FAIL);
      return MYSQL_INVALID_SOCKET;
    }

    MYSQL_SOCKET listener_socket =
        mysql_socket_socket(key_socket_unix, AF_UNIX, SOCK_STREAM, 0);

    if (mysql_socket_getfd(listener_socket) < 0) {
      LogErr(ERROR_LEVEL, ER_CONN_UNIX_NO_FD, strerror(errno));
      return MYSQL_INVALID_SOCKET;
    }

    mysql_socket_set_thread_owner(listener_socket);

    memset(&UNIXaddr, 0, sizeof(UNIXaddr));
    UNIXaddr.sun_family = AF_UNIX;
    my_stpcpy(UNIXaddr.sun_path, m_unix_sockname.c_str());
    (void)unlink(m_unix_sockname.c_str());

    // Set socket option SO_REUSEADDR
    int option_enable = 1;
    (void)mysql_socket_setsockopt(listener_socket, SOL_SOCKET, SO_REUSEADDR,
                                  (char *)&option_enable,
                                  sizeof(option_enable));
    // bind
    umask(0);
    if (mysql_socket_bind(listener_socket,
                          reinterpret_cast<struct sockaddr *>(&UNIXaddr),
                          sizeof(UNIXaddr)) < 0) {
      LogErr(ERROR_LEVEL, ER_CONN_UNIX_NO_BIND_NO_START, strerror(errno));
      LogErr(ERROR_LEVEL, ER_CONN_UNIX_IS_THERE_ANOTHER_USING_SOCKET,
             m_unix_sockname.c_str());
      mysql_socket_close(listener_socket);
      return MYSQL_INVALID_SOCKET;
    }
    umask(((~my_umask) & 0666));

    // listen
    if (mysql_socket_listen(listener_socket, (int)m_backlog) < 0)
      LogErr(WARNING_LEVEL, ER_CONN_UNIX_LISTEN_FAILED, socket_errno);

      // set sock fd non blocking.
#if !defined(NO_FCNTL_NONBLOCK)
    (void)mysql_sock_set_nonblocking(listener_socket);
#endif

    return listener_socket;
  }
};

bool Unix_socket::create_lockfile() {
  int fd;
  char buffer[8];
  pid_t cur_pid = getpid();
  std::string lock_filename = m_unix_sockname + ".lock";

  static_assert(sizeof(pid_t) == 4, "");
  int retries = 3;
  while (true) {
    if (!retries--) {
      LogErr(ERROR_LEVEL, ER_CONN_UNIX_LOCK_FILE_GIVING_UP,
             lock_filename.c_str());
      return true;
    }

    fd = open(lock_filename.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600);

    if (fd >= 0) break;

    if (errno != EEXIST) {
      LogErr(ERROR_LEVEL, ER_CONN_UNIX_LOCK_FILE_CANT_CREATE,
             lock_filename.c_str());
      return true;
    }

    fd = open(lock_filename.c_str(), O_RDONLY, 0600);
    if (fd < 0) {
      LogErr(ERROR_LEVEL, ER_CONN_UNIX_LOCK_FILE_CANT_OPEN,
             lock_filename.c_str());
      return true;
    }

    ssize_t len;
    if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0) {
      LogErr(ERROR_LEVEL, ER_CONN_UNIX_LOCK_FILE_CANT_READ,
             lock_filename.c_str());
      close(fd);
      return true;
    }

    close(fd);

    if (len == 0) {
      LogErr(ERROR_LEVEL, ER_CONN_UNIX_LOCK_FILE_EMPTY, lock_filename.c_str());
      return true;
    }
    buffer[len] = '\0';

    pid_t parent_pid = getppid();
    pid_t read_pid = atoi(buffer);

    if (read_pid <= 0) {
      LogErr(ERROR_LEVEL, ER_CONN_UNIX_LOCK_FILE_PIDLESS,
             lock_filename.c_str());
      return true;
    }

    if (read_pid != cur_pid && read_pid != parent_pid) {
      if (kill(read_pid, 0) == 0) {
        LogErr(ERROR_LEVEL, ER_CONN_UNIX_PID_CLAIMED_SOCKET_FILE,
               static_cast<int>(read_pid));
        return true;
      }
    }

    /*
      Unlink the lock file as it is not associated with any process and
      retry.
    */
    if (unlink(lock_filename.c_str()) < 0) {
      LogErr(ERROR_LEVEL, ER_CONN_UNIX_LOCK_FILE_CANT_DELETE,
             lock_filename.c_str(), errno);
      return true;
    }
  }

  snprintf(buffer, sizeof(buffer), "%d\n", static_cast<int>(cur_pid));
  if (write(fd, buffer, strlen(buffer)) !=
      static_cast<signed>(strlen(buffer))) {
    close(fd);
    LogErr(ERROR_LEVEL, ER_CONN_UNIX_LOCK_FILE_CANT_WRITE,
           lock_filename.c_str(), errno);

    if (unlink(lock_filename.c_str()) == -1)
      LogErr(ERROR_LEVEL, ER_CONN_UNIX_LOCK_FILE_CANT_DELETE,
             lock_filename.c_str(), errno);

    return true;
  }

  if (fsync(fd) != 0) {
    close(fd);
    LogErr(ERROR_LEVEL, ER_CONN_UNIX_LOCK_FILE_CANT_SYNC, lock_filename.c_str(),
           errno);

    if (unlink(lock_filename.c_str()) == -1)
      LogErr(ERROR_LEVEL, ER_CONN_UNIX_LOCK_FILE_CANT_DELETE,
             lock_filename.c_str(), errno);

    return true;
  }

  if (close(fd) != 0) {
    LogErr(ERROR_LEVEL, ER_CONN_UNIX_LOCK_FILE_CANT_CLOSE,
           lock_filename.c_str(), errno);

    if (unlink(lock_filename.c_str()) == -1)
      LogErr(ERROR_LEVEL, ER_CONN_UNIX_LOCK_FILE_CANT_DELETE,
             lock_filename.c_str(), errno);

    return true;
  }
  return false;
}

#endif  // HAVE_SYS_UN_H

///////////////////////////////////////////////////////////////////////////
// Mysqld_socket_listener implementation
///////////////////////////////////////////////////////////////////////////

Mysqld_socket_listener::Mysqld_socket_listener(
    const std::list<Bind_address_info> &bind_addresses, uint tcp_port,
    const Bind_address_info &admin_bind_addr, uint admin_tcp_port,
    bool use_separate_thread_for_admin, uint backlog, uint port_timeout,
    std::string unix_sockname)
    : m_bind_addresses(bind_addresses),
      m_admin_bind_address(admin_bind_addr),
      m_tcp_port(tcp_port),
      m_admin_tcp_port(admin_tcp_port),
      m_use_separate_thread_for_admin(use_separate_thread_for_admin),
      m_backlog(backlog),
      m_port_timeout(port_timeout),
      m_unix_sockname(unix_sockname),
      m_unlink_sockname(false),
      m_admin_interface_listen_socket(mysql_socket_invalid()) {
#ifdef HAVE_LIBWRAP
  /*
    Set up syslog parameters on behalf of the TCP-wrappers.
    The loadable component that logs server errors to syslog
    may re-open it with user-defined attributes (logging of
    PIDS / ident) later, but we establish a sensible baseline
    here in case that log-sink is not used. Note that the
    wrapper is hard-coded to use LOG_AUTH in the syslog()
    call below, which lets the wrapper log to a different
    facility than the rest of the server (the facility of
    which defaults to LOG_DAEMON and is user-configurable)
    if desired.
  */
  libwrap_name = my_progname + dirname_length(my_progname);
  openlog(libwrap_name, LOG_PID, LOG_AUTH);
#endif /* HAVE_LIBWRAP */
}

void Mysqld_socket_listener::add_socket_to_listener(
    MYSQL_SOCKET listen_socket) {
  mysql_socket_set_thread_owner(listen_socket);

#ifdef HAVE_POLL
  m_poll_info.m_fds.emplace_back(
      pollfd{mysql_socket_getfd(listen_socket), POLLIN, 0});
  m_poll_info.m_pfs_fds.push_back(listen_socket);
#else   // HAVE_POLL
  FD_SET(mysql_socket_getfd(listen_socket), &m_select_info.m_client_fds);
  if ((uint)mysql_socket_getfd(listen_socket) >
      m_select_info.m_max_used_connection)
    m_select_info.m_max_used_connection = mysql_socket_getfd(listen_socket);
#endif  // HAVE_POLL
}

void Mysqld_socket_listener::setup_connection_events(
    const socket_vector_t &socket_vector) {
#ifdef HAVE_POLL
  const socket_vector_t::size_type total_number_of_addresses_to_bind =
      socket_vector.size();
  m_poll_info.m_fds.reserve(total_number_of_addresses_to_bind);
  m_poll_info.m_pfs_fds.reserve(total_number_of_addresses_to_bind);
#endif

  for (const auto &socket_element : socket_vector)
    add_socket_to_listener(socket_element.m_socket);
}

/**
  Accept a new connection on a ready listening socket.

  @param listen_sock  Listening socket ready to accept a new connection
  @param [out] connect_sock  Socket corresponding to a new accepted connection

  @return operation result
    @retval true on error
    @retval false on success
*/
static bool accept_connection(MYSQL_SOCKET listen_sock,
                              MYSQL_SOCKET *connect_sock) {
  struct sockaddr_storage c_addr;
  for (uint retry = 0; retry < MAX_ACCEPT_RETRY; retry++) {
    socket_len_t length = sizeof(struct sockaddr_storage);
    *connect_sock =
        mysql_socket_accept(key_socket_client_connection, listen_sock,
                            (struct sockaddr *)(&c_addr), &length);
    if (mysql_socket_getfd(*connect_sock) != INVALID_SOCKET ||
        (socket_errno != SOCKET_EINTR && socket_errno != SOCKET_EAGAIN))
      break;
  }
  if (mysql_socket_getfd(*connect_sock) == INVALID_SOCKET) {
    /*
      accept(2) failed on the listening port, after many retries.
      There is not much details to report about the client,
      increment the server global status variable.
    */

    if ((connection_errors_accept++ & 255) == 0) {  // This can happen often
#ifdef _WIN32
      Socket_error_message_buf msg_buff;
      FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, socket_errno,
                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)msg_buff,
                    sizeof(msg_buff), NULL);
      LogErr(ERROR_LEVEL, ER_CONN_SOCKET_ACCEPT_FAILED, msg_buff);
#else
      LogErr(ERROR_LEVEL, ER_CONN_SOCKET_ACCEPT_FAILED, strerror(errno));
#endif
    }
    if (socket_errno == SOCKET_ENFILE || socket_errno == SOCKET_EMFILE)
      sleep(1);  // Give other threads some time
    return true;
  }

  return false;
}

#ifdef HAVE_LIBWRAP
/**
  Ask TCP wrapper whether an accepted connection is allowed.

  @param connect_sock  Socket corresponding to accepted connection

  @return operation result
    @retval true  connection is prohibited by TCP wrapper's policy
    @retval false  connection is allowed by TCP wrapper's policy
*/
bool check_connection_refused_by_tcp_wrapper(MYSQL_SOCKET connect_sock) {
  struct request_info req;
  signal(SIGCHLD, SIG_DFL);
  request_init(&req, RQ_DAEMON, libwrap_name, RQ_FILE,
               mysql_socket_getfd(connect_sock), NULL);
  fromhost(&req);

  if (!hosts_access(&req)) {
    /*
      This may be stupid but refuse() includes an exit(0)
      which we surely don't want...
      clean_exit() - same stupid thing ...

      We're using syslog() here instead of my_syslog()
      as this lets us pass in a facility that may differ
      from that used by the error logging component.
      This is unproblematic as TCP-wrapper is unix specific,
      anyway.
    */
    syslog(LOG_AUTH | LOG_WARNING, "refused connect from %s",
           eval_client(&req));

#ifdef HAVE_LIBWRAP_PROTOTYPES
    // Some distros have patched tcpd.h to have proper prototypes
    if (req.sink) (req.sink)(req.fd);
#else
    // Some distros have not patched tcpd.h
    if (req.sink) ((void (*)(int))req.sink)(req.fd);
#endif
    /*
      The connection was refused by TCP wrappers.
      There are no details (by client IP) available to update the host_cache.
    */
    mysql_socket_shutdown(connect_sock, SHUT_RDWR);
    mysql_socket_close(connect_sock);

    connection_errors_tcpwrap++;
    return true;
  }

  return false;
}
#endif  // HAVE_LIBWRAP

static my_thread_handle admin_socket_thread_id;
static my_thread_attr_t admin_socket_thread_attrib;
static bool admin_thread_started = false;

static mysql_mutex_t LOCK_start_admin_thread;
static mysql_cond_t COND_start_admin_thread;

#ifdef HAVE_PSI_INTERFACE
static PSI_mutex_key key_LOCK_start_admin_thread;
static PSI_cond_key key_COND_start_admin_thread;

static PSI_mutex_info admin_socket_thread_mutexes[] = {
    {&key_LOCK_start_admin_thread, "LOCK_start_admin_thread",
     PSI_FLAG_SINGLETON, 0, PSI_DOCUMENT_ME}};

static PSI_cond_info admin_socket_thread_conds[] = {
    {&key_COND_start_admin_thread, "COND_start_admin_thread",
     PSI_FLAG_SINGLETON, 0, PSI_DOCUMENT_ME}};

static inline void init_psi_keys(void) {
  const char *category = "sql";
  int count = array_elements(admin_socket_thread_mutexes);
  mysql_mutex_register(category, admin_socket_thread_mutexes, count);

  count = array_elements(admin_socket_thread_conds);
  mysql_cond_register(category, admin_socket_thread_conds, count);
}
#endif

/**
  Signal to a spawning thread that spawned thread has been started.
*/
static inline void mark_admin_thread_started() {
  mysql_mutex_lock(&LOCK_start_admin_thread);
  admin_thread_started = true;
  mysql_cond_signal(&COND_start_admin_thread);
  mysql_mutex_unlock(&LOCK_start_admin_thread);
}

/**
  Wait until admin thread has started execution.
*/
static inline void wait_for_admin_thread_started() {
  mysql_mutex_lock(&LOCK_start_admin_thread);
  while (!admin_thread_started)
    mysql_cond_wait(&COND_start_admin_thread, &LOCK_start_admin_thread);
  mysql_mutex_unlock(&LOCK_start_admin_thread);
}

/**
  Listen to admin interface and accept incoming connection on it.
  This function is run in a separate thread.

  @return operation result. false on success, true on error
*/
static bool handle_admin_socket(
    /// pointer to a socket for listening to admin interface
    MYSQL_SOCKET admin_socket
#ifdef HAVE_SETNS
    ,
    /// network namespace associated with the socket
    const std::string &network_namespace_for_listening_socket
#endif
) {
  mark_admin_thread_started();

#ifdef HAVE_POLL
  static const int NUMBER_OF_POLLED_FDS = 1;
  struct pollfd fds[NUMBER_OF_POLLED_FDS] = {
      {mysql_socket_getfd(admin_socket), POLLIN, 0}};
#else
  fd_set client_fds;
  FD_ZERO(&client_fds);
  FD_SET(mysql_socket_getfd(admin_socket), &client_fds);
  int max_used_connection = mysql_socket_getfd(admin_socket);
#endif

  while (!connection_events_loop_aborted()) {
#ifdef HAVE_POLL
    int retval = poll(fds, NUMBER_OF_POLLED_FDS, -1);
#else
    fd_set read_fds = client_fds;
    int retval = select(max_used_connection, &read_fds, 0, 0, 0);
#endif

    if (retval < 0 && socket_errno != SOCKET_EINTR) {
      /*
        select(2)/poll(2) failed on the listening port.
        There is not much details to report about the client,
        increment the server global status variable.
      */
      ++connection_errors_query_block;
      if (!select_errors++ && !connection_events_loop_aborted())
        LogErr(ERROR_LEVEL, ER_CONN_SOCKET_SELECT_FAILED, socket_errno);
    }

    if (retval < 0) return true;

    if (connection_events_loop_aborted()) return false;

#ifdef HAVE_SETNS
    /*
      If a network namespace is specified for a listening socket then set this
      network namespace as active before call to accept().
      It is not clear from manuals whether a socket returned by a call to
      accept() borrows a network namespace from a server socket used for
      accepting a new connection. For that reason, assign a network namespace
      explicitly before calling accept().
    */
    if (!network_namespace_for_listening_socket.empty() &&
        set_network_namespace(network_namespace_for_listening_socket))
      return true;
#endif

    MYSQL_SOCKET connect_sock;
    bool accept_retval = accept_connection(admin_socket, &connect_sock);

#ifdef HAVE_SETNS
    if (!network_namespace_for_listening_socket.empty() &&
        restore_original_network_namespace())
      return true;
#endif

    if (accept_retval) continue;

#ifdef HAVE_LIBWRAP
    if (check_connection_refused_by_tcp_wrapper(connect_sock)) return true;
#endif  // HAVE_LIBWRAP

    Channel_info_tcpip_socket *channel_info =
        new (std::nothrow) Channel_info_tcpip_socket(connect_sock, true);
    if (channel_info == nullptr) {
      (void)mysql_socket_shutdown(connect_sock, SHUT_RDWR);
      (void)mysql_socket_close(connect_sock);
      connection_errors_internal++;
      return true;
    }

#ifdef HAVE_SETNS
    if (!network_namespace_for_listening_socket.empty())
      channel_info->set_network_namespace(
          network_namespace_for_listening_socket);
#endif

    Connection_handler_manager *mgr =
        Connection_handler_manager::get_instance();

    if (channel_info != nullptr) mgr->process_new_connection(channel_info);
  }

  return false;
}

using admin_thread_arg_t = std::pair<MYSQL_SOCKET, std::string>;

/**
  Initialize thread's internal structures, run thread loop,
  deinitialize thread's internal structure on thread exit.

  @param arg  pointer to a socket for listening to admin interface
*/
extern "C" void *admin_socket_thread(void *arg) {
  my_thread_init();

  std::unique_ptr<admin_thread_arg_t> arg_for_admin_socket_thread(
      (admin_thread_arg_t *)arg);

  (void)handle_admin_socket(arg_for_admin_socket_thread->first
#ifdef HAVE_SETNS
                            ,
                            arg_for_admin_socket_thread->second
#endif
  );

  my_thread_end();
  my_thread_exit(nullptr);

  return nullptr;
}

/**
  Initialize context required for running a thread handling connection requests
  on admin interface. Such context include mutex LOCK_start_admin_thread,
  condition variable COND_start_admin_thread and attributes used for thread
  spawning.
*/
static inline void initialize_thread_context() {
#ifdef HAVE_PSI_INTERFACE
  init_psi_keys();
#endif

  mysql_mutex_init(key_LOCK_start_admin_thread, &LOCK_start_admin_thread,
                   MY_MUTEX_INIT_FAST);
  mysql_cond_init(key_COND_start_admin_thread, &COND_start_admin_thread);

  (void)my_thread_attr_init(&admin_socket_thread_attrib);
  my_thread_attr_setdetachstate(&admin_socket_thread_attrib,
                                MY_THREAD_CREATE_JOINABLE);
#ifndef _WIN32
  pthread_attr_setscope(&admin_socket_thread_attrib, PTHREAD_SCOPE_SYSTEM);
#endif
}

/**
  Spawn a thread for handling incoming connections request on admin interface.

  @param admin_socket  A socket to listen corresponding admin interface.
  @param network_namespace Network namespace to use for communicating
                           via admin socket
  @return Operation result. false on success, true on failure.
*/
static inline bool spawn_admin_thread(MYSQL_SOCKET admin_socket,
                                      const std::string &network_namespace) {
  initialize_thread_context();

  admin_thread_arg_t *arg_for_admin_socket_thread =
      new (std::nothrow) admin_thread_arg_t(admin_socket, network_namespace);

  if (arg_for_admin_socket_thread == nullptr) return true;

  int ret = mysql_thread_create(
      key_thread_handle_con_admin_sockets, &admin_socket_thread_id,
      &admin_socket_thread_attrib, admin_socket_thread,
      (void *)arg_for_admin_socket_thread);

  (void)my_thread_attr_destroy(&admin_socket_thread_attrib);

  if (ret) {
    LogErr(ERROR_LEVEL, ER_CANT_CREATE_ADMIN_THREAD, errno);
    return true;
  }

  wait_for_admin_thread_started();

  return false;
}

bool Mysqld_socket_listener::check_and_spawn_admin_connection_handler_thread()
    const {
  if (m_use_separate_thread_for_admin) {
    if (spawn_admin_thread(m_admin_interface_listen_socket,
                           m_admin_bind_address.network_namespace))
      return true;
  }
  return false;
}

bool Mysqld_socket_listener::setup_listener() {
  /*
    It's matter to add a socket for admin connection listener firstly,
    before listening sockets for other connection types be added.
    It is done in order to check availability of new incoming connection
    on admin interface with higher priority than on other interfaces..
  */
  if (!m_admin_bind_address.address.empty()) {
    TCP_socket tcp_socket(m_admin_bind_address.address,
                          m_admin_bind_address.network_namespace,
                          m_admin_tcp_port, m_backlog, m_port_timeout);

    MYSQL_SOCKET mysql_socket = tcp_socket.get_listener_socket();
    if (mysql_socket.fd == INVALID_SOCKET) return true;

    m_admin_interface_listen_socket = mysql_socket;

    if (!m_use_separate_thread_for_admin) {
      m_socket_vector.emplace_back(mysql_socket, Socket_type::TCP_SOCKET,
                                   &m_admin_bind_address.network_namespace,
                                   Socket_interface_type::ADMIN_INTERFACE);
    }
  }

  // Setup tcp socket listener
  if (m_tcp_port) {
    for (const auto &bind_address_info : m_bind_addresses) {
      TCP_socket tcp_socket(bind_address_info.address,
                            bind_address_info.network_namespace, m_tcp_port,
                            m_backlog, m_port_timeout);

      MYSQL_SOCKET mysql_socket = tcp_socket.get_listener_socket();
      if (mysql_socket.fd == INVALID_SOCKET) return true;
      m_socket_vector.emplace_back(mysql_socket, Socket_type::TCP_SOCKET,
                                   &bind_address_info.network_namespace,
                                   Socket_interface_type::DEFAULT_INTERFACE);
    }
  }
#if defined(HAVE_SYS_UN_H)
  // Setup unix socket listener
  if (m_unix_sockname != "") {
    Unix_socket unix_socket(&m_unix_sockname, m_backlog);

    MYSQL_SOCKET mysql_socket = unix_socket.get_listener_socket();
    if (mysql_socket.fd == INVALID_SOCKET) return true;
    Listen_socket s(mysql_socket, Socket_type::UNIX_SOCKET);
    m_socket_vector.push_back(s);
    m_unlink_sockname = true;
  }
#endif /* HAVE_SYS_UN_H */

  setup_connection_events(m_socket_vector);

  return false;
}

const Listen_socket *Mysqld_socket_listener::get_listen_socket() const {
/*
  In case admin interface was set up, then first check whether an admin socket
  ready to accept a new connection. Doing this way provides higher priority
  to admin interface over other listeners.
*/
#ifdef HAVE_POLL
  uint start_index = 0;
  if (!m_admin_bind_address.address.empty() &&
      !m_use_separate_thread_for_admin) {
    if (m_poll_info.m_fds[0].revents & POLLIN) {
      return &m_socket_vector[0];
    } else
      start_index = 1;
  }

  for (uint i = start_index; i < m_socket_vector.size(); ++i) {
    if (m_poll_info.m_fds[i].revents & POLLIN) {
      return &m_socket_vector[i];
    }
  }

#else  // HAVE_POLL
  if (!m_admin_bind_address.address.empty() &&
      !m_use_separate_thread_for_admin &&
      FD_ISSET(mysql_socket_getfd(m_admin_interface_listen_socket),
               const_cast<fd_set *>(&m_select_info.m_read_fds))) {
    return &m_socket_vector[0];
  }

  for (const auto &socket_element : m_socket_vector) {
    if (FD_ISSET(mysql_socket_getfd(socket_element.m_socket),
                 const_cast<fd_set *>(&m_select_info.m_read_fds))) {
      return &socket_element;
    }
  }

#endif  // HAVE_POLL
  return nullptr;
  ;
}

Channel_info *Mysqld_socket_listener::listen_for_connection_event() {
#ifdef HAVE_POLL
  int retval = poll(&m_poll_info.m_fds[0], m_socket_vector.size(), -1);
#else
  m_select_info.m_read_fds = m_select_info.m_client_fds;
  int retval = select((int)m_select_info.m_max_used_connection,
                      &m_select_info.m_read_fds, 0, 0, 0);
#endif

  if (retval < 0 && socket_errno != SOCKET_EINTR) {
    /*
      select(2)/poll(2) failed on the listening port.
      There is not much details to report about the client,
      increment the server global status variable.
    */
    ++connection_errors_query_block;
    if (!select_errors++ && !connection_events_loop_aborted())
      LogErr(ERROR_LEVEL, ER_CONN_SOCKET_SELECT_FAILED, socket_errno);
  }

  if (retval < 0 || connection_events_loop_aborted()) return nullptr;

  /* Is this a new connection request ? */
  const Listen_socket *listen_socket = get_listen_socket();
  /*
    When poll/select returns control flow then at least one ready server socket
    must exist. Check that get_ready_socket() returns a valid socket.
  */
  assert(listen_socket != nullptr);
  MYSQL_SOCKET connect_sock;
#ifdef HAVE_SETNS
  /*
    If a network namespace is specified for a listening socket then set this
    network namespace as active before call to accept().
    It is not clear from manuals whether a socket returned by a call to
    accept() borrows a network namespace from a server socket used for
    accepting a new connection. For that reason, assign a network namespace
    explicitly before calling accept().
  */
  std::string network_namespace_for_listening_socket;
  if (listen_socket->m_socket_type == Socket_type::TCP_SOCKET) {
    network_namespace_for_listening_socket =
        (listen_socket->m_network_namespace != nullptr
             ? *listen_socket->m_network_namespace
             : std::string(""));
    if (!network_namespace_for_listening_socket.empty() &&
        set_network_namespace(network_namespace_for_listening_socket))
      return nullptr;
  }
#endif
  if (accept_connection(listen_socket->m_socket, &connect_sock)) {
#ifdef HAVE_SETNS
    if (!network_namespace_for_listening_socket.empty())
      (void)restore_original_network_namespace();
#endif
    return nullptr;
  }

#ifdef HAVE_SETNS
  if (!network_namespace_for_listening_socket.empty() &&
      restore_original_network_namespace())
    return nullptr;
#endif

#ifdef HAVE_LIBWRAP
  if ((listen_socket->m_socket_type == Socket_type::TCP_SOCKET) &&
      check_connection_refused_by_tcp_wrapper(connect_sock)) {
    return nullptr;
  }
#endif  // HAVE_LIBWRAP

  Channel_info *channel_info = nullptr;
  if (listen_socket->m_socket_type == Socket_type::UNIX_SOCKET)
    channel_info = new (std::nothrow) Channel_info_local_socket(connect_sock);
  else
    channel_info = new (std::nothrow) Channel_info_tcpip_socket(
        connect_sock, (listen_socket->m_socket_interface ==
                       Socket_interface_type::ADMIN_INTERFACE));
  if (channel_info == nullptr) {
    (void)mysql_socket_shutdown(connect_sock, SHUT_RDWR);
    (void)mysql_socket_close(connect_sock);
    connection_errors_internal++;
    return nullptr;
  }

#ifdef HAVE_SETNS
  if (listen_socket->m_socket_type == Socket_type::TCP_SOCKET &&
      !network_namespace_for_listening_socket.empty())
    static_cast<Channel_info_tcpip_socket *>(channel_info)
        ->set_network_namespace(network_namespace_for_listening_socket);
#endif
  return channel_info;
}

void Mysqld_socket_listener::close_listener() {
  for (const auto &socket_element : m_socket_vector) {
    (void)mysql_socket_shutdown(socket_element.m_socket, SHUT_RDWR);
    (void)mysql_socket_close(socket_element.m_socket);
  }

  /*
    In case a separate thread was spawned to handle incoming connection
    requests on admin interface, a socket corresponding to an admin interface
    being listened is not included in the m_socket_map. Instead, this socket
    referenced by the data member m_admin_interface_listen_socket.
  */
  if (m_use_separate_thread_for_admin) {
    if (admin_socket_thread_id != my_thread_handle{}) {
#ifdef _WIN32
      /*
        For Windows, first close the socket referenced by the data member
        m_admin_interface_listen_socket. It results in return from select()
        API call running from a separate thread.
      */
      (void)mysql_socket_close(m_admin_interface_listen_socket);
      m_admin_interface_listen_socket.fd = INVALID_SOCKET;
      my_thread_join(&admin_socket_thread_id, nullptr);
#else
      // First, finish listening thread.
      pthread_kill(admin_socket_thread_id.thread, SIGALRM);
      my_thread_join(&admin_socket_thread_id, nullptr);

#endif
      mysql_mutex_destroy(&LOCK_start_admin_thread);
      mysql_cond_destroy(&COND_start_admin_thread);
    }  // if (admin_socket_thread_id != my_thread_handle{})
    /*
      After a thread listening on admin interface finished, it is safe
      to close listening socket. But socket is opened before thread is
      spawned, so we may need to close the socket even if
      admin_socket_thread_id has not been assigned.
    */
    if (m_admin_interface_listen_socket.fd != INVALID_SOCKET) {
      (void)mysql_socket_close(m_admin_interface_listen_socket);
      m_admin_interface_listen_socket.fd = INVALID_SOCKET;
    }
  }  // use_separate_thread_for_admin

#if defined(HAVE_SYS_UN_H)
  if (m_unix_sockname != "" && m_unlink_sockname) {
    std::string lock_filename = m_unix_sockname + ".lock";
    (void)unlink(lock_filename.c_str());
    (void)unlink(m_unix_sockname.c_str());
  }
#endif

#ifdef HAVE_SETNS
  release_network_namespace_resources();
#endif

  m_socket_vector.clear();
  m_bind_addresses.clear();
}