MySQLProtocol.h 16.6 KB
Newer Older
Y
draft  
Yuriy 已提交
1 2
#pragma once

3
#include <IO/ReadBuffer.h>
Y
draft  
Yuriy 已提交
4
#include <IO/WriteBuffer.h>
5 6
#include <IO/copyData.h>
#include <Core/Types.h>
Y
draft  
Yuriy 已提交
7 8 9 10 11
#include <random>
#include <sstream>

/// Implementation of MySQL wire protocol

12 13 14 15 16 17 18 19 20 21
namespace DB
{

namespace ErrorCodes
{
    extern const int UNKNOWN_PACKET_FROM_CLIENT;
}

namespace MySQLProtocol
{
Y
draft  
Yuriy 已提交
22 23 24 25 26 27

const size_t MAX_PACKET_LENGTH = (1 << 24) - 1; // 16 mb
const size_t SCRAMBLE_LENGTH = 20;
const size_t AUTH_PLUGIN_DATA_PART_1_LENGTH = 8;
const size_t MYSQL_ERRMSG_SIZE = 512;

28 29 30
namespace Authentication
{
    const String ClearText = "mysql_clear_password";
Y
draft  
Yuriy 已提交
31 32
}

33 34 35 36
enum CharacterSet
{
    utf8_general_ci = 33,
    binary = 63
Y
draft  
Yuriy 已提交
37 38
};

39 40
enum StatusFlags
{
Y
draft  
Yuriy 已提交
41 42 43
    SERVER_SESSION_STATE_CHANGED = 0x4000
};

44 45
enum Capability
{
Y
draft  
Yuriy 已提交
46 47 48 49 50 51 52 53 54 55
    CLIENT_CONNECT_WITH_DB = 0x00000008,
    CLIENT_PROTOCOL_41 = 0x00000200,
    CLIENT_TRANSACTIONS = 0x00002000, // TODO
    CLIENT_SESSION_TRACK = 0x00800000, // TODO
    CLIENT_SECURE_CONNECTION = 0x00008000,
    CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA = 0x00200000,
    CLIENT_PLUGIN_AUTH = 0x00080000,
    CLIENT_DEPRECATE_EOF = 0x01000000,
};

56 57
enum Command
{
Y
draft  
Yuriy 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    COM_SLEEP = 0x0,
    COM_QUIT = 0x1,
    COM_INIT_DB = 0x2,
    COM_QUERY = 0x3,
    COM_FIELD_LIST = 0x4,
    COM_CREATE_DB = 0x5,
    COM_DROP_DB = 0x6,
    COM_REFRESH = 0x7,
    COM_SHUTDOWN = 0x8,
    COM_STATISTICS = 0x9,
    COM_PROCESS_INFO = 0xa,
    COM_CONNECT = 0xb,
    COM_PROCESS_KILL = 0xc,
    COM_DEBUG = 0xd,
    COM_PING = 0xe,
    COM_TIME = 0xf,
    COM_DELAYED_INSERT = 0x10,
    COM_CHANGE_USER = 0x11,
    COM_RESET_CONNECTION = 0x1f,
    COM_DAEMON = 0x1d
};

80 81
enum ColumnType
{
Y
draft  
Yuriy 已提交
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
    MYSQL_TYPE_DECIMAL = 0x00,
    MYSQL_TYPE_TINY = 0x01,
    MYSQL_TYPE_SHORT = 0x02,
    MYSQL_TYPE_LONG = 0x03,
    MYSQL_TYPE_FLOAT = 0x04,
    MYSQL_TYPE_DOUBLE = 0x05,
    MYSQL_TYPE_NULL = 0x06,
    MYSQL_TYPE_TIMESTAMP = 0x07,
    MYSQL_TYPE_LONGLONG = 0x08,
    MYSQL_TYPE_INT24 = 0x09,
    MYSQL_TYPE_DATE = 0x0a,
    MYSQL_TYPE_TIME = 0x0b,
    MYSQL_TYPE_DATETIME = 0x0c,
    MYSQL_TYPE_YEAR = 0x0d,
    MYSQL_TYPE_VARCHAR = 0x0f,
    MYSQL_TYPE_BIT = 0x10,
    MYSQL_TYPE_NEWDECIMAL = 0xf6,
    MYSQL_TYPE_ENUM = 0xf7,
    MYSQL_TYPE_SET = 0xf8,
    MYSQL_TYPE_TINY_BLOB = 0xf9,
    MYSQL_TYPE_MEDIUM_BLOB = 0xfa,
    MYSQL_TYPE_LONG_BLOB = 0xfb,
    MYSQL_TYPE_BLOB = 0xfc,
    MYSQL_TYPE_VAR_STRING = 0xfd,
    MYSQL_TYPE_STRING = 0xfe,
    MYSQL_TYPE_GEOMETRY = 0xff
};


111 112 113 114 115 116 117 118 119 120 121
class ProtocolError : public DB::Exception
{
public:
    using Exception::Exception;
};


class WritePacket
{
public:
    virtual String getPayload() const = 0;
Y
draft  
Yuriy 已提交
122

123 124
    virtual ~WritePacket() = default;
};
Y
draft  
Yuriy 已提交
125 126


127 128
class ReadPacket
{
Y
draft  
Yuriy 已提交
129
public:
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
    virtual void readPayload(String payload) = 0;

    virtual ~ReadPacket() = default;
};


/* Writes and reads packets, keeping sequence-id.
 * Throws ProtocolError, if packet with incorrect sequence-id was received.
 */
class PacketSender
{
public:
    PacketSender()
    {}

    PacketSender(std::shared_ptr<ReadBuffer> in, std::shared_ptr<WriteBuffer> out)
        : in(std::move(in)), out(std::move(out)), sequence_id(0), log(&Poco::Logger::get("MySQLHandler"))
    {
    }

    String receivePacketPayload()
    {
        WriteBufferFromOwnString buf;

        size_t payload_length = 0;
        size_t packet_sequence_id = 0;

        // packets which are larger than or equal to 16MB are splitted
        do
        {
            LOG_TRACE(log, "Reading from buffer");

            in->readStrict(reinterpret_cast<char *>(&payload_length), 3);

            if (payload_length > MAX_PACKET_LENGTH)
            {
                std::ostringstream tmp;
                tmp << "Received packet with payload larger than MAX_PACKET_LENGTH: " << payload_length;
                throw ProtocolError(tmp.str(), ErrorCodes::UNKNOWN_PACKET_FROM_CLIENT);
            }

            in->readStrict(reinterpret_cast<char *>(&packet_sequence_id), 1);

            if (packet_sequence_id != sequence_id)
            {
                std::ostringstream tmp;
                tmp << "Received packet with wrong sequence-id: " << packet_sequence_id << ". Expected: " << sequence_id << '.';
                throw ProtocolError(tmp.str(), ErrorCodes::UNKNOWN_PACKET_FROM_CLIENT);
            }
            sequence_id++;

            LOG_TRACE(log, "Received packet. Sequence-id: " << packet_sequence_id << ", payload length: " << payload_length);

            copyData(*in, static_cast<WriteBuffer &>(buf), payload_length);
        } while (payload_length == MAX_PACKET_LENGTH);

        return std::move(buf.str());
    }

    template<typename T>
    T receivePacket()
    {
        static_assert(std::is_base_of<ReadPacket, T>());
        T packet;
        packet.readPayload(std::move(receivePacketPayload()));
        return packet;
    }

    template<class T>
    void sendPacket(const T & packet, bool flush = false)
    {
        static_assert(std::is_base_of<WritePacket, T>());
        String payload = packet.getPayload();
        size_t pos = 0;
        do
        {
            size_t payload_length = std::min(payload.length() - pos, MAX_PACKET_LENGTH);

            LOG_TRACE(log, "Writing packet of size " << payload_length << " with sequence-id " << static_cast<int>(sequence_id));
            LOG_TRACE(log, packetToText(payload));

            out->write(reinterpret_cast<const char *>(&payload_length), 3);
            out->write(reinterpret_cast<const char *>(&sequence_id), 1);
            out->write(payload.data() + pos, payload_length);

            pos += payload_length;
            sequence_id++;
        } while (pos < payload.length());

        LOG_TRACE(log, "Packet was sent.");

        if (flush)
        {
            out->next();
        }
    }

    /// Sets sequence-id to 0. Must be called before each command phase.
    void resetSequenceId();

private:
    /// Converts packet to text. Is used for debug output.
    static String packetToText(String payload);

    std::shared_ptr<ReadBuffer> in;
    std::shared_ptr<WriteBuffer> out;
    size_t sequence_id;
    Poco::Logger * log;
Y
draft  
Yuriy 已提交
238 239 240
};


241
uint64_t readLengthEncodedNumber(std::istringstream & ss);
Y
draft  
Yuriy 已提交
242

243
String writeLengthEncodedNumber(uint64_t x);
Y
draft  
Yuriy 已提交
244

245 246 247 248 249 250 251
void writeLengthEncodedString(String & payload, const String & s);

void writeNulTerminatedString(String & payload, const String & s);


class Handshake : public WritePacket
{
Y
draft  
Yuriy 已提交
252
    int protocol_version = 0xa;
253
    String server_version;
Y
draft  
Yuriy 已提交
254 255 256 257
    uint32_t connection_id;
    uint32_t capability_flags;
    uint8_t character_set;
    uint32_t status_flags;
258
    String auth_plugin_data;
Y
draft  
Yuriy 已提交
259
public:
260 261 262 263 264 265 266 267 268
    explicit Handshake(uint32_t connection_id, String server_version)
        : protocol_version(0xa), server_version(std::move(server_version)), connection_id(connection_id), capability_flags(
        CLIENT_PROTOCOL_41
        | CLIENT_SECURE_CONNECTION
        | CLIENT_PLUGIN_AUTH
        | CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA
        | CLIENT_CONNECT_WITH_DB
        | CLIENT_DEPRECATE_EOF), character_set(63), status_flags(0)
    {
Y
draft  
Yuriy 已提交
269 270 271
        auth_plugin_data.resize(SCRAMBLE_LENGTH);
    }

272 273 274
    String getPayload() const override
    {
        String result;
Y
draft  
Yuriy 已提交
275
        result.append(1, protocol_version);
276
        writeNulTerminatedString(result, server_version);
Y
draft  
Yuriy 已提交
277
        result.append(reinterpret_cast<const char *>(&connection_id), 4);
278
        writeNulTerminatedString(result, auth_plugin_data.substr(0, AUTH_PLUGIN_DATA_PART_1_LENGTH));
Y
draft  
Yuriy 已提交
279 280 281 282 283 284 285 286
        result.append(reinterpret_cast<const char *>(&capability_flags), 2);
        result.append(reinterpret_cast<const char *>(&character_set), 1);
        result.append(reinterpret_cast<const char *>(&status_flags), 2);
        result.append((reinterpret_cast<const char *>(&capability_flags)) + 2, 2);
        result.append(1, SCRAMBLE_LENGTH + 1);
        result.append(1, 0x0);
        result.append(10, 0x0);
        result.append(auth_plugin_data.substr(AUTH_PLUGIN_DATA_PART_1_LENGTH, SCRAMBLE_LENGTH - AUTH_PLUGIN_DATA_PART_1_LENGTH));
287
        result.append(Authentication::ClearText);
Y
draft  
Yuriy 已提交
288 289 290 291 292
        result.append(1, 0x0);
        return result;
    }
};

293 294
class HandshakeResponse : public ReadPacket
{
Y
draft  
Yuriy 已提交
295 296 297 298
public:
    uint32_t capability_flags;
    uint32_t max_packet_size;
    uint8_t character_set;
299 300 301 302
    String username;
    String auth_response;
    String database;
    String auth_plugin_name;
Y
draft  
Yuriy 已提交
303

Y
Yuriy 已提交
304 305 306 307
    HandshakeResponse() = default;

    HandshakeResponse(const HandshakeResponse &) = default;

308 309
    void readPayload(String s) override
    {
Y
draft  
Yuriy 已提交
310 311 312 313 314 315 316 317 318
        std::istringstream ss(s);

        ss.readsome(reinterpret_cast<char *>(&capability_flags), 4);
        ss.readsome(reinterpret_cast<char *>(&max_packet_size), 4);
        ss.readsome(reinterpret_cast<char *>(&character_set), 1);
        ss.ignore(23);

        std::getline(ss, username, static_cast<char>(0x0));

319 320 321
        if (capability_flags & CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA)
        {
            auto len = readLengthEncodedNumber(ss);
Y
draft  
Yuriy 已提交
322 323
            auth_response.resize(len);
            ss.read(auth_response.data(), static_cast<std::streamsize>(len));
324 325 326
        }
        else if (capability_flags & CLIENT_SECURE_CONNECTION)
        {
Y
draft  
Yuriy 已提交
327 328 329 330
            uint8_t len;
            ss.read(reinterpret_cast<char *>(&len), 1);
            auth_response.resize(len);
            ss.read(auth_response.data(), len);
331 332 333
        }
        else
        {
Y
draft  
Yuriy 已提交
334 335 336
            std::getline(ss, auth_response, static_cast<char>(0x0));
        }

337 338
        if (capability_flags & CLIENT_CONNECT_WITH_DB)
        {
Y
draft  
Yuriy 已提交
339 340 341
            std::getline(ss, database, static_cast<char>(0x0));
        }

342 343
        if (capability_flags & CLIENT_PLUGIN_AUTH)
        {
Y
draft  
Yuriy 已提交
344 345 346 347 348
            std::getline(ss, auth_plugin_name, static_cast<char>(0x0));
        }
    }
};

349 350 351 352 353 354 355 356 357 358 359 360 361 362
class AuthSwitchRequest : public WritePacket
{
    String plugin_name;
    String auth_plugin_data;
public:
    AuthSwitchRequest(String plugin_name, String auth_plugin_data)
        : plugin_name(std::move(plugin_name)), auth_plugin_data(std::move(auth_plugin_data))
    {
    }

    String getPayload() const override
    {
        String result;
        result.append(1, 0xfe);
Y
Yuriy 已提交
363
        writeNulTerminatedString(result, plugin_name);
364 365 366 367 368 369 370 371 372 373 374
        result.append(auth_plugin_data);
        return result;
    }
};

/// Packet with a single null-terminated string. Is used for clear text authentication.
class NullTerminatedString : public ReadPacket
{
public:
    String value;

Y
Yuriy 已提交
375 376 377 378
    NullTerminatedString() = default;

    NullTerminatedString(const NullTerminatedString &) = default;

379 380 381 382 383 384 385 386 387 388 389 390 391
    void readPayload(String s) override
    {
        if (s.length() == 0 || s.back() != 0)
        {
            throw ProtocolError("String is not null terminated.", ErrorCodes::UNKNOWN_PACKET_FROM_CLIENT);
        }
        value = s;
        value.pop_back();
    }
};

class OK_Packet : public WritePacket
{
Y
draft  
Yuriy 已提交
392 393 394 395 396 397
    uint8_t header;
    uint32_t capabilities;
    uint64_t affected_rows;
    uint64_t last_insert_id;
    int16_t warnings = 0;
    uint32_t status_flags;
398 399
    String info;
    String session_state_changes;
Y
draft  
Yuriy 已提交
400 401
public:
    OK_Packet(uint8_t header, uint32_t capabilities, uint64_t affected_rows, uint64_t last_insert_id, uint32_t status_flags,
402 403 404
              int16_t warnings, String session_state_changes)
        : header(header), capabilities(capabilities), affected_rows(affected_rows), last_insert_id(last_insert_id), warnings(warnings),
          status_flags(status_flags), session_state_changes(std::move(session_state_changes))
Y
draft  
Yuriy 已提交
405 406 407
    {
    }

408 409 410
    String getPayload() const override
    {
        String result;
Y
draft  
Yuriy 已提交
411
        result.append(1, header);
412 413
        result.append(writeLengthEncodedNumber(affected_rows));
        result.append(writeLengthEncodedNumber(last_insert_id));
Y
draft  
Yuriy 已提交
414

415 416
        if (capabilities & CLIENT_PROTOCOL_41)
        {
Y
draft  
Yuriy 已提交
417 418
            result.append(reinterpret_cast<const char *>(&status_flags), 2);
            result.append(reinterpret_cast<const char *>(&warnings), 2);
419 420 421
        }
        else if (capabilities & CLIENT_TRANSACTIONS)
        {
Y
draft  
Yuriy 已提交
422 423 424
            result.append(reinterpret_cast<const char *>(&status_flags), 2);
        }

425 426 427
        if (capabilities & CLIENT_SESSION_TRACK)
        {
            result.append(writeLengthEncodedNumber(info.length()));
Y
draft  
Yuriy 已提交
428
            result.append(info);
429 430 431
            if (status_flags & SERVER_SESSION_STATE_CHANGED)
            {
                result.append(writeLengthEncodedNumber(session_state_changes.length()));
Y
draft  
Yuriy 已提交
432 433
                result.append(session_state_changes);
            }
434 435 436
        }
        else
        {
Y
draft  
Yuriy 已提交
437 438 439 440 441 442
            result.append(info);
        }
        return result;
    }
};

443 444
class EOF_Packet : public WritePacket
{
Y
draft  
Yuriy 已提交
445 446 447
    int warnings;
    int status_flags;
public:
448 449
    EOF_Packet(int warnings, int status_flags) : warnings(warnings), status_flags(status_flags)
    {}
Y
draft  
Yuriy 已提交
450

451 452 453
    String getPayload() const override
    {
        String result;
Y
draft  
Yuriy 已提交
454 455 456 457 458 459 460
        result.append(1, 0xfe); // EOF header
        result.append(reinterpret_cast<const char *>(&warnings), 2);
        result.append(reinterpret_cast<const char *>(&status_flags), 2);
        return result;
    }
};

461 462
class ERR_Packet : public WritePacket
{
Y
draft  
Yuriy 已提交
463
    int error_code;
464 465
    String sql_state;
    String error_message;
Y
draft  
Yuriy 已提交
466
public:
467 468
    ERR_Packet(int error_code, String sql_state, String error_message)
        : error_code(error_code), sql_state(std::move(sql_state)), error_message(std::move(error_message))
Y
draft  
Yuriy 已提交
469 470 471
    {
    }

472
    String getPayload() const override
Y
draft  
Yuriy 已提交
473
    {
474
        String result;
Y
draft  
Yuriy 已提交
475 476 477 478 479 480 481 482 483
        result.append(1, 0xff);
        result.append(reinterpret_cast<const char *>(&error_code), 2);
        result.append("#", 1);
        result.append(sql_state.data(), sql_state.length());
        result.append(error_message.data(), std::min(error_message.length(), MYSQL_ERRMSG_SIZE));
        return result;
    }
};

484 485 486 487 488 489 490
class ColumnDefinition : public WritePacket
{
    String schema;
    String table;
    String org_table;
    String name;
    String org_name;
Y
draft  
Yuriy 已提交
491 492 493 494 495 496 497
    size_t next_length = 0x0c;
    uint16_t character_set;
    uint32_t column_length;
    ColumnType column_type;
    uint16_t flags;
    uint8_t decimals = 0x00;
public:
498 499 500 501 502 503
    ColumnDefinition(
        String schema,
        String table,
        String org_table,
        String name,
        String org_name,
Y
draft  
Yuriy 已提交
504 505 506 507 508 509
        uint16_t character_set,
        uint32_t column_length,
        ColumnType column_type,
        uint16_t flags,
        uint8_t decimals)

510 511 512
        : schema(std::move(schema)), table(std::move(table)), org_table(std::move(org_table)), name(std::move(name)),
          org_name(std::move(org_name)), character_set(character_set), column_length(column_length), column_type(column_type), flags(flags),
          decimals(decimals)
Y
draft  
Yuriy 已提交
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
    /// Should be used when column metadata (original name, table, original table, database) is unknown.
    ColumnDefinition(
        String name,
        uint16_t character_set,
        uint32_t column_length,
        ColumnType column_type,
        uint16_t flags,
        uint8_t decimals)
        : ColumnDefinition("", "", "", std::move(name), "", character_set, column_length, column_type, flags, decimals)
    {
    }

    String getPayload() const override
    {
        String result;
        writeLengthEncodedString(result, "def"); /// always "def"
        writeLengthEncodedString(result, ""); /// schema
        writeLengthEncodedString(result, ""); /// table
        writeLengthEncodedString(result, ""); /// org_table
        writeLengthEncodedString(result, name);
        writeLengthEncodedString(result, ""); /// org_name
        result.append(writeLengthEncodedNumber(next_length));
Y
draft  
Yuriy 已提交
538 539 540 541 542 543 544 545 546 547
        result.append(reinterpret_cast<const char *>(&character_set), 2);
        result.append(reinterpret_cast<const char *>(&column_length), 4);
        result.append(reinterpret_cast<const char *>(&column_type), 1);
        result.append(reinterpret_cast<const char *>(&flags), 2);
        result.append(reinterpret_cast<const char *>(&decimals), 2);
        result.append(2, 0x0);
        return result;
    }
};

548 549
class ComFieldList : public ReadPacket
{
Y
draft  
Yuriy 已提交
550
public:
551
    String table, field_wildcard;
Y
draft  
Yuriy 已提交
552

Y
Yuriy 已提交
553 554 555 556
    ComFieldList() = default;

    ComFieldList(const ComFieldList &) = default;

557
    void readPayload(String payload)
Y
draft  
Yuriy 已提交
558 559 560 561 562 563 564 565
    {
        std::istringstream ss(payload);
        ss.ignore(1); // command byte
        std::getline(ss, table, static_cast<char>(0x0));
        field_wildcard = payload.substr(table.length() + 2); // rest of the packet
    }
};

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
class LengthEncodedNumber : public WritePacket
{
    uint64_t value;
public:
    LengthEncodedNumber(uint64_t value): value(value)
    {
    }

    String getPayload() const override
    {
        return writeLengthEncodedNumber(value);
    }
};

class ResultsetRow : public WritePacket
{
    std::vector<String> columns;
public:
    ResultsetRow()
    {
    }

    void appendColumn(String value)
    {
        columns.emplace_back(std::move(value));
    }

    String getPayload() const override
    {
        String result;
        for (const String & column : columns)
        {
            writeLengthEncodedString(result, column);
        }
        return result;
    }
};
Y
draft  
Yuriy 已提交
603 604 605

}
}