forked from facebook/mysql-5.6
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket_connection.cc
1512 lines (1287 loc) · 49.2 KB
/
socket_connection.cc
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
/*
Copyright (c) 2013, 2022, 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 also distributed 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 included with MySQL.
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()) {
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_start_index(0),
m_next_index(0),
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