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
| /**
* MySQL客户端-服务器协议处理器
* 负责处理MySQL网络协议的各个阶段
*/
class Protocol_classic {
private:
THD *thd; ///< 关联的线程句柄
NET *net; ///< 网络连接对象
String packet; ///< 数据包缓冲区
uint client_capabilities; ///< 客户端能力标志
// 压缩相关
bool compression_enabled; ///< 是否启用压缩
uint32_t compress_threshold; ///< 压缩阈值
public:
/**
* 构造函数:初始化协议处理器
* @param thd_arg 线程句柄
*/
Protocol_classic(THD *thd_arg) : thd(thd_arg), net(&thd_arg->net),
compression_enabled(false),
compress_threshold(50) {
client_capabilities = 0;
}
/**
* 发送握手包给客户端
* MySQL协议的第一个步骤:服务器向客户端发送握手包
* @return true表示成功,false表示失败
*/
bool send_handshake_packet() {
// 构造握手包结构
String handshake_packet;
// 1. 协议版本号(1字节)
handshake_packet.append(static_cast<char>(PROTOCOL_VERSION));
// 2. 服务器版本字符串(以NULL结尾)
handshake_packet.append(MYSQL_SERVER_VERSION);
handshake_packet.append('\0');
// 3. 连接ID(4字节小端序)
uint32_t connection_id = thd->thread_id();
handshake_packet.append(reinterpret_cast<char*>(&connection_id), 4);
// 4. 认证插件数据第一部分(8字节)
char auth_plugin_data[21]; // 20字节随机数据 + 1字节NULL
generate_random_string(auth_plugin_data, 20);
handshake_packet.append(auth_plugin_data, 8);
handshake_packet.append('\0'); // 填充字节
// 5. 服务器能力标志低16位
uint32_t server_capabilities = get_server_capabilities();
uint16_t capability_flags_1 = server_capabilities & 0xFFFF;
handshake_packet.append(reinterpret_cast<char*>(&capability_flags_1), 2);
// 6. 服务器字符集(1字节)
uint8_t charset = default_charset_info->number;
handshake_packet.append(static_cast<char>(charset));
// 7. 服务器状态标志(2字节)
uint16_t status_flags = thd->server_status;
handshake_packet.append(reinterpret_cast<char*>(&status_flags), 2);
// 8. 服务器能力标志高16位
uint16_t capability_flags_2 = (server_capabilities >> 16) & 0xFFFF;
handshake_packet.append(reinterpret_cast<char*>(&capability_flags_2), 2);
// 9. 认证插件数据长度
uint8_t auth_plugin_data_len = 21;
handshake_packet.append(static_cast<char>(auth_plugin_data_len));
// 10. 保留字节(10字节)
for (int i = 0; i < 10; i++) {
handshake_packet.append('\0');
}
// 11. 认证插件数据第二部分(12字节)
handshake_packet.append(auth_plugin_data + 8, 12);
handshake_packet.append('\0');
// 12. 认证插件名称
handshake_packet.append("mysql_native_password");
handshake_packet.append('\0');
// 发送握手包
return write_packet(handshake_packet.ptr(), handshake_packet.length());
}
/**
* 处理客户端认证响应
* @return true表示认证成功,false表示认证失败
*/
bool handle_auth_response() {
// 1. 读取客户端响应包
ulong packet_length = read_packet();
if (packet_length == packet_error) {
return false;
}
char *packet_data = reinterpret_cast<char*>(net->read_pos);
// 2. 解析客户端能力标志(4字节)
if (packet_length < 4) {
return false;
}
client_capabilities = uint4korr(packet_data);
// 3. 解析最大包大小(4字节)
if (packet_length < 8) {
return false;
}
uint32_t max_packet_size = uint4korr(packet_data + 4);
thd->variables.max_allowed_packet = max_packet_size;
// 4. 解析客户端字符集(1字节)
if (packet_length < 9) {
return false;
}
uint8_t client_charset = packet_data[8];
// 5. 跳过保留字节(23字节)
size_t offset = 9 + 23;
if (packet_length <= offset) {
return false;
}
// 6. 解析用户名(以NULL结尾的字符串)
const char *username = packet_data + offset;
size_t username_len = strlen(username);
offset += username_len + 1;
// 7. 解析认证响应数据
if (packet_length <= offset) {
return false;
}
uint8_t auth_response_len = packet_data[offset++];
if (packet_length < offset + auth_response_len) {
return false;
}
const char *auth_response = packet_data + offset;
offset += auth_response_len;
// 8. 解析数据库名(可选)
const char *database = nullptr;
if (offset < packet_length && (client_capabilities & CLIENT_CONNECT_WITH_DB)) {
database = packet_data + offset;
}
// 9. 执行用户认证
Security_context *sctx = thd->security_context();
return authenticate_user(sctx, username, auth_response,
auth_response_len, database);
}
/**
* 读取客户端数据包
* @return 包长度,错误时返回packet_error
*/
ulong read_packet() {
return my_net_read(net);
}
/**
* 向客户端写入数据包
* @param packet 数据包内容
* @param length 数据包长度
* @return true表示成功,false表示失败
*/
bool write_packet(const char *packet, size_t length) {
return my_net_write(net, reinterpret_cast<const uchar*>(packet), length);
}
/**
* 发送OK包
* @param affected_rows 影响的行数
* @param last_insert_id 最后插入的ID
* @param server_status 服务器状态
* @param warning_count 警告数量
* @return true表示成功,false表示失败
*/
bool send_ok_packet(ulonglong affected_rows = 0,
ulonglong last_insert_id = 0,
uint server_status = 0,
uint warning_count = 0) {
String ok_packet;
// OK包标志字节
ok_packet.append('\0');
// 影响行数(长度编码整数)
append_length_encoded_integer(ok_packet, affected_rows);
// 最后插入ID(长度编码整数)
append_length_encoded_integer(ok_packet, last_insert_id);
// 服务器状态标志(2字节)
uint16_t status = server_status;
ok_packet.append(reinterpret_cast<char*>(&status), 2);
// 警告数量(2字节)
uint16_t warnings = warning_count;
ok_packet.append(reinterpret_cast<char*>(&warnings), 2);
return write_packet(ok_packet.ptr(), ok_packet.length());
}
/**
* 发送错误包
* @param sql_errno SQL错误码
* @param err 错误消息
* @return true表示成功,false表示失败
*/
bool send_error_packet(uint sql_errno, const char *err) {
String error_packet;
// 错误包标志字节
error_packet.append('\xff');
// 错误码(2字节小端序)
uint16_t error_code = sql_errno;
error_packet.append(reinterpret_cast<char*>(&error_code), 2);
// SQL状态标记(如果客户端支持)
if (client_capabilities & CLIENT_PROTOCOL_41) {
error_packet.append('#');
error_packet.append("HY000"); // 通用SQL状态
}
// 错误消息
error_packet.append(err);
return write_packet(error_packet.ptr(), error_packet.length());
}
private:
/**
* 获取服务器能力标志
*/
uint32_t get_server_capabilities() const {
uint32_t capabilities = 0;
capabilities |= CLIENT_LONG_PASSWORD; // 新的更安全的密码
capabilities |= CLIENT_FOUND_ROWS; // 返回找到的行数而不是影响的行数
capabilities |= CLIENT_LONG_FLAG; // 获取所有列标志
capabilities |= CLIENT_CONNECT_WITH_DB; // 可以在连接时指定数据库
capabilities |= CLIENT_NO_SCHEMA; // 不允许database.table.column语法
capabilities |= CLIENT_COMPRESS; // 可以使用压缩协议
capabilities |= CLIENT_LOCAL_FILES; // 可以使用LOAD DATA LOCAL
capabilities |= CLIENT_PROTOCOL_41; // 新的4.1协议
capabilities |= CLIENT_INTERACTIVE; // 支持交互式超时
capabilities |= CLIENT_SSL; // 支持SSL
capabilities |= CLIENT_TRANSACTIONS; // 客户端知道事务
capabilities |= CLIENT_SECURE_CONNECTION; // 新的4.1认证
capabilities |= CLIENT_MULTI_STATEMENTS; // 启用/禁用多语句支持
capabilities |= CLIENT_MULTI_RESULTS; // 启用/禁用多结果支持
capabilities |= CLIENT_PS_MULTI_RESULTS; // 多结果集预处理语句
capabilities |= CLIENT_PLUGIN_AUTH; // 客户端支持插件认证
capabilities |= CLIENT_CONNECT_ATTRS; // 连接属性
capabilities |= CLIENT_SESSION_TRACK; // 会话状态跟踪
capabilities |= CLIENT_DEPRECATE_EOF; // 弃用EOF包
return capabilities;
}
/**
* 生成随机字符串(用于认证盐值)
* @param buffer 输出缓冲区
* @param length 字符串长度
*/
void generate_random_string(char *buffer, size_t length) {
static const char charset[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for (size_t i = 0; i < length; i++) {
buffer[i] = charset[rand() % (sizeof(charset) - 1)];
}
buffer[length] = '\0';
}
/**
* 追加长度编码整数到包中
* @param packet 数据包对象
* @param value 要编码的整数值
*/
void append_length_encoded_integer(String &packet, ulonglong value) {
if (value < 251) {
packet.append(static_cast<char>(value));
} else if (value < 65536) {
packet.append('\xfc');
uint16_t val = static_cast<uint16_t>(value);
packet.append(reinterpret_cast<char*>(&val), 2);
} else if (value < 16777216) {
packet.append('\xfd');
packet.append(reinterpret_cast<char*>(&value), 3);
} else {
packet.append('\xfe');
packet.append(reinterpret_cast<char*>(&value), 8);
}
}
};
/**
* 连接处理主函数
* 这是每个连接线程的核心处理循环
* @param thd 线程句柄
*/
void handle_connection(THD *thd) {
// 1. 获取网络连接信息
NET *net = &thd->net;
Protocol_classic *protocol = thd->get_protocol_classic();
// 2. 发送握手包
if (!protocol->send_handshake_packet()) {
LogErr(ERROR_LEVEL, ER_HANDSHAKE_ERROR);
return;
}
// 3. 处理认证
if (!protocol->handle_auth_response()) {
LogErr(WARNING_LEVEL, ER_ACCESS_DENIED_ERROR,
thd->security_context()->priv_user().str,
thd->security_context()->priv_host().str,
"YES");
return;
}
// 4. 认证成功,发送OK包
if (!protocol->send_ok_packet()) {
return;
}
// 5. 进入命令处理循环
thd->proc_info = "等待命令";
NET_SERVER server_extension;
server_extension.thd = thd;
net->extension = &server_extension;
while (!net->error && net->vio != nullptr && !thd->killed) {
// 读取客户端命令
if (do_command(thd)) {
break; // 出错或客户端断开连接
}
}
// 6. 清理连接资源
thd->proc_info = "清理";
end_connection(thd);
}
/**
* 执行客户端命令
* 解析并执行客户端发送的各种命令类型
* @param thd 线程句柄
* @return true表示连接应该关闭,false表示继续处理
*/
bool do_command(THD *thd) {
// 1. 读取命令包
NET *net = &thd->net;
thd->proc_info = "等待查询";
ulong packet_length = my_net_read(net);
if (packet_length == packet_error) {
// 网络错误或客户端断开
LogDebug(GENERAL_LOG, "Client disconnected");
return true;
}
// 2. 解析命令类型
enum enum_server_command command =
static_cast<enum_server_command>(net->read_pos[0]);
// 3. 更新统计信息
thd->inc_status_var(thd->status_var.questions);
// 4. 根据命令类型分派处理
COM_DATA com_data;
if (!parse_com_data(net->read_pos, packet_length, &com_data)) {
// 解析命令数据失败
my_error(ER_MALFORMED_PACKET, MYF(0));
return true;
}
// 5. 分派命令执行
return dispatch_command(thd, &com_data, command);
}
/**
* 分派命令执行
* 根据命令类型调用相应的处理函数
* @param thd 线程句柄
* @param com_data 命令数据
* @param command 命令类型
* @return true表示连接应该关闭,false表示继续处理
*/
bool dispatch_command(THD *thd, const COM_DATA *com_data,
enum enum_server_command command) {
thd->set_command(command);
switch (command) {
case COM_INIT_DB:
// 切换数据库命令
return mysql_change_db(thd, com_data->com_init_db.db_name, false);
case COM_QUERY:
// SQL查询命令
return mysql_parse(thd, com_data->com_query.query,
com_data->com_query.length);
case COM_FIELD_LIST:
// 字段列表命令(已弃用)
return mysql_list_fields(thd, com_data->com_field_list.table_name,
com_data->com_field_list.query);
case COM_QUIT:
// 退出命令
LogDebug(GENERAL_LOG, "Client requested quit");
return true;
case COM_STATISTICS:
// 统计信息命令
return mysql_statistics(thd);
case COM_PING:
// Ping命令
return send_ok_packet(thd);
case COM_STMT_PREPARE:
// 预处理语句准备
return mysql_stmt_prepare(thd, com_data->com_stmt_prepare.query,
com_data->com_stmt_prepare.length);
case COM_STMT_EXECUTE:
// 预处理语句执行
return mysql_stmt_execute(thd, com_data->com_stmt_execute.stmt_id,
com_data->com_stmt_execute.flags,
com_data->com_stmt_execute.params,
com_data->com_stmt_execute.params_length);
case COM_STMT_CLOSE:
// 预处理语句关闭
mysql_stmt_close(thd, com_data->com_stmt_close.stmt_id);
return false;
case COM_RESET_CONNECTION:
// 重置连接状态
return mysql_reset_connection(thd);
default:
// 不支持的命令
my_error(ER_UNKNOWN_COM_ERROR, MYF(0));
return true;
}
}
|