log_event.cc 135 KB
Newer Older
Kent Boortz's avatar
Kent Boortz committed
1
/*
2
   Copyright (c) 2000, 2018, Oracle and/or its affiliates.
Marko Mäkelä's avatar
Marko Mäkelä committed
3
   Copyright (c) 2009, 2021, MariaDB
4

unknown's avatar
unknown committed
5 6
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
unknown's avatar
unknown committed
7
   the Free Software Foundation; version 2 of the License.
8

unknown's avatar
unknown committed
9 10 11 12
   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 for more details.
13

unknown's avatar
unknown committed
14 15
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
Vicențiu Ciorbaru's avatar
Vicențiu Ciorbaru committed
16
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335  USA */
unknown's avatar
unknown committed
17 18


19
#include "mariadb.h"
20
#include "sql_priv.h"
21
#include "handler.h"
22
#ifndef MYSQL_CLIENT
23 24 25 26 27 28 29 30 31 32 33
#include "unireg.h"
#include "log_event.h"
#include "sql_base.h"                           // close_thread_tables
#include "sql_cache.h"                       // QUERY_CACHE_FLAGS_SIZE
#include "sql_locale.h" // MY_LOCALE, my_locale_by_number, my_locale_en_US
#include "key.h"        // key_copy
#include "lock.h"       // mysql_unlock_tables
#include "sql_parse.h"  // mysql_test_parse_for_slave
#include "tztime.h"     // struct Time_zone
#include "sql_load.h"   // mysql_load
#include "sql_db.h"     // load_db_opt_by_name
34
#include "slave.h"
35 36
#include "rpl_rli.h"
#include "rpl_mi.h"
unknown's avatar
unknown committed
37
#include "rpl_filter.h"
unknown's avatar
unknown committed
38
#include "rpl_record.h"
Konstantin Osipov's avatar
Konstantin Osipov committed
39
#include "transaction.h"
40
#include <my_dir.h>
41
#include "sql_show.h"    // append_identifier
Sergei Golubchik's avatar
Sergei Golubchik committed
42
#include <mysql/psi/mysql_statement.h>
43
#include <strfunc.h>
44
#include "compat56.h"
45
#include "sql_insert.h"
46 47 48
#ifdef WITH_WSREP
#include "wsrep_mysqld.h"
#endif /* WITH_WSREP */
49 50
#else
#include "mysqld_error.h"
unknown's avatar
unknown committed
51
#endif /* MYSQL_CLIENT */
52

53
#include <my_bitmap.h>
54
#include "rpl_utility.h"
Sergei Golubchik's avatar
Sergei Golubchik committed
55
#include "rpl_constants.h"
Sergei Golubchik's avatar
Sergei Golubchik committed
56
#include "sql_digest.h"
vinchen's avatar
vinchen committed
57
#include "zlib.h"
unknown's avatar
unknown committed
58

Sergei Golubchik's avatar
Sergei Golubchik committed
59
#define my_b_write_string(A, B) my_b_write((A), (uchar*)(B), (uint) (sizeof(B) - 1))
unknown's avatar
unknown committed
60

61
#ifndef _AIX
62
PSI_memory_key key_memory_log_event;
63
#endif
64 65 66
PSI_memory_key key_memory_Incident_log_event_message;
PSI_memory_key key_memory_Rows_query_log_event_rows_query;

unknown's avatar
unknown committed
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
/**
  BINLOG_CHECKSUM variable.
*/
const char *binlog_checksum_type_names[]= {
  "NONE",
  "CRC32",
  NullS
};

unsigned int binlog_checksum_type_length[]= {
  sizeof("NONE") - 1,
  sizeof("CRC32") - 1,
  0
};

TYPELIB binlog_checksum_typelib=
{
  array_elements(binlog_checksum_type_names) - 1, "",
  binlog_checksum_type_names,
  binlog_checksum_type_length
};


90 91
#define FLAGSTR(V,F) ((V)&(F)?#F" ":"")

92 93 94 95 96 97 98 99
/*
  Size of buffer for printing a double in format %.<PREC>g

  optional '-' + optional zero + '.'  + PREC digits + 'e' + sign +
  exponent digits + '\0'
*/
#define FMT_G_BUFSIZE(PREC) (3 + (PREC) + 5 + 1)

unknown's avatar
unknown committed
100 101 102 103 104 105 106 107
/* 
   replication event checksum is introduced in the following "checksum-home" version.
   The checksum-aware servers extract FD's version to decide whether the FD event
   carries checksum info.

   TODO: correct the constant when it has been determined 
   (which main tree to push and when) 
*/
108 109 110 111 112
const Version checksum_version_split_mysql(5, 6, 1);
const Version checksum_version_split_mariadb(5, 3, 0);

// First MySQL version with fraction seconds
const Version fsp_version_split_mysql(5, 6, 0);
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
/*
  Cache that will automatically be written to a dedicated file on
  destruction.

  DESCRIPTION

 */
class Write_on_release_cache
{
public:
  enum flag
  {
    FLUSH_F
  };

  typedef unsigned short flag_set;

  /*
    Constructor.

    SYNOPSIS
      Write_on_release_cache
      cache  Pointer to cache to use
      file   File to write cache to upon destruction
      flags  Flags for the cache

    DESCRIPTION
141 142 143
      Cache common parameters and ensure common flush_data() code
      on successful copy of the cache, the cache will be reinited as a
      WRITE_CACHE.
144 145 146 147 148

      Currently, a pointer to the cache is provided in the
      constructor, but it would be possible to create a subclass
      holding the IO_CACHE itself.
   */
Monty's avatar
Monty committed
149 150
  Write_on_release_cache(IO_CACHE *cache, FILE *file, flag_set flags = 0, Log_event *ev = NULL)
    : m_cache(cache), m_file(file), m_flags(flags), m_ev(ev)
151 152 153 154
  {
    reinit_io_cache(m_cache, WRITE_CACHE, 0L, FALSE, TRUE);
  }

155 156 157
  ~Write_on_release_cache() {}

  bool flush_data()
158
  {
Monty's avatar
Monty committed
159
#ifdef MYSQL_CLIENT
160
    if (m_ev == NULL)
Monty's avatar
Monty committed
161
    {
162 163 164 165
      if (copy_event_cache_to_file_and_reinit(m_cache, m_file))
        return 1;
      if ((m_flags & FLUSH_F) && fflush(m_file))
        return 1;
Monty's avatar
Monty committed
166 167 168 169
    }
    else // if m_ev<>NULL, then storing the output in output_buf
    {
      LEX_STRING tmp_str;
170
      bool res;
Monty's avatar
Monty committed
171
      if (copy_event_cache_to_string_and_reinit(m_cache, &tmp_str))
172
        return 1;
173 174
      /* use 2 argument append as tmp_str is not \0 terminated */
      res= m_ev->output_buf.append(tmp_str.str, tmp_str.length);
Monty's avatar
Monty committed
175
      my_free(tmp_str.str);
176
      return res ? res : 0;
Monty's avatar
Monty committed
177 178
    }
#else /* MySQL_SERVER */
179 180 181 182
    if (copy_event_cache_to_file_and_reinit(m_cache, m_file))
      return 1;
    if ((m_flags & FLUSH_F) && fflush(m_file))
      return 1;
Monty's avatar
Monty committed
183
#endif
184
    return 0;
185 186 187 188 189 190 191 192 193
  }

  /*
    Return a pointer to the internal IO_CACHE.

    SYNOPSIS
      operator&()

    DESCRIPTION
194 195 196 197

      Function to return a pointer to the internal cache, so that the
      object can be treated as a IO_CACHE and used with the my_b_*
      IO_CACHE functions
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

    RETURN VALUE
      A pointer to the internal IO_CACHE.
   */
  IO_CACHE *operator&()
  {
    return m_cache;
  }

private:
  // Hidden, to prevent usage.
  Write_on_release_cache(Write_on_release_cache const&);

  IO_CACHE *m_cache;
  FILE *m_file;
  flag_set m_flags;
Monty's avatar
Monty committed
214
  Log_event *m_ev; // Used for Flashback
215 216
};

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
#ifndef DBUG_OFF
#define DBUG_DUMP_EVENT_BUF(B,L)                                         \
  do {                                                                   \
    const uchar *_buf=(uchar*)(B);                                       \
    size_t _len=(L);                                                     \
    if (_len >= LOG_EVENT_MINIMAL_HEADER_LEN)                            \
    {                                                                    \
      DBUG_PRINT("data", ("header: timestamp:%u type:%u server_id:%u len:%u log_pos:%u flags:%u",  \
                          uint4korr(_buf), _buf[EVENT_TYPE_OFFSET],      \
                          uint4korr(_buf+SERVER_ID_OFFSET),              \
                          uint4korr(_buf+EVENT_LEN_OFFSET),              \
                          uint4korr(_buf+LOG_POS_OFFSET),                \
                          uint4korr(_buf+FLAGS_OFFSET)));                \
      DBUG_DUMP("data", _buf+LOG_EVENT_MINIMAL_HEADER_LEN,               \
                _len-LOG_EVENT_MINIMAL_HEADER_LEN);                      \
    }                                                                    \
    else                                                                 \
      DBUG_DUMP("data", _buf, _len);                                     \
  } while(0)
#else
#define DBUG_DUMP_EVENT_BUF(B,L) do { } while(0)
#endif
unknown's avatar
unknown committed
239

unknown's avatar
unknown committed
240
/*
241
  read_str()
unknown's avatar
unknown committed
242
*/
243

244 245
static inline int read_str(const char **buf, const char *buf_end,
                           const char **str, uint8 *len)
246
{
247
  if (*buf + ((uint) (uchar) **buf) >= buf_end)
248
    return 1;
249 250 251
  *len= (uint8) **buf;
  *str= (*buf)+1;
  (*buf)+= (uint) *len+1;
252 253 254
  return 0;
}

255

unknown's avatar
unknown committed
256
/**
Alexander Barkov's avatar
The bug  
Alexander Barkov committed
257
  Transforms a string into "" or its expression in X'HHHH' form.
258
*/
unknown's avatar
unknown committed
259

260
char *str_to_hex(char *to, const char *from, size_t len)
261 262 263
{
  if (len)
  {
Alexander Barkov's avatar
The bug  
Alexander Barkov committed
264 265
    *to++= 'X';
    *to++= '\'';
unknown's avatar
unknown committed
266
    to= octet2hex(to, from, len);
Alexander Barkov's avatar
The bug  
Alexander Barkov committed
267 268
    *to++= '\'';
    *to= '\0';
269 270
  }
  else
unknown's avatar
unknown committed
271 272
    to= strmov(to, "\"\"");
  return to;                               // pointer to end 0 of 'to'
273 274
}

vinchen's avatar
vinchen committed
275 276 277 278 279
#define BINLOG_COMPRESSED_HEADER_LEN 1
#define BINLOG_COMPRESSED_ORIGINAL_LENGTH_MAX_BYTES 4
/**
  Compressed Record
    Record Header: 1 Byte
vinchen's avatar
vinchen committed
280 281 282 283
             7 Bit: Always 1, mean compressed;
           4-6 Bit: Compressed algorithm - Always 0, means zlib
                    It maybe support other compression algorithm in the future.
           0-3 Bit: Bytes of "Record Original Length"
vinchen's avatar
vinchen committed
284
    Record Original Length: 1-4 Bytes
285
    Compressed Buf:
vinchen's avatar
vinchen committed
286 287 288 289 290 291 292 293
*/

/**
  Get the length of compress content.
*/

uint32 binlog_get_compress_len(uint32 len)
{
294
    /* 5 for the begin content, 1 reserved for a '\0'*/
vinchen's avatar
vinchen committed
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
    return ALIGN_SIZE((BINLOG_COMPRESSED_HEADER_LEN + BINLOG_COMPRESSED_ORIGINAL_LENGTH_MAX_BYTES) 
                        + compressBound(len) + 1);
}

/**
   Compress buf from 'src' to 'dst'.

   Note: 1) Then the caller should guarantee the length of 'dst', which
      can be got by binlog_get_uncompress_len, is enough to hold
      the content uncompressed.
         2) The 'comlen' should stored the length of 'dst', and it will
      be set as the size of compressed content after return.

   return zero if successful, others otherwise.
*/
int binlog_buf_compress(const char *src, char *dst, uint32 len, uint32 *comlen)
{
  uchar lenlen;
  if (len & 0xFF000000)
  {
    dst[1] = uchar(len >> 24);
    dst[2] = uchar(len >> 16);
    dst[3] = uchar(len >> 8);
    dst[4] = uchar(len);
    lenlen = 4;
  }
  else if (len & 0x00FF0000)
  {
    dst[1] = uchar(len >> 16);
    dst[2] = uchar(len >> 8);
    dst[3] = uchar(len);
    lenlen = 3;
  }
  else if (len & 0x0000FF00)
  {
    dst[1] = uchar(len >> 8);
    dst[2] = uchar(len);
    lenlen = 2;
  }
  else 
  {
    dst[1] = uchar(len);
    lenlen = 1;
  }
  dst[0] = 0x80 | (lenlen & 0x07);

  uLongf tmplen = (uLongf)*comlen - BINLOG_COMPRESSED_HEADER_LEN - lenlen - 1;
342 343
  if (compress((Bytef *)dst + BINLOG_COMPRESSED_HEADER_LEN + lenlen, &tmplen,
               (const Bytef *)src, (uLongf)len) != Z_OK)
vinchen's avatar
vinchen committed
344 345 346 347 348 349 350 351 352
  {
    return 1;
  }
  *comlen = (uint32)tmplen + BINLOG_COMPRESSED_HEADER_LEN + lenlen;
  return 0;
}

/**
   Convert a query_compressed_log_event to query_log_event
353
   from 'src' to 'dst', the size after compression stored in 'newlen'.
vinchen's avatar
vinchen committed
354

355 356 357 358 359
   @Note:
      1) The caller should call my_free to release 'dst' if *is_malloc is
         returned as true.
      2) If *is_malloc is retuened as false, then 'dst' reuses the passed-in
         'buf'.
vinchen's avatar
vinchen committed
360

361
   return zero if successful, non-zero otherwise.
vinchen's avatar
vinchen committed
362 363
*/

364 365
int
query_event_uncompress(const Format_description_log_event *description_event,
vinchen's avatar
vinchen committed
366 367
                       bool contain_checksum, const char *src, ulong src_len, 
                       char* buf, ulong buf_size, bool* is_malloc, char **dst,
368
                       ulong *newlen)
vinchen's avatar
vinchen committed
369 370
{
  ulong len = uint4korr(src + EVENT_LEN_OFFSET);
371
  const char *tmp = src;
vinchen's avatar
vinchen committed
372 373 374 375 376
  const char *end = src + len;

  // bad event
  if (src_len < len )
    return 1;
vinchen's avatar
vinchen committed
377 378 379

  DBUG_ASSERT((uchar)src[EVENT_TYPE_OFFSET] == QUERY_COMPRESSED_EVENT);

380 381 382
  uint8 common_header_len= description_event->common_header_len;
  uint8 post_header_len=
    description_event->post_header_len[QUERY_COMPRESSED_EVENT-1];
vinchen's avatar
vinchen committed
383

vinchen's avatar
vinchen committed
384 385
  *is_malloc = false;

386
  tmp += common_header_len;
vinchen's avatar
vinchen committed
387 388 389
  // bad event
  if (end <= tmp)
    return 1;
vinchen's avatar
vinchen committed
390

391 392
  uint db_len = (uint)tmp[Q_DB_LEN_OFFSET];
  uint16 status_vars_len= uint2korr(tmp + Q_STATUS_VARS_LEN_OFFSET);
vinchen's avatar
vinchen committed
393

394
  tmp += post_header_len + status_vars_len + db_len + 1;
vinchen's avatar
vinchen committed
395 396 397
  // bad event
  if (end <= tmp)
    return 1;
vinchen's avatar
vinchen committed
398

399 400
  int32 comp_len = (int32)(len - (tmp - src) - 
                  (contain_checksum ? BINLOG_CHECKSUM_LEN : 0));
401
  uint32 un_len = binlog_get_uncompress_len(tmp);
vinchen's avatar
vinchen committed
402 403 404 405 406

  // bad event 
  if (comp_len < 0 || un_len == 0)
    return 1;

407
  *newlen = (ulong)(tmp - src) + un_len;
vinchen's avatar
vinchen committed
408 409
  if(contain_checksum)
    *newlen += BINLOG_CHECKSUM_LEN;
410
  
411
  uint32 alloc_size = (uint32)ALIGN_SIZE(*newlen);
412
  char *new_dst = NULL;
vinchen's avatar
vinchen committed
413

vinchen's avatar
vinchen committed
414
  
415 416 417 418 419 420
  if (alloc_size <= buf_size) 
  {
    new_dst = buf;
  }
  else 
  {
421
    new_dst = (char *)my_malloc(PSI_INSTRUMENT_ME, alloc_size, MYF(MY_WME));
422 423 424 425 426 427 428
    if (!new_dst)
      return 1;

    *is_malloc = true;
  }

  /* copy the head*/
429 430
  memcpy(new_dst, src , tmp - src);
  if (binlog_buf_uncompress(tmp, new_dst + (tmp - src),
vinchen's avatar
vinchen committed
431
                            comp_len, &un_len))
432
  {
433
    if (*is_malloc)
434
      my_free(new_dst);
435 436 437

    *is_malloc = false;

438 439
    return 1;
  }
vinchen's avatar
vinchen committed
440

441
  new_dst[EVENT_TYPE_OFFSET] = QUERY_EVENT;
442 443 444
  int4store(new_dst + EVENT_LEN_OFFSET, *newlen);
  if(contain_checksum)
  {
vinchen's avatar
vinchen committed
445
    ulong clear_len = *newlen - BINLOG_CHECKSUM_LEN;
446 447
    int4store(new_dst + clear_len,
              my_checksum(0L, (uchar *)new_dst, clear_len));
vinchen's avatar
vinchen committed
448
  }
449
  *dst = new_dst;
450
  return 0;
vinchen's avatar
vinchen committed
451 452
}

453 454
int
row_log_event_uncompress(const Format_description_log_event *description_event,
vinchen's avatar
vinchen committed
455 456
                         bool contain_checksum, const char *src, ulong src_len,
                         char* buf, ulong buf_size, bool* is_malloc, char **dst,
457
                         ulong *newlen)
vinchen's avatar
vinchen committed
458 459 460
{
  Log_event_type type = (Log_event_type)(uchar)src[EVENT_TYPE_OFFSET];
  ulong len = uint4korr(src + EVENT_LEN_OFFSET);
461
  const char *tmp = src;
462
  char *new_dst = NULL;
vinchen's avatar
vinchen committed
463 464 465 466 467
  const char *end = tmp + len;

  // bad event
  if (src_len < len)
    return 1;
vinchen's avatar
vinchen committed
468 469 470

  DBUG_ASSERT(LOG_EVENT_IS_ROW_COMPRESSED(type));

471 472
  uint8 common_header_len= description_event->common_header_len;
  uint8 post_header_len= description_event->post_header_len[type-1];
vinchen's avatar
vinchen committed
473

474
  tmp += common_header_len + ROWS_HEADER_LEN_V1;
vinchen's avatar
vinchen committed
475 476 477 478 479 480
  if (post_header_len == ROWS_HEADER_LEN_V2)
  {
    /*
      Have variable length header, check length,
      which includes length bytes
    */
vinchen's avatar
vinchen committed
481 482 483 484 485

    // bad event
    if (end - tmp <= 2)
      return 1;

vinchen's avatar
vinchen committed
486
    uint16 var_header_len= uint2korr(tmp);
vinchen's avatar
vinchen committed
487
    DBUG_ASSERT(var_header_len >= 2);
vinchen's avatar
vinchen committed
488 489 490 491 492

    /* skip over var-len header, extracting 'chunks' */
    tmp += var_header_len;

    /* get the uncompressed event type */
493 494
    type=
      (Log_event_type)(type - WRITE_ROWS_COMPRESSED_EVENT + WRITE_ROWS_EVENT);
vinchen's avatar
vinchen committed
495 496 497 498
  }
  else 
  {
    /* get the uncompressed event type */
499 500
    type= (Log_event_type)
      (type - WRITE_ROWS_COMPRESSED_EVENT_V1 + WRITE_ROWS_EVENT_V1);
vinchen's avatar
vinchen committed
501 502
  }

vinchen's avatar
vinchen committed
503 504 505 506
  //bad event
  if (end <= tmp)
    return 1;

vinchen's avatar
vinchen committed
507 508 509 510 511 512 513 514
  ulong m_width = net_field_length((uchar **)&tmp);
  tmp += (m_width + 7) / 8;

  if (type == UPDATE_ROWS_EVENT_V1 || type == UPDATE_ROWS_EVENT)
  {
    tmp += (m_width + 7) / 8;
  }

vinchen's avatar
vinchen committed
515 516 517 518
  //bad event
  if (end <= tmp)
    return 1;

519
  uint32 un_len = binlog_get_uncompress_len(tmp);
vinchen's avatar
vinchen committed
520 521 522 523
  //bad event
  if (un_len == 0)
    return 1;

524 525
  int32 comp_len = (int32)(len - (tmp - src) - 
    (contain_checksum ? BINLOG_CHECKSUM_LEN : 0));
vinchen's avatar
vinchen committed
526 527 528 529
  //bad event
  if (comp_len <=0)
    return 1;

530
  *newlen = ulong(tmp - src) + un_len;
vinchen's avatar
vinchen committed
531 532 533
  if(contain_checksum)
    *newlen += BINLOG_CHECKSUM_LEN;

534
  size_t alloc_size = ALIGN_SIZE(*newlen);
535 536 537 538 539 540 541 542
  
  *is_malloc = false;
  if (alloc_size <= buf_size) 
  {
    new_dst = buf;
  }
  else
  {
543
    new_dst = (char *)my_malloc(PSI_INSTRUMENT_ME, alloc_size, MYF(MY_WME));
544 545 546 547 548
    if (!new_dst)
      return 1;

    *is_malloc = true;
  }
vinchen's avatar
vinchen committed
549

550 551 552 553
  /* Copy the head. */
  memcpy(new_dst, src , tmp - src);
  /* Uncompress the body. */
  if (binlog_buf_uncompress(tmp, new_dst + (tmp - src),
vinchen's avatar
vinchen committed
554
                            comp_len, &un_len))
555
  {
556
    if (*is_malloc)
557
      my_free(new_dst);
558

559 560
    return 1;
  }
vinchen's avatar
vinchen committed
561

562 563
  new_dst[EVENT_TYPE_OFFSET] = type;
  int4store(new_dst + EVENT_LEN_OFFSET, *newlen);
vinchen's avatar
vinchen committed
564 565
  if(contain_checksum){
    ulong clear_len = *newlen - BINLOG_CHECKSUM_LEN;
566 567
    int4store(new_dst + clear_len,
              my_checksum(0L, (uchar *)new_dst, clear_len));
vinchen's avatar
vinchen committed
568
  }
569
  *dst = new_dst;
570
  return 0;
vinchen's avatar
vinchen committed
571 572 573 574
}

/**
  Get the length of uncompress content.
vinchen's avatar
vinchen committed
575
  return 0 means error.
vinchen's avatar
vinchen committed
576 577 578 579
*/

uint32 binlog_get_uncompress_len(const char *buf)
{
580
  uint32 len = 0;
581 582 583 584 585 586 587
  uint32 lenlen = 0;

  if ((buf == NULL) || ((buf[0] & 0xe0) != 0x80))
    return len;

  lenlen = buf[0] & 0x07;

588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
  switch(lenlen)
  {
  case 1:
    len = uchar(buf[1]);
    break;
  case 2:
    len = uchar(buf[1]) << 8 | uchar(buf[2]);
    break;
  case 3:
    len = uchar(buf[1]) << 16 | uchar(buf[2]) << 8 | uchar(buf[3]);
    break;
  case 4:
    len = uchar(buf[1]) << 24 | uchar(buf[2]) << 16 |
          uchar(buf[3]) << 8 | uchar(buf[4]);
    break;
  default:
    DBUG_ASSERT(lenlen >= 1 && lenlen <= 4);
    break;
  }
  return len;
vinchen's avatar
vinchen committed
608 609 610 611 612 613 614 615 616 617 618 619 620
}

/**
   Uncompress the content in 'src' with length of 'len' to 'dst'.

   Note: 1) Then the caller should guarantee the length of 'dst' (which
      can be got by statement_get_uncompress_len) is enough to hold
      the content uncompressed.
         2) The 'newlen' should stored the length of 'dst', and it will
      be set as the size of uncompressed content after return.

   return zero if successful, others otherwise.
*/
621 622
int binlog_buf_uncompress(const char *src, char *dst, uint32 len,
                          uint32 *newlen)
vinchen's avatar
vinchen committed
623
{
624 625 626 627
  if((src[0] & 0x80) == 0)
  {
    return 1;
  }
vinchen's avatar
vinchen committed
628

629 630
  uint32 lenlen= src[0] & 0x07;
  uLongf buflen= *newlen;
vinchen's avatar
vinchen committed
631 632 633

  uint32 alg = (src[0] & 0x70) >> 4;
  switch(alg)
634
  {
vinchen's avatar
vinchen committed
635 636 637 638 639 640 641 642 643 644 645
  case 0:
    // zlib
    if(uncompress((Bytef *)dst, &buflen,
      (const Bytef*)src + 1 + lenlen, len - 1 - lenlen) != Z_OK)
    {
      return 1;
    }
    break;
  default:
    //TODO
    //bad algorithm
646 647
    return 1;
  }
vinchen's avatar
vinchen committed
648

vinchen's avatar
vinchen committed
649
  DBUG_ASSERT(*newlen == (uint32)buflen);
650 651
  *newlen = (uint32)buflen;
  return 0;
vinchen's avatar
vinchen committed
652 653
}

654

unknown's avatar
unknown committed
655
/**************************************************************************
656
	Log_event methods (= the parent class of all events)
unknown's avatar
unknown committed
657
**************************************************************************/
658

unknown's avatar
unknown committed
659 660 661
/**
  @return
  returns the human readable name of the event's type
unknown's avatar
unknown committed
662
*/
663

664
const char* Log_event::get_type_str(Log_event_type type)
unknown's avatar
unknown committed
665
{
666
  switch(type) {
667
  case START_EVENT_V3:  return "Start_v3";
unknown's avatar
unknown committed
668 669 670 671 672
  case STOP_EVENT:   return "Stop";
  case QUERY_EVENT:  return "Query";
  case ROTATE_EVENT: return "Rotate";
  case INTVAR_EVENT: return "Intvar";
  case LOAD_EVENT:   return "Load";
673
  case NEW_LOAD_EVENT:   return "New_load";
unknown's avatar
unknown committed
674
  case SLAVE_EVENT:  return "Slave";
675 676 677 678
  case CREATE_FILE_EVENT: return "Create_file";
  case APPEND_BLOCK_EVENT: return "Append_block";
  case DELETE_FILE_EVENT: return "Delete_file";
  case EXEC_LOAD_EVENT: return "Exec_load";
679
  case RAND_EVENT: return "RAND";
unknown's avatar
unknown committed
680
  case XID_EVENT: return "Xid";
unknown's avatar
unknown committed
681
  case USER_VAR_EVENT: return "User var";
682
  case FORMAT_DESCRIPTION_EVENT: return "Format_desc";
683
  case TABLE_MAP_EVENT: return "Table_map";
684 685 686
  case PRE_GA_WRITE_ROWS_EVENT: return "Write_rows_event_old";
  case PRE_GA_UPDATE_ROWS_EVENT: return "Update_rows_event_old";
  case PRE_GA_DELETE_ROWS_EVENT: return "Delete_rows_event_old";
687 688 689
  case WRITE_ROWS_EVENT_V1: return "Write_rows_v1";
  case UPDATE_ROWS_EVENT_V1: return "Update_rows_v1";
  case DELETE_ROWS_EVENT_V1: return "Delete_rows_v1";
690 691 692
  case WRITE_ROWS_EVENT: return "Write_rows";
  case UPDATE_ROWS_EVENT: return "Update_rows";
  case DELETE_ROWS_EVENT: return "Delete_rows";
unknown's avatar
unknown committed
693 694
  case BEGIN_LOAD_QUERY_EVENT: return "Begin_load_query";
  case EXECUTE_LOAD_QUERY_EVENT: return "Execute_load_query";
695
  case INCIDENT_EVENT: return "Incident";
696
  case ANNOTATE_ROWS_EVENT: return "Annotate_rows";
697
  case BINLOG_CHECKPOINT_EVENT: return "Binlog_checkpoint";
698 699
  case GTID_EVENT: return "Gtid";
  case GTID_LIST_EVENT: return "Gtid_list";
700
  case START_ENCRYPTION_EVENT: return "Start_encryption";
701 702 703 704 705 706 707 708

  /* The following is only for mysqlbinlog */
  case IGNORABLE_LOG_EVENT: return "Ignorable log event";
  case ROWS_QUERY_LOG_EVENT: return "MySQL Rows_query";
  case GTID_LOG_EVENT: return "MySQL Gtid";
  case ANONYMOUS_GTID_LOG_EVENT: return "MySQL Anonymous_Gtid";
  case PREVIOUS_GTIDS_LOG_EVENT: return "MySQL Previous_gtids";
  case HEARTBEAT_LOG_EVENT: return "Heartbeat";
709 710 711
  case TRANSACTION_CONTEXT_EVENT: return "Transaction_context";
  case VIEW_CHANGE_EVENT: return "View_change";
  case XA_PREPARE_LOG_EVENT: return "XA_prepare";
vinchen's avatar
vinchen committed
712 713 714 715 716 717 718
  case QUERY_COMPRESSED_EVENT: return "Query_compressed";
  case WRITE_ROWS_COMPRESSED_EVENT: return "Write_rows_compressed";
  case UPDATE_ROWS_COMPRESSED_EVENT: return "Update_rows_compressed";
  case DELETE_ROWS_COMPRESSED_EVENT: return "Delete_rows_compressed";
  case WRITE_ROWS_COMPRESSED_EVENT_V1: return "Write_rows_compressed_v1";
  case UPDATE_ROWS_COMPRESSED_EVENT_V1: return "Update_rows_compressed_v1";
  case DELETE_ROWS_COMPRESSED_EVENT_V1: return "Delete_rows_compressed_v1";
719

unknown's avatar
unknown committed
720
  default: return "Unknown";				/* impossible */
unknown's avatar
unknown committed
721 722 723
  }
}

724 725 726 727 728
const char* Log_event::get_type_str()
{
  return get_type_str(get_type_code());
}

729

unknown's avatar
unknown committed
730
/*
731
  Log_event::Log_event()
732
*/
733

734
Log_event::Log_event(const char* buf,
unknown's avatar
unknown committed
735
                     const Format_description_log_event* description_event)
736
  :temp_buf(0), exec_time(0), cache_type(Log_event::EVENT_INVALID_CACHE),
737
    checksum_alg(BINLOG_CHECKSUM_ALG_UNDEF)
738
{
739 740
#ifndef MYSQL_CLIENT
  thd = 0;
unknown's avatar
unknown committed
741
#endif
742
  when = uint4korr(buf);
743
  when_sec_part= ~0UL;
744
  server_id = uint4korr(buf + SERVER_ID_OFFSET);
745
  data_written= uint4korr(buf + EVENT_LEN_OFFSET);
746
  if (description_event->binlog_version==1)
747
  {
748 749 750
    log_pos= 0;
    flags= 0;
    return;
751
  }
752 753 754
  /* 4.0 or newer */
  log_pos= uint4korr(buf + LOG_POS_OFFSET);
  /*
755 756 757 758 759 760 761 762
    If the log is 4.0 (so here it can only be a 4.0 relay log read by
    the SQL thread or a 4.0 master binlog read by the I/O thread),
    log_pos is the beginning of the event: we transform it into the end
    of the event, which is more useful.
    But how do you know that the log is 4.0: you know it if
    description_event is version 3 *and* you are not reading a
    Format_desc (remember that mysqlbinlog starts by assuming that 5.0
    logs are in 4.0 format, until it finds a Format_desc).
763 764
  */
  if (description_event->binlog_version==3 &&
765
      (uchar)buf[EVENT_TYPE_OFFSET]<FORMAT_DESCRIPTION_EVENT && log_pos)
766
  {
767 768 769
      /*
        If log_pos=0, don't change it. log_pos==0 is a marker to mean
        "don't change rli->group_master_log_pos" (see
770 771
        inc_group_relay_log_pos()). As it is unreal log_pos, adding the
        event len's is nonsense. For example, a fake Rotate event should
772
        not have its log_pos (which is 0) changed or it will modify
773 774 775 776
        Exec_master_log_pos in SHOW SLAVE STATUS, displaying a nonsense
        value of (a non-zero offset which does not exist in the master's
        binlog, so which will cause problems if the user uses this value
        in CHANGE MASTER).
777
      */
unknown's avatar
unknown committed
778
    log_pos+= data_written; /* purecov: inspected */
779
  }
780
  DBUG_PRINT("info", ("log_pos: %llu", log_pos));
781 782

  flags= uint2korr(buf + FLAGS_OFFSET);
783 784
  if (((uchar)buf[EVENT_TYPE_OFFSET] == FORMAT_DESCRIPTION_EVENT) ||
      ((uchar)buf[EVENT_TYPE_OFFSET] == ROTATE_EVENT))
785 786
  {
    /*
787 788
      These events always have a header which stops here (i.e. their
      header is FROZEN).
789 790
    */
    /*
791 792 793 794 795 796 797
      Initialization to zero of all other Log_event members as they're
      not specified. Currently there are no such members; in the future
      there will be an event UID (but Format_description and Rotate
      don't need this UID, as they are not propagated through
      --log-slave-updates (remember the UID is used to not play a query
      twice when you have two masters which are slaves of a 3rd master).
      Then we are done.
798 799 800 801
    */
    return;
  }
  /* otherwise, go on with reading the header from buf (nothing now) */
802 803 804
}


805 806 807 808 809 810 811 812
/**
  This needn't be format-tolerant, because we only parse the first
  LOG_EVENT_MINIMAL_HEADER_LEN bytes (just need the event's length).
*/

int Log_event::read_log_event(IO_CACHE* file, String* packet,
                              const Format_description_log_event *fdle,
                              enum enum_binlog_checksum_alg checksum_alg_arg)
813
{
814 815 816 817 818 819 820 821 822 823
  ulong data_len;
  char buf[LOG_EVENT_MINIMAL_HEADER_LEN];
  uchar ev_offset= packet->length();
#if !defined(MYSQL_CLIENT)
  THD *thd=current_thd;
  ulong max_allowed_packet= thd ? thd->slave_thread ? slave_max_allowed_packet
                                                    : thd->variables.max_allowed_packet
                                : ~(uint)0;
#endif
  DBUG_ENTER("Log_event::read_log_event(IO_CACHE*,String*...)");
Michael Widenius's avatar
Michael Widenius committed
824

825
  if (my_b_read(file, (uchar*) buf, sizeof(buf)))
826
  {
827
    /*
828 829 830
      If the read hits eof, we must report it as eof so the caller
      will know it can go into cond_wait to be woken up on the next
      update to the log.
831
    */
832 833 834
    DBUG_PRINT("error",("file->error: %d", file->error));
    DBUG_RETURN(file->error == 0 ? LOG_READ_EOF :
                file->error > 0 ? LOG_READ_TRUNC : LOG_READ_IO);
835
  }
836
  data_len= uint4korr(buf + EVENT_LEN_OFFSET);
837

838 839 840
  /* Append the log event header to packet */
  if (packet->append(buf, sizeof(buf)))
    DBUG_RETURN(LOG_READ_MEM);
841 842 843 844

  if (data_len < LOG_EVENT_MINIMAL_HEADER_LEN)
    DBUG_RETURN(LOG_READ_BOGUS);

Eugene Kosov's avatar
Eugene Kosov committed
845 846
  if (data_len > MY_MAX(max_allowed_packet,
                        opt_binlog_rows_event_max_size + MAX_LOG_EVENT_HEADER))
847 848
    DBUG_RETURN(LOG_READ_TOO_LARGE);

849
  if (likely(data_len > LOG_EVENT_MINIMAL_HEADER_LEN))
850
  {
851
    /* Append rest of event, read directly from file into packet */
852
    if (packet->append(file, data_len - LOG_EVENT_MINIMAL_HEADER_LEN))
853
    {
854
      /*
855
        Fatal error occurred when appending rest of the event
856
        to packet, possible failures:
857
	1. EOF occurred when reading from file, it's really an error
858
           as there's supposed to be more bytes available.
859 860 861
           file->error will have been set to number of bytes left to read
        2. Read was interrupted, file->error would normally be set to -1
        3. Failed to allocate memory for packet, my_errno
Sergei Golubchik's avatar
Sergei Golubchik committed
862
           will be ENOMEM(file->error should be 0, but since the
863 864
           memory allocation occurs before the call to read it might
           be uninitialized)
865
      */
866 867
      DBUG_RETURN(my_errno == ENOMEM ? LOG_READ_MEM :
                  (file->error >= 0 ? LOG_READ_TRUNC: LOG_READ_IO));
868
    }
869 870 871 872 873
  }

  if (fdle->crypto_data.scheme)
  {
    uchar iv[BINLOG_IV_LENGTH];
Monty's avatar
Monty committed
874
    fdle->crypto_data.set_iv(iv, (uint32) (my_b_tell(file) - data_len));
875 876 877 878 879 880 881 882 883
    size_t sz= data_len + ev_offset + 1;
#ifdef HAVE_WOLFSSL
    /*
      Workaround for MDEV-19582.
      WolfSSL reads memory out of bounds with decryption/NOPAD)
      We allocate a little more memory therefore.
    */
    sz += MY_AES_BLOCK_SIZE;
#endif
884
    char *newpkt= (char*)my_malloc(PSI_INSTRUMENT_ME, sz, MYF(MY_WME));
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
    if (!newpkt)
      DBUG_RETURN(LOG_READ_MEM);
    memcpy(newpkt, packet->ptr(), ev_offset);

    uint dstlen;
    uchar *src= (uchar*)packet->ptr() + ev_offset;
    uchar *dst= (uchar*)newpkt + ev_offset;
    memcpy(src + EVENT_LEN_OFFSET, src, 4);
    if (encryption_crypt(src + 4, data_len - 4, dst + 4, &dstlen,
            fdle->crypto_data.key, fdle->crypto_data.key_length, iv,
            sizeof(iv), ENCRYPTION_FLAG_DECRYPT | ENCRYPTION_FLAG_NOPAD,
            ENCRYPTION_KEY_SYSTEM_DATA, fdle->crypto_data.key_version))
    {
      my_free(newpkt);
      DBUG_RETURN(LOG_READ_DECRYPT);
    }
    DBUG_ASSERT(dstlen == data_len - 4);
    memcpy(dst, dst + EVENT_LEN_OFFSET, 4);
    int4store(dst + EVENT_LEN_OFFSET, data_len);
    packet->reset(newpkt, data_len + ev_offset, data_len + ev_offset + 1,
                  &my_charset_bin);
  }
907

908 909 910 911 912
  /*
    CRC verification of the Dump thread
  */
  if (data_len > LOG_EVENT_MINIMAL_HEADER_LEN)
  {
913 914 915 916
    /* Corrupt the event for Dump thread*/
    DBUG_EXECUTE_IF("corrupt_read_log_event2",
      uchar *debug_event_buf_c = (uchar*) packet->ptr() + ev_offset;
      if (debug_event_buf_c[EVENT_TYPE_OFFSET] != FORMAT_DESCRIPTION_EVENT)
unknown's avatar
unknown committed
917
      {
918 919 920 921
        int debug_cor_pos = rand() % (data_len - BINLOG_CHECKSUM_LEN);
        debug_event_buf_c[debug_cor_pos] =~ debug_event_buf_c[debug_cor_pos];
        DBUG_PRINT("info", ("Corrupt the event at Log_event::read_log_event: byte on position %d", debug_cor_pos));
        DBUG_SET("-d,corrupt_read_log_event2");
unknown's avatar
unknown committed
922
      }
923 924
    );
    if (event_checksum_test((uchar*) packet->ptr() + ev_offset,
925
                             data_len, checksum_alg_arg))
926
      DBUG_RETURN(LOG_READ_CHECKSUM_FAILURE);
927
  }
928
  DBUG_RETURN(0);
unknown's avatar
unknown committed
929
}
930

931
Log_event* Log_event::read_log_event(IO_CACHE* file,
932
                                     const Format_description_log_event *fdle,
unknown's avatar
unknown committed
933
                                     my_bool crc_check)
unknown's avatar
unknown committed
934
{
935
  DBUG_ENTER("Log_event::read_log_event(IO_CACHE*,Format_description_log_event*...)");
936
  DBUG_ASSERT(fdle != 0);
937
  String event;
938
  const char *error= 0;
939
  Log_event *res= 0;
unknown's avatar
unknown committed
940

941
  switch (read_log_event(file, &event, fdle, BINLOG_CHECKSUM_ALG_OFF))
unknown's avatar
unknown committed
942
  {
943 944 945 946 947
    case 0:
      break;
    case LOG_READ_EOF: // no error here; we are at the file's end
      goto err;
    case LOG_READ_BOGUS:
948
      error= "Event invalid";
949 950 951 952 953 954 955 956 957 958 959 960 961
      goto err;
    case LOG_READ_IO:
      error= "read error";
      goto err;
    case LOG_READ_MEM:
      error= "Out of memory";
      goto err;
    case LOG_READ_TRUNC:
      error= "Event truncated";
      goto err;
    case LOG_READ_TOO_LARGE:
      error= "Event too big";
      goto err;
962 963 964
    case LOG_READ_DECRYPT:
      error= "Event decryption failure";
      goto err;
965 966 967 968 969
    case LOG_READ_CHECKSUM_FAILURE:
    default:
      DBUG_ASSERT(0);
      error= "internal error";
      goto err;
unknown's avatar
unknown committed
970
  }
971

972
  if ((res= read_log_event(event.ptr(), event.length(),
973
                           &error, fdle, crc_check)))
974
    res->register_temp_buf(event.release(), true);
975

976
err:
977
  if (unlikely(error))
978
  {
979
    DBUG_ASSERT(!res);
980 981 982 983
#ifdef MYSQL_CLIENT
    if (force_opt)
      DBUG_RETURN(new Unknown_log_event());
#endif
984 985
    if (event.length() >= OLD_HEADER_LEN)
      sql_print_error("Error in Log_event::read_log_event(): '%s',"
986 987 988
                      " data_len: %lu, event_type: %u", error,
                      (ulong) uint4korr(&event[EVENT_LEN_OFFSET]),
                      (uint) (uchar)event[EVENT_TYPE_OFFSET]);
989 990
    else
      sql_print_error("Error in Log_event::read_log_event(): '%s'", error);
991 992 993 994 995 996 997 998 999
    /*
      The SQL slave thread will check if file->error<0 to know
      if there was an I/O error. Even if there is no "low-level" I/O errors
      with 'file', any of the high-level above errors is worrying
      enough to stop the SQL thread now ; as we are skipping the current event,
      going on with reading and successfully executing other events can
      only corrupt the slave's databases. So stop.
    */
    file->error= -1;
1000
  }
1001
  DBUG_RETURN(res);
unknown's avatar
unknown committed
1002 1003
}

1004

unknown's avatar
unknown committed
1005
/**
1006
  Binlog format tolerance is in (buf, event_len, fdle)
1007
  constructors.
unknown's avatar
unknown committed
1008
*/
1009

1010 1011
Log_event* Log_event::read_log_event(const char* buf, uint event_len,
				     const char **error,
1012
                                     const Format_description_log_event *fdle,
unknown's avatar
unknown committed
1013
                                     my_bool crc_check)
unknown's avatar
unknown committed
1014
{
1015
  Log_event* ev;
1016
  enum enum_binlog_checksum_alg alg;
1017
  DBUG_ENTER("Log_event::read_log_event(char*,...)");
1018 1019
  DBUG_ASSERT(fdle != 0);
  DBUG_PRINT("info", ("binlog_version: %d", fdle->binlog_version));
1020
  DBUG_DUMP_EVENT_BUF(buf, event_len);
1021

1022 1023 1024 1025
  /*
    Check the integrity; This is needed because handle_slave_io() doesn't
    check if packet is of proper length.
 */
1026
  if (event_len < EVENT_LEN_OFFSET)
1027 1028
  {
    *error="Sanity check failed";		// Needed to free buffer
unknown's avatar
unknown committed
1029
    DBUG_RETURN(NULL); // general sanity check - will fail on a partial read
1030
  }
unknown's avatar
unknown committed
1031

1032
  uint event_type= (uchar)buf[EVENT_TYPE_OFFSET];
unknown's avatar
unknown committed
1033 1034
  // all following START events in the current file are without checksum
  if (event_type == START_EVENT_V3)
1035
    (const_cast< Format_description_log_event *>(fdle))->checksum_alg= BINLOG_CHECKSUM_ALG_OFF;
unknown's avatar
unknown committed
1036 1037
  /*
    CRC verification by SQL and Show-Binlog-Events master side.
1038
    The caller has to provide @fdle->checksum_alg to
unknown's avatar
unknown committed
1039 1040 1041 1042 1043
    be the last seen FD's (A) descriptor.
    If event is FD the descriptor is in it.
    Notice, FD of the binlog can be only in one instance and therefore
    Show-Binlog-Events executing master side thread needs just to know
    the only FD's (A) value -  whereas RL can contain more.
1044
    In the RL case, the alg is kept in FD_e (@fdle) which is reset
unknown's avatar
unknown committed
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
    to the newer read-out event after its execution with possibly new alg descriptor.
    Therefore in a typical sequence of RL:
    {FD_s^0, FD_m, E_m^1} E_m^1 
    will be verified with (A) of FD_m.

    See legends definition on MYSQL_BIN_LOG::relay_log_checksum_alg docs
    lines (log.h).

    Notice, a pre-checksum FD version forces alg := BINLOG_CHECKSUM_ALG_UNDEF.
  */
  alg= (event_type != FORMAT_DESCRIPTION_EVENT) ?
1056
    fdle->checksum_alg : get_checksum_alg(buf, event_len);
unknown's avatar
unknown committed
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
  // Emulate the corruption during reading an event
  DBUG_EXECUTE_IF("corrupt_read_log_event_char",
    if (event_type != FORMAT_DESCRIPTION_EVENT)
    {
      char *debug_event_buf_c = (char *)buf;
      int debug_cor_pos = rand() % (event_len - BINLOG_CHECKSUM_LEN);
      debug_event_buf_c[debug_cor_pos] =~ debug_event_buf_c[debug_cor_pos];
      DBUG_PRINT("info", ("Corrupt the event at Log_event::read_log_event(char*,...): byte on position %d", debug_cor_pos));
      DBUG_SET("-d,corrupt_read_log_event_char");
    }
  );                                                 
  if (crc_check &&
      event_checksum_test((uchar *) buf, event_len, alg))
  {
#ifdef MYSQL_CLIENT
    *error= "Event crc check failed! Most likely there is event corruption.";
    if (force_opt)
    {
1075
      ev= new Unknown_log_event(buf, fdle);
unknown's avatar
unknown committed
1076 1077 1078 1079 1080
      DBUG_RETURN(ev);
    }
    else
      DBUG_RETURN(NULL);
#else
1081
    *error= ER_THD_OR_DEFAULT(current_thd, ER_BINLOG_READ_EVENT_CHECKSUM_FAILURE);
1082
    sql_print_error("%s", *error);
unknown's avatar
unknown committed
1083 1084 1085 1086
    DBUG_RETURN(NULL);
#endif
  }

1087
  if (event_type > fdle->number_of_event_types &&
1088 1089 1090
      event_type != FORMAT_DESCRIPTION_EVENT)
  {
    /*
1091
      It is unsafe to use the fdle if its post_header_len
1092 1093 1094 1095 1096
      array does not include the event type.
    */
    DBUG_PRINT("error", ("event type %d found, but the current "
                         "Format_description_log_event supports only %d event "
                         "types", event_type,
1097
                         fdle->number_of_event_types));
1098 1099 1100 1101
    ev= NULL;
  }
  else
  {
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    /*
      In some previuos versions (see comment in
      Format_description_log_event::Format_description_log_event(char*,...)),
      event types were assigned different id numbers than in the
      present version. In order to replicate from such versions to the
      present version, we must map those event type id's to our event
      type id's.  The mapping is done with the event_type_permutation
      array, which was set up when the Format_description_log_event
      was read.
    */
1112
    if (fdle->event_type_permutation)
1113
    {
1114
      int new_event_type= fdle->event_type_permutation[event_type];
1115 1116 1117 1118
      DBUG_PRINT("info", ("converting event type %d to %d (%s)",
                   event_type, new_event_type,
                   get_type_str((Log_event_type)new_event_type)));
      event_type= new_event_type;
1119 1120
    }

unknown's avatar
unknown committed
1121 1122 1123 1124
    if (alg != BINLOG_CHECKSUM_ALG_UNDEF &&
        (event_type == FORMAT_DESCRIPTION_EVENT ||
         alg != BINLOG_CHECKSUM_ALG_OFF))
      event_len= event_len - BINLOG_CHECKSUM_LEN;
1125

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
    /*
      Create an object of Ignorable_log_event for unrecognized sub-class.
      So that SLAVE SQL THREAD will only update the position and continue.
      We should look for this flag first instead of judging by event_type
      Any event can be Ignorable_log_event if it has this flag on.
      look into @note of Ignorable_log_event
    */
    if (uint2korr(buf + FLAGS_OFFSET) & LOG_EVENT_IGNORABLE_F)
    {
      ev= new Ignorable_log_event(buf, fdle,
                                  get_type_str((Log_event_type) event_type));
      goto exit;
    }
1139 1140
    switch(event_type) {
    case QUERY_EVENT:
1141
      ev  = new Query_log_event(buf, event_len, fdle, QUERY_EVENT);
1142
      break;
vinchen's avatar
vinchen committed
1143
    case QUERY_COMPRESSED_EVENT:
1144 1145
      ev = new Query_compressed_log_event(buf, event_len, fdle,
                                          QUERY_COMPRESSED_EVENT);
vinchen's avatar
vinchen committed
1146
      break;
1147
    case LOAD_EVENT:
1148
      ev = new Load_log_event(buf, event_len, fdle);
1149 1150
      break;
    case NEW_LOAD_EVENT:
1151
      ev = new Load_log_event(buf, event_len, fdle);
1152 1153
      break;
    case ROTATE_EVENT:
1154
      ev = new Rotate_log_event(buf, event_len, fdle);
1155
      break;
1156
    case BINLOG_CHECKPOINT_EVENT:
1157
      ev = new Binlog_checkpoint_log_event(buf, event_len, fdle);
1158
      break;
1159
    case GTID_EVENT:
1160
      ev = new Gtid_log_event(buf, event_len, fdle);
1161 1162
      break;
    case GTID_LIST_EVENT:
1163
      ev = new Gtid_list_log_event(buf, event_len, fdle);
1164
      break;
1165
    case CREATE_FILE_EVENT:
1166
      ev = new Create_file_log_event(buf, event_len, fdle);
1167 1168
      break;
    case APPEND_BLOCK_EVENT:
1169
      ev = new Append_block_log_event(buf, event_len, fdle);
1170 1171
      break;
    case DELETE_FILE_EVENT:
1172
      ev = new Delete_file_log_event(buf, event_len, fdle);
1173 1174
      break;
    case EXEC_LOAD_EVENT:
1175
      ev = new Execute_load_log_event(buf, event_len, fdle);
1176 1177
      break;
    case START_EVENT_V3: /* this is sent only by MySQL <=4.x */
1178
      ev = new Start_log_event_v3(buf, event_len, fdle);
1179 1180
      break;
    case STOP_EVENT:
1181
      ev = new Stop_log_event(buf, fdle);
1182 1183
      break;
    case INTVAR_EVENT:
1184
      ev = new Intvar_log_event(buf, fdle);
1185 1186
      break;
    case XID_EVENT:
1187
      ev = new Xid_log_event(buf, fdle);
1188
      break;
1189 1190 1191
    case XA_PREPARE_LOG_EVENT:
      ev = new XA_prepare_log_event(buf, fdle);
      break;
1192
    case RAND_EVENT:
1193
      ev = new Rand_log_event(buf, fdle);
1194 1195
      break;
    case USER_VAR_EVENT:
1196
      ev = new User_var_log_event(buf, event_len, fdle);
1197 1198
      break;
    case FORMAT_DESCRIPTION_EVENT:
1199
      ev = new Format_description_log_event(buf, event_len, fdle);
1200
      break;
1201
#if defined(HAVE_REPLICATION) 
1202
    case PRE_GA_WRITE_ROWS_EVENT:
1203
      ev = new Write_rows_log_event_old(buf, event_len, fdle);
1204 1205
      break;
    case PRE_GA_UPDATE_ROWS_EVENT:
1206
      ev = new Update_rows_log_event_old(buf, event_len, fdle);
1207 1208
      break;
    case PRE_GA_DELETE_ROWS_EVENT:
1209
      ev = new Delete_rows_log_event_old(buf, event_len, fdle);
1210
      break;
1211
    case WRITE_ROWS_EVENT_V1:
1212
    case WRITE_ROWS_EVENT:
1213
      ev = new Write_rows_log_event(buf, event_len, fdle);
1214
      break;
1215
    case UPDATE_ROWS_EVENT_V1:
1216
    case UPDATE_ROWS_EVENT:
1217
      ev = new Update_rows_log_event(buf, event_len, fdle);
1218
      break;
1219
    case DELETE_ROWS_EVENT_V1:
1220
    case DELETE_ROWS_EVENT:
1221
      ev = new Delete_rows_log_event(buf, event_len, fdle);
1222
      break;
1223

vinchen's avatar
vinchen committed
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
    case WRITE_ROWS_COMPRESSED_EVENT:
    case WRITE_ROWS_COMPRESSED_EVENT_V1:
      ev = new Write_rows_compressed_log_event(buf, event_len, fdle);
      break;
    case UPDATE_ROWS_COMPRESSED_EVENT:
    case UPDATE_ROWS_COMPRESSED_EVENT_V1:
      ev = new Update_rows_compressed_log_event(buf, event_len, fdle);
      break;
    case DELETE_ROWS_COMPRESSED_EVENT:
    case DELETE_ROWS_COMPRESSED_EVENT_V1:
      ev = new Delete_rows_compressed_log_event(buf, event_len, fdle);
      break;

1237 1238 1239 1240
      /* MySQL GTID events are ignored */
    case GTID_LOG_EVENT:
    case ANONYMOUS_GTID_LOG_EVENT:
    case PREVIOUS_GTIDS_LOG_EVENT:
1241 1242
    case TRANSACTION_CONTEXT_EVENT:
    case VIEW_CHANGE_EVENT:
1243
      ev= new Ignorable_log_event(buf, fdle,
1244 1245 1246
                                  get_type_str((Log_event_type) event_type));
      break;

1247
    case TABLE_MAP_EVENT:
1248
      ev = new Table_map_log_event(buf, event_len, fdle);
1249
      break;
1250
#endif
1251
    case BEGIN_LOAD_QUERY_EVENT:
1252
      ev = new Begin_load_query_log_event(buf, event_len, fdle);
1253 1254
      break;
    case EXECUTE_LOAD_QUERY_EVENT:
1255
      ev= new Execute_load_query_log_event(buf, event_len, fdle);
1256 1257
      break;
    case INCIDENT_EVENT:
1258
      ev = new Incident_log_event(buf, event_len, fdle);
1259
      break;
1260
    case ANNOTATE_ROWS_EVENT:
1261 1262 1263 1264
      ev = new Annotate_rows_log_event(buf, event_len, fdle);
      break;
    case START_ENCRYPTION_EVENT:
      ev = new Start_encryption_log_event(buf, event_len, fdle);
1265
      break;
1266
    default:
1267 1268 1269 1270
      DBUG_PRINT("error",("Unknown event code: %d",
                          (uchar) buf[EVENT_TYPE_OFFSET]));
      ev= NULL;
      break;
1271
    }
unknown's avatar
unknown committed
1272
  }
1273
exit:
1274

unknown's avatar
unknown committed
1275 1276 1277
  if (ev)
  {
    ev->checksum_alg= alg;
1278
#ifdef MYSQL_CLIENT
unknown's avatar
unknown committed
1279 1280 1281
    if (ev->checksum_alg != BINLOG_CHECKSUM_ALG_OFF &&
        ev->checksum_alg != BINLOG_CHECKSUM_ALG_UNDEF)
      ev->crc= uint4korr(buf + (event_len));
1282
#endif
unknown's avatar
unknown committed
1283 1284
  }

1285
  DBUG_PRINT("read_event", ("%s(type_code: %u; event_len: %u)",
1286
                            ev ? ev->get_type_str() : "<unknown>",
1287
                            (uchar)buf[EVENT_TYPE_OFFSET],
1288
                            event_len));
1289
  /*
1290 1291 1292 1293 1294 1295 1296
    is_valid() are small event-specific sanity tests which are
    important; for example there are some my_malloc() in constructors
    (e.g. Query_log_event::Query_log_event(char*...)); when these
    my_malloc() fail we can't return an error out of the constructor
    (because constructor is "void") ; so instead we leave the pointer we
    wanted to allocate (e.g. 'query') to 0 and we test it in is_valid().
    Same for Format_description_log_event, member 'post_header_len'.
1297 1298

    SLAVE_EVENT is never used, so it should not be read ever.
1299
  */
1300
  if (!ev || !ev->is_valid() || (event_type == SLAVE_EVENT))
1301
  {
1302 1303
    DBUG_PRINT("error",("Found invalid event in binary log"));

1304
    delete ev;
1305
#ifdef MYSQL_CLIENT
1306
    if (!force_opt) /* then mysqlbinlog dies */
1307 1308
    {
      *error= "Found invalid event in binary log";
unknown's avatar
unknown committed
1309
      DBUG_RETURN(0);
1310
    }
1311
    ev= new Unknown_log_event(buf, fdle);
1312 1313
#else
    *error= "Found invalid event in binary log";
unknown's avatar
unknown committed
1314
    DBUG_RETURN(0);
1315
#endif
1316
  }
unknown's avatar
unknown committed
1317
  DBUG_RETURN(ev);  
unknown's avatar
unknown committed
1318 1319
}

1320

1321

1322
/* 2 utility functions for the next method */
1323

1324 1325
/**
   Read a string with length from memory.
1326

1327 1328 1329 1330 1331
   This function reads the string-with-length stored at
   <code>src</code> and extract the length into <code>*len</code> and
   a pointer to the start of the string into <code>*dst</code>. The
   string can then be copied using <code>memcpy()</code> with the
   number of bytes given in <code>*len</code>.
1332

1333 1334 1335 1336 1337 1338 1339 1340
   @param src Pointer to variable holding a pointer to the memory to
              read the string from.
   @param dst Pointer to variable holding a pointer where the actual
              string starts. Starting from this position, the string
              can be copied using @c memcpy().
   @param len Pointer to variable where the length will be stored.
   @param end One-past-the-end of the memory where the string is
              stored.
1341

1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
   @return    Zero if the entire string can be copied successfully,
              @c UINT_MAX if the length could not be read from memory
              (that is, if <code>*src >= end</code>), otherwise the
              number of bytes that are missing to read the full
              string, which happends <code>*dst + *len >= end</code>.
*/
static int
get_str_len_and_pointer(const Log_event::Byte **src,
                        const char **dst,
                        uint *len,
                        const Log_event::Byte *end)
1353
{
1354 1355 1356 1357
  if (*src >= end)
    return -1;       // Will be UINT_MAX in two-complement arithmetics
  uint length= **src;
  if (length > 0)
1358
  {
1359 1360 1361
    if (*src + length >= end)
      return (int)(*src + length - end + 1);   // Number of bytes missing
    *dst= (char *)*src + 1;                    // Will be copied later
1362
  }
1363 1364
  *len= length;
  *src+= length + 1;
1365
  return 0;
1366 1367
}

1368 1369 1370
static void copy_str_and_move(const char **src, 
                              Log_event::Byte **dst, 
                              size_t len)
1371
{
1372 1373 1374 1375 1376
  memcpy(*dst, *src, len);
  *src= (const char *)*dst;
  (*dst)+= len;
  *(*dst)++= 0;
}
1377

1378

1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
#ifndef DBUG_OFF
static char const *
code_name(int code)
{
  static char buf[255];
  switch (code) {
  case Q_FLAGS2_CODE: return "Q_FLAGS2_CODE";
  case Q_SQL_MODE_CODE: return "Q_SQL_MODE_CODE";
  case Q_CATALOG_CODE: return "Q_CATALOG_CODE";
  case Q_AUTO_INCREMENT: return "Q_AUTO_INCREMENT";
  case Q_CHARSET_CODE: return "Q_CHARSET_CODE";
  case Q_TIME_ZONE_CODE: return "Q_TIME_ZONE_CODE";
  case Q_CATALOG_NZ_CODE: return "Q_CATALOG_NZ_CODE";
  case Q_LC_TIME_NAMES_CODE: return "Q_LC_TIME_NAMES_CODE";
  case Q_CHARSET_DATABASE_CODE: return "Q_CHARSET_DATABASE_CODE";
  case Q_TABLE_MAP_FOR_UPDATE_CODE: return "Q_TABLE_MAP_FOR_UPDATE_CODE";
  case Q_MASTER_DATA_WRITTEN_CODE: return "Q_MASTER_DATA_WRITTEN_CODE";
  case Q_HRNOW: return "Q_HRNOW";
1397
  }
1398 1399
  sprintf(buf, "CODE#%d", code);
  return buf;
1400
}
1401
#endif
1402

1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
#define VALIDATE_BYTES_READ(CUR_POS, START, EVENT_LEN)      \
  do {                                                      \
       uchar *cur_pos= (uchar *)CUR_POS;                    \
       uchar *start= (uchar *)START;                        \
       uint len= EVENT_LEN;                                 \
       uint bytes_read= (uint)(cur_pos - start);            \
       DBUG_PRINT("info", ("Bytes read: %u event_len:%u.\n",\
             bytes_read, len));                             \
       if (bytes_read >= len)                               \
         DBUG_VOID_RETURN;                                  \
  } while (0)
1414

1415
/**
1416
   Macro to check that there is enough space to read from memory.
1417

1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
   @param PTR Pointer to memory
   @param END End of memory
   @param CNT Number of bytes that should be read.
 */
#define CHECK_SPACE(PTR,END,CNT)                      \
  do {                                                \
    DBUG_PRINT("info", ("Read %s", code_name(pos[-1]))); \
    if ((PTR) + (CNT) > (END)) {                      \
      DBUG_PRINT("info", ("query= 0"));               \
      query= 0;                                       \
      DBUG_VOID_RETURN;                               \
    }                                                 \
  } while (0)
1431 1432 1433


/**
1434
  This is used by the SQL slave thread to prepare the event before execution.
1435
*/
1436 1437 1438 1439 1440 1441
Query_log_event::Query_log_event(const char* buf, uint event_len,
                                 const Format_description_log_event
                                 *description_event,
                                 Log_event_type event_type)
  :Log_event(buf, description_event), data_buf(0), query(NullS),
   db(NullS), catalog_len(0), status_vars_len(0),
1442
   flags2_inited(0), sql_mode_inited(0), charset_inited(0), flags2(0),
1443 1444 1445
   auto_increment_increment(1), auto_increment_offset(1),
   time_zone_len(0), lc_time_names_number(0), charset_database_number(0),
   table_map_for_update(0), master_data_written(0)
1446
{
1447 1448 1449 1450 1451 1452 1453
  ulong data_len;
  uint32 tmp;
  uint8 common_header_len, post_header_len;
  Log_event::Byte *start;
  const Log_event::Byte *end;
  bool catalog_nz= 1;
  DBUG_ENTER("Query_log_event::Query_log_event(char*,...)");
1454

1455 1456 1457 1458 1459 1460
  memset(&user, 0, sizeof(user));
  memset(&host, 0, sizeof(host));
  common_header_len= description_event->common_header_len;
  post_header_len= description_event->post_header_len[event_type-1];
  DBUG_PRINT("info",("event_len: %u  common_header_len: %d  post_header_len: %d",
                     event_len, common_header_len, post_header_len));
1461
  
1462 1463 1464 1465 1466 1467 1468 1469 1470
  /*
    We test if the event's length is sensible, and if so we compute data_len.
    We cannot rely on QUERY_HEADER_LEN here as it would not be format-tolerant.
    We use QUERY_HEADER_MINIMAL_LEN which is the same for 3.23, 4.0 & 5.0.
  */
  if (event_len < (uint)(common_header_len + post_header_len))
    DBUG_VOID_RETURN;				
  data_len = event_len - (common_header_len + post_header_len);
  buf+= common_header_len;
1471
  
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
  thread_id = slave_proxy_id = uint4korr(buf + Q_THREAD_ID_OFFSET);
  exec_time = uint4korr(buf + Q_EXEC_TIME_OFFSET);
  db_len = (uchar)buf[Q_DB_LEN_OFFSET]; // TODO: add a check of all *_len vars
  error_code = uint2korr(buf + Q_ERR_CODE_OFFSET);

  /*
    5.0 format starts here.
    Depending on the format, we may or not have affected/warnings etc
    The remnent post-header to be parsed has length:
  */
  tmp= post_header_len - QUERY_HEADER_MINIMAL_LEN; 
  if (tmp)
1484
  {
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
    status_vars_len= uint2korr(buf + Q_STATUS_VARS_LEN_OFFSET);
    /*
      Check if status variable length is corrupt and will lead to very
      wrong data. We could be even more strict and require data_len to
      be even bigger, but this will suffice to catch most corruption
      errors that can lead to a crash.
    */
    if (status_vars_len > MY_MIN(data_len, MAX_SIZE_LOG_EVENT_STATUS))
    {
      DBUG_PRINT("info", ("status_vars_len (%u) > data_len (%lu); query= 0",
                          status_vars_len, data_len));
      query= 0;
      DBUG_VOID_RETURN;
    }
    data_len-= status_vars_len;
    DBUG_PRINT("info", ("Query_log_event has status_vars_len: %u",
                        (uint) status_vars_len));
    tmp-= 2;
  } 
1504 1505
  else
  {
1506 1507 1508 1509 1510 1511 1512 1513 1514
    /*
      server version < 5.0 / binlog_version < 4 master's event is 
      relay-logged with storing the original size of the event in
      Q_MASTER_DATA_WRITTEN_CODE status variable.
      The size is to be restored at reading Q_MASTER_DATA_WRITTEN_CODE-marked
      event from the relay log.
    */
    DBUG_ASSERT(description_event->binlog_version < 4);
    master_data_written= (uint32)data_written;
1515
  }
1516 1517 1518 1519 1520
  /*
    We have parsed everything we know in the post header for QUERY_EVENT,
    the rest of post header is either comes from older version MySQL or
    dedicated to derived events (e.g. Execute_load_query...)
  */
1521

1522
  /* variable-part: the status vars; only in MySQL 5.0  */
1523
  
1524 1525 1526
  start= (Log_event::Byte*) (buf+post_header_len);
  end= (const Log_event::Byte*) (start+status_vars_len);
  for (const Log_event::Byte* pos= start; pos < end;)
1527
  {
1528 1529 1530
    switch (*pos++) {
    case Q_FLAGS2_CODE:
      CHECK_SPACE(pos, end, 4);
1531
      flags2_inited= description_event->options_written_to_bin_log;
1532 1533 1534 1535 1536
      flags2= uint4korr(pos);
      DBUG_PRINT("info",("In Query_log_event, read flags2: %lu", (ulong) flags2));
      pos+= 4;
      break;
    case Q_SQL_MODE_CODE:
1537
    {
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
      CHECK_SPACE(pos, end, 8);
      sql_mode_inited= 1;
      sql_mode= (sql_mode_t) uint8korr(pos);
      DBUG_PRINT("info",("In Query_log_event, read sql_mode: %llu", sql_mode));
      pos+= 8;
      break;
    }
    case Q_CATALOG_NZ_CODE:
      DBUG_PRINT("info", ("case Q_CATALOG_NZ_CODE; pos:%p; end:%p",
                          pos, end));
      if (get_str_len_and_pointer(&pos, &catalog, &catalog_len, end))
1549
      {
1550 1551 1552
        DBUG_PRINT("info", ("query= 0"));
        query= 0;
        DBUG_VOID_RETURN;
1553
      }
1554 1555 1556 1557 1558 1559 1560 1561
      break;
    case Q_AUTO_INCREMENT:
      CHECK_SPACE(pos, end, 4);
      auto_increment_increment= uint2korr(pos);
      auto_increment_offset=    uint2korr(pos+2);
      pos+= 4;
      break;
    case Q_CHARSET_CODE:
1562
    {
1563 1564 1565 1566 1567
      CHECK_SPACE(pos, end, 6);
      charset_inited= 1;
      memcpy(charset, pos, 6);
      pos+= 6;
      break;
1568
    }
1569
    case Q_TIME_ZONE_CODE:
1570
    {
1571
      if (get_str_len_and_pointer(&pos, &time_zone_str, &time_zone_len, end))
1572
      {
1573 1574 1575
        DBUG_PRINT("info", ("Q_TIME_ZONE_CODE: query= 0"));
        query= 0;
        DBUG_VOID_RETURN;
1576
      }
1577
      break;
1578
    }
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
    case Q_CATALOG_CODE: /* for 5.0.x where 0<=x<=3 masters */
      CHECK_SPACE(pos, end, 1);
      if ((catalog_len= *pos))
        catalog= (char*) pos+1;                           // Will be copied later
      CHECK_SPACE(pos, end, catalog_len + 2);
      pos+= catalog_len+2; // leap over end 0
      catalog_nz= 0; // catalog has end 0 in event
      break;
    case Q_LC_TIME_NAMES_CODE:
      CHECK_SPACE(pos, end, 2);
      lc_time_names_number= uint2korr(pos);
      pos+= 2;
      break;
    case Q_CHARSET_DATABASE_CODE:
      CHECK_SPACE(pos, end, 2);
      charset_database_number= uint2korr(pos);
      pos+= 2;
      break;
    case Q_TABLE_MAP_FOR_UPDATE_CODE:
      CHECK_SPACE(pos, end, 8);
      table_map_for_update= uint8korr(pos);
      pos+= 8;
      break;
    case Q_MASTER_DATA_WRITTEN_CODE:
      CHECK_SPACE(pos, end, 4);
      data_written= master_data_written= uint4korr(pos);
      pos+= 4;
      break;
    case Q_INVOKER:
1608
    {
1609 1610 1611 1612 1613
      CHECK_SPACE(pos, end, 1);
      user.length= *pos++;
      CHECK_SPACE(pos, end, user.length);
      user.str= (char *)pos;
      pos+= user.length;
1614

1615 1616 1617 1618 1619 1620
      CHECK_SPACE(pos, end, 1);
      host.length= *pos++;
      CHECK_SPACE(pos, end, host.length);
      host.str= (char *)pos;
      pos+= host.length;
      break;
1621
    }
1622
    case Q_HRNOW:
1623
    {
1624 1625 1626 1627
      CHECK_SPACE(pos, end, 3);
      when_sec_part= uint3korr(pos);
      pos+= 3;
      break;
1628
    }
1629 1630 1631 1632 1633
    default:
      /* That's why you must write status vars in growing order of code */
      DBUG_PRINT("info",("Query_log_event has unknown status vars (first has\
 code: %u), skipping the rest of them", (uint) *(pos-1)));
      pos= (const uchar*) end;                         // Break loop
1634
    }
1635
  }
1636

1637 1638 1639 1640 1641 1642 1643
#if !defined(MYSQL_CLIENT)
  if (description_event->server_version_split.kind ==
      Format_description_log_event::master_version_split::KIND_MYSQL)
  {
    // Handle MariaDB/MySQL incompatible sql_mode bits
    sql_mode_t mysql_sql_mode= sql_mode;
    sql_mode&= MODE_MASK_MYSQL_COMPATIBLE; // Unset MySQL specific bits
1644

1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
    /*
      sql_mode flags related to fraction second rounding/truncation
      have opposite meaning in MySQL vs MariaDB.
      MySQL:
       - rounds fractional seconds by default
       - truncates if TIME_TRUNCATE_FRACTIONAL is set
      MariaDB:
       - truncates fractional seconds by default
       - rounds if TIME_ROUND_FRACTIONAL is set
    */
    if (description_event->server_version_split >= fsp_version_split_mysql &&
       !(mysql_sql_mode & MODE_MYSQL80_TIME_TRUNCATE_FRACTIONAL))
      sql_mode|= MODE_TIME_ROUND_FRACTIONAL;
  }
#endif
1660

1661 1662 1663 1664 1665
  /**
    Layout for the data buffer is as follows
    +--------+-----------+------+------+---------+----+-------+
    | catlog | time_zone | user | host | db name | \0 | Query |
    +--------+-----------+------+------+---------+----+-------+
1666

1667 1668 1669 1670
    To support the query cache we append the following buffer to the above
    +-------+----------------------------------------+-------+
    |db len | uninitiatlized space of size of db len | FLAGS |
    +-------+----------------------------------------+-------+
1671

1672 1673 1674 1675
    The area of buffer starting from Query field all the way to the end belongs
    to the Query buffer and its structure is described in alloc_query() in
    sql_parse.cc
    */
1676

1677
#if !defined(MYSQL_CLIENT) && defined(HAVE_QUERY_CACHE)
1678 1679
  if (!(start= data_buf = (Log_event::Byte*) my_malloc(PSI_INSTRUMENT_ME,
                                                       catalog_len + 1
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
                                                    +  time_zone_len + 1
                                                    +  user.length + 1
                                                    +  host.length + 1
                                                    +  data_len + 1
                                                    +  sizeof(size_t)//for db_len
                                                    +  db_len + 1
                                                    +  QUERY_CACHE_DB_LENGTH_SIZE
                                                    +  QUERY_CACHE_FLAGS_SIZE,
                                                       MYF(MY_WME))))
#else
1690 1691
  if (!(start= data_buf = (Log_event::Byte*) my_malloc(PSI_INSTRUMENT_ME,
                                                       catalog_len + 1
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
                                                    +  time_zone_len + 1
                                                    +  user.length + 1
                                                    +  host.length + 1
                                                    +  data_len + 1,
                                                       MYF(MY_WME))))
#endif
      DBUG_VOID_RETURN;
  if (catalog_len)                                  // If catalog is given
  {
    /**
      @todo we should clean up and do only copy_str_and_move; it
      works for both cases.  Then we can remove the catalog_nz
      flag. /sven
    */
    if (likely(catalog_nz)) // true except if event comes from 5.0.0|1|2|3.
      copy_str_and_move(&catalog, &start, catalog_len);
    else
    {
      memcpy(start, catalog, catalog_len+1); // copy end 0
      catalog= (const char *)start;
      start+= catalog_len+1;
1713
    }
1714 1715 1716
  }
  if (time_zone_len)
    copy_str_and_move(&time_zone_str, &start, time_zone_len);
1717

1718 1719 1720 1721 1722 1723 1724 1725 1726
  if (user.length)
  {
    copy_str_and_move(&user.str, &start, user.length);
  }
  else
  {
    user.str= (char*) start;
    *(start++)= 0;
  }
1727

1728 1729 1730 1731 1732 1733 1734
  if (host.length)
    copy_str_and_move(&host.str, &start, host.length);
  else
  {
    host.str= (char*) start;
    *(start++)= 0;
  }
1735

1736 1737 1738 1739 1740 1741
  /**
    if time_zone_len or catalog_len are 0, then time_zone and catalog
    are uninitialized at this point.  shouldn't they point to the
    zero-length null-terminated strings we allocated space for in the
    my_alloc call above? /sven
  */
1742

1743 1744 1745 1746 1747 1748
  /* A 2nd variable part; this is common to all versions */ 
  memcpy((char*) start, end, data_len);          // Copy db and query
  start[data_len]= '\0';              // End query with \0 (For safetly)
  db= (char *)start;
  query= (char *)(start + db_len + 1);
  q_len= data_len - db_len -1;
1749

1750 1751 1752 1753 1754 1755 1756
  if (data_len && (data_len < db_len ||
                   data_len < q_len ||
                   data_len != (db_len + q_len + 1)))
  {
    q_len= 0;
    query= NULL;
    DBUG_VOID_RETURN;
1757
  }
1758

1759 1760
  uint32 max_length= uint32(event_len - ((const char*)(end + db_len + 1) -
                                         (buf - common_header_len)));
1761 1762 1763
  if (q_len != max_length ||
      (event_len < uint((const char*)(end + db_len + 1) -
                        (buf - common_header_len))))
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
  {
    q_len= 0;
    query= NULL;
    DBUG_VOID_RETURN;
  }
  /**
    Append the db length at the end of the buffer. This will be used by
    Query_cache::send_result_to_client() in case the query cache is On.
   */
#if !defined(MYSQL_CLIENT) && defined(HAVE_QUERY_CACHE)
  size_t db_length= (size_t)db_len;
  memcpy(start + data_len + 1, &db_length, sizeof(size_t));
#endif
  DBUG_VOID_RETURN;
1778 1779
}

1780 1781 1782 1783 1784 1785 1786
Query_compressed_log_event::Query_compressed_log_event(const char *buf,
      uint event_len,
      const Format_description_log_event
      *description_event,
      Log_event_type event_type)
      :Query_log_event(buf, event_len, description_event, event_type),
       query_buf(NULL)
1787
{
1788
  if(query)
1789
  {
1790 1791
    uint32 un_len=binlog_get_uncompress_len(query);
    if (!un_len)
1792
    {
1793 1794
      query = 0;
      return;
1795
    }
Monty's avatar
Monty committed
1796

1797
    /* Reserve one byte for '\0' */
1798 1799
    query_buf = (Log_event::Byte*)my_malloc(PSI_INSTRUMENT_ME,
                                            ALIGN_SIZE(un_len + 1), MYF(MY_WME));
1800 1801
    if(query_buf &&
       !binlog_buf_uncompress(query, (char *)query_buf, q_len, &un_len))
Monty's avatar
Monty committed
1802
    {
1803 1804 1805
      query_buf[un_len] = 0;
      query = (const char *)query_buf;
      q_len = un_len;
Monty's avatar
Monty committed
1806 1807 1808
    }
    else
    {
1809
      query= 0;
1810 1811 1812 1813
    }
  }
}

1814 1815 1816 1817
/*
  Replace a binlog event read into a packet with a dummy event. Either a
  Query_log_event that has just a comment, or if that will not fit in the
  space used for the event to be replaced, then a NULL user_var event.
1818

1819 1820 1821
  This is used when sending binlog data to a slave which does not understand
  this particular event and which is too old to support informational events
  or holes in the event stream.
Monty's avatar
Monty committed
1822

1823 1824
  This allows to write such events into the binlog on the master and still be
  able to replicate against old slaves without them breaking.
Monty's avatar
Monty committed
1825

1826 1827 1828
  Clears the flag LOG_EVENT_THREAD_SPECIFIC_F and set LOG_EVENT_SUPPRESS_USE_F.
  Overwrites the type with QUERY_EVENT (or USER_VAR_EVENT), and replaces the
  body with a minimal query / NULL user var.
Monty's avatar
Monty committed
1829

1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
  Returns zero on success, -1 if error due to too little space in original
  event. A minimum of 25 bytes (19 bytes fixed header + 6 bytes in the body)
  is needed in any event to be replaced with a dummy event.
*/
int
Query_log_event::dummy_event(String *packet, ulong ev_offset,
                             enum enum_binlog_checksum_alg checksum_alg)
{
  uchar *p= (uchar *)packet->ptr() + ev_offset;
  size_t data_len= packet->length() - ev_offset;
  uint16 flags;
  static const size_t min_user_var_event_len=
    LOG_EVENT_HEADER_LEN + UV_NAME_LEN_SIZE + 1 + UV_VAL_IS_NULL; // 25
  static const size_t min_query_event_len=
    LOG_EVENT_HEADER_LEN + QUERY_HEADER_LEN + 1 + 1; // 34
Monty's avatar
Monty committed
1845

1846 1847 1848 1849 1850
  if (checksum_alg == BINLOG_CHECKSUM_ALG_CRC32)
    data_len-= BINLOG_CHECKSUM_LEN;
  else
    DBUG_ASSERT(checksum_alg == BINLOG_CHECKSUM_ALG_UNDEF ||
                checksum_alg == BINLOG_CHECKSUM_ALG_OFF);
Monty's avatar
Monty committed
1851

1852 1853 1854
  if (data_len < min_user_var_event_len)
    /* Cannot replace with dummy, event too short. */
    return -1;
Monty's avatar
Monty committed
1855

1856 1857 1858 1859
  flags= uint2korr(p + FLAGS_OFFSET);
  flags&= ~LOG_EVENT_THREAD_SPECIFIC_F;
  flags|= LOG_EVENT_SUPPRESS_USE_F;
  int2store(p + FLAGS_OFFSET, flags);
Monty's avatar
Monty committed
1860

1861 1862 1863 1864
  if (data_len < min_query_event_len)
  {
    /*
      Have to use dummy user_var event for such a short packet.
Monty's avatar
Monty committed
1865

1866 1867 1868 1869
      This works, but the event will be considered part of an event group with
      the following event. So for example @@global.sql_slave_skip_counter=1
      will skip not only the dummy event, but also the immediately following
      event.
Monty's avatar
Monty committed
1870

1871 1872 1873 1874 1875 1876
      We write a NULL user var with the name @`!dummyvar` (or as much
      as that as will fit within the size of the original event - so
      possibly just @`!`).
    */
    static const char var_name[]= "!dummyvar";
    size_t name_len= data_len - (min_user_var_event_len - 1);
Monty's avatar
Monty committed
1877

1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
    p[EVENT_TYPE_OFFSET]= USER_VAR_EVENT;
    int4store(p + LOG_EVENT_HEADER_LEN, name_len);
    memcpy(p + LOG_EVENT_HEADER_LEN + UV_NAME_LEN_SIZE, var_name, name_len);
    p[LOG_EVENT_HEADER_LEN + UV_NAME_LEN_SIZE + name_len]= 1; // indicates NULL
  }
  else
  {
    /*
      Use a dummy query event, just a comment.
    */
    static const char message[]=
      "# Dummy event replacing event type %u that slave cannot handle.";
    char buf[sizeof(message)+1];  /* +1, as %u can expand to 3 digits. */
    uchar old_type= p[EVENT_TYPE_OFFSET];
    uchar *q= p + LOG_EVENT_HEADER_LEN;
    size_t comment_len, len;
Monty's avatar
Monty committed
1894

1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
    p[EVENT_TYPE_OFFSET]= QUERY_EVENT;
    int4store(q + Q_THREAD_ID_OFFSET, 0);
    int4store(q + Q_EXEC_TIME_OFFSET, 0);
    q[Q_DB_LEN_OFFSET]= 0;
    int2store(q + Q_ERR_CODE_OFFSET, 0);
    int2store(q + Q_STATUS_VARS_LEN_OFFSET, 0);
    q[Q_DATA_OFFSET]= 0;                    /* Zero terminator for empty db */
    q+= Q_DATA_OFFSET + 1;
    len= my_snprintf(buf, sizeof(buf), message, old_type);
    comment_len= data_len - (min_query_event_len - 1);
    if (comment_len <= len)
      memcpy(q, buf, comment_len);
    else
Monty's avatar
Monty committed
1908
    {
1909 1910
      memcpy(q, buf, len);
      memset(q+len, ' ', comment_len - len);
Monty's avatar
Monty committed
1911 1912 1913
    }
  }

1914
  if (checksum_alg == BINLOG_CHECKSUM_ALG_CRC32)
Monty's avatar
Monty committed
1915
  {
1916 1917
    ha_checksum crc= my_checksum(0, p, data_len);
    int4store(p + data_len, crc);
Monty's avatar
Monty committed
1918
  }
1919
  return 0;
Monty's avatar
Monty committed
1920 1921
}

1922 1923 1924
/*
  Replace an event (GTID event) with a BEGIN query event, to be compatible
  with an old slave.
1925
*/
1926 1927 1928
int
Query_log_event::begin_event(String *packet, ulong ev_offset,
                             enum enum_binlog_checksum_alg checksum_alg)
1929
{
1930 1931 1932 1933
  uchar *p= (uchar *)packet->ptr() + ev_offset;
  uchar *q= p + LOG_EVENT_HEADER_LEN;
  size_t data_len= packet->length() - ev_offset;
  uint16 flags;
1934

1935 1936 1937 1938 1939
  if (checksum_alg == BINLOG_CHECKSUM_ALG_CRC32)
    data_len-= BINLOG_CHECKSUM_LEN;
  else
    DBUG_ASSERT(checksum_alg == BINLOG_CHECKSUM_ALG_UNDEF ||
                checksum_alg == BINLOG_CHECKSUM_ALG_OFF);
1940

1941 1942 1943 1944 1945 1946 1947 1948
  /*
    Currently we only need to replace GTID event.
    The length of GTID differs depending on whether it contains commit id.
  */
  DBUG_ASSERT(data_len == LOG_EVENT_HEADER_LEN + GTID_HEADER_LEN ||
              data_len == LOG_EVENT_HEADER_LEN + GTID_HEADER_LEN + 2);
  if (data_len != LOG_EVENT_HEADER_LEN + GTID_HEADER_LEN &&
      data_len != LOG_EVENT_HEADER_LEN + GTID_HEADER_LEN + 2)
1949
    return 1;
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961

  flags= uint2korr(p + FLAGS_OFFSET);
  flags&= ~LOG_EVENT_THREAD_SPECIFIC_F;
  flags|= LOG_EVENT_SUPPRESS_USE_F;
  int2store(p + FLAGS_OFFSET, flags);

  p[EVENT_TYPE_OFFSET]= QUERY_EVENT;
  int4store(q + Q_THREAD_ID_OFFSET, 0);
  int4store(q + Q_EXEC_TIME_OFFSET, 0);
  q[Q_DB_LEN_OFFSET]= 0;
  int2store(q + Q_ERR_CODE_OFFSET, 0);
  if (data_len == LOG_EVENT_HEADER_LEN + GTID_HEADER_LEN)
1962
  {
1963 1964 1965
    int2store(q + Q_STATUS_VARS_LEN_OFFSET, 0);
    q[Q_DATA_OFFSET]= 0;                    /* Zero terminator for empty db */
    q+= Q_DATA_OFFSET + 1;
1966
  }
1967
  else
1968
  {
1969 1970 1971 1972 1973 1974 1975
    DBUG_ASSERT(data_len == LOG_EVENT_HEADER_LEN + GTID_HEADER_LEN + 2);
    /* Put in an empty time_zone_str to take up the extra 2 bytes. */
    int2store(q + Q_STATUS_VARS_LEN_OFFSET, 2);
    q[Q_DATA_OFFSET]= Q_TIME_ZONE_CODE;
    q[Q_DATA_OFFSET+1]= 0;           /* Zero length for empty time_zone_str */
    q[Q_DATA_OFFSET+2]= 0;                  /* Zero terminator for empty db */
    q+= Q_DATA_OFFSET + 3;
1976
  }
1977
  memcpy(q, "BEGIN", 5);
1978

1979
  if (checksum_alg == BINLOG_CHECKSUM_ALG_CRC32)
1980
  {
1981 1982
    ha_checksum crc= my_checksum(0, p, data_len);
    int4store(p + data_len, crc);
1983
  }
1984
  return 0;
1985 1986 1987
}


1988 1989 1990
/**************************************************************************
	Start_log_event_v3 methods
**************************************************************************/
1991 1992


1993 1994 1995 1996
Start_log_event_v3::Start_log_event_v3(const char* buf, uint event_len,
                                       const Format_description_log_event
                                       *description_event)
  :Log_event(buf, description_event), binlog_version(BINLOG_VERSION)
1997
{
1998
  if (event_len < LOG_EVENT_MINIMAL_HEADER_LEN + ST_COMMON_HEADER_LEN_OFFSET)
1999
  {
2000
    server_version[0]= 0;
2001 2002
    return;
  }
2003 2004 2005 2006 2007 2008 2009 2010
  buf+= LOG_EVENT_MINIMAL_HEADER_LEN;
  binlog_version= uint2korr(buf+ST_BINLOG_VER_OFFSET);
  memcpy(server_version, buf+ST_SERVER_VER_OFFSET,
	 ST_SERVER_VER_LEN);
  // prevent overrun if log is corrupted on disk
  server_version[ST_SERVER_VER_LEN-1]= 0;
  created= uint4korr(buf+ST_CREATED_OFFSET);
  dont_set_created= 1;
2011 2012
}

Monty's avatar
Monty committed
2013

2014 2015 2016 2017
/***************************************************************************
       Format_description_log_event methods
****************************************************************************/

2018
/**
2019 2020 2021 2022 2023 2024
  Format_description_log_event 1st ctor.

    Ctor. Can be used to create the event to write to the binary log (when the
    server starts or when FLUSH LOGS), or to create artificial events to parse
    binlogs from MySQL 3.23 or 4.x.
    When in a client, only the 2nd use is possible.
2025

2026 2027 2028 2029 2030 2031 2032
  @param binlog_version         the binlog version for which we want to build
                                an event. Can be 1 (=MySQL 3.23), 3 (=4.0.x
                                x>=2 and 4.1) or 4 (MySQL 5.0). Note that the
                                old 4.0 (binlog version 2) is not supported;
                                it should not be used for replication with
                                5.0.
  @param server_ver             a string containing the server version.
2033
*/
2034

2035 2036 2037
Format_description_log_event::
Format_description_log_event(uint8 binlog_ver, const char* server_ver)
  :Start_log_event_v3(), event_type_permutation(0)
2038
{
2039 2040 2041 2042 2043 2044 2045 2046 2047
  binlog_version= binlog_ver;
  switch (binlog_ver) {
  case 4: /* MySQL 5.0 */
    memcpy(server_version, ::server_version, ST_SERVER_VER_LEN);
    DBUG_EXECUTE_IF("pretend_version_50034_in_binlog",
                    strmov(server_version, "5.0.34"););
    common_header_len= LOG_EVENT_HEADER_LEN;
    number_of_event_types= LOG_EVENT_TYPES;
    /* we'll catch my_malloc() error in is_valid() */
2048 2049
    post_header_len=(uint8*) my_malloc(PSI_INSTRUMENT_ME,
                                       number_of_event_types*sizeof(uint8)
2050 2051
                                       + BINLOG_CHECKSUM_ALG_DESC_LEN,
                                       MYF(0));
2052
    /*
2053 2054 2055
      This long list of assignments is not beautiful, but I see no way to
      make it nicer, as the right members are #defines, not array members, so
      it's impossible to write a loop.
2056
    */
2057
    if (post_header_len)
2058
    {
2059 2060 2061 2062
#ifndef DBUG_OFF
      // Allows us to sanity-check that all events initialized their
      // events (see the end of this 'if' block).
      memset(post_header_len, 255, number_of_event_types*sizeof(uint8));
2063 2064
#endif

2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
      /* Note: all event types must explicitly fill in their lengths here. */
      post_header_len[START_EVENT_V3-1]= START_V3_HEADER_LEN;
      post_header_len[QUERY_EVENT-1]= QUERY_HEADER_LEN;
      post_header_len[STOP_EVENT-1]= STOP_HEADER_LEN;
      post_header_len[ROTATE_EVENT-1]= ROTATE_HEADER_LEN;
      post_header_len[INTVAR_EVENT-1]= INTVAR_HEADER_LEN;
      post_header_len[LOAD_EVENT-1]= LOAD_HEADER_LEN;
      post_header_len[SLAVE_EVENT-1]= SLAVE_HEADER_LEN;
      post_header_len[CREATE_FILE_EVENT-1]= CREATE_FILE_HEADER_LEN;
      post_header_len[APPEND_BLOCK_EVENT-1]= APPEND_BLOCK_HEADER_LEN;
      post_header_len[EXEC_LOAD_EVENT-1]= EXEC_LOAD_HEADER_LEN;
      post_header_len[DELETE_FILE_EVENT-1]= DELETE_FILE_HEADER_LEN;
      post_header_len[NEW_LOAD_EVENT-1]= NEW_LOAD_HEADER_LEN;
      post_header_len[RAND_EVENT-1]= RAND_HEADER_LEN;
      post_header_len[USER_VAR_EVENT-1]= USER_VAR_HEADER_LEN;
      post_header_len[FORMAT_DESCRIPTION_EVENT-1]= FORMAT_DESCRIPTION_HEADER_LEN;
      post_header_len[XID_EVENT-1]= XID_HEADER_LEN;
2082
      post_header_len[XA_PREPARE_LOG_EVENT-1]= XA_PREPARE_HEADER_LEN;
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
      post_header_len[BEGIN_LOAD_QUERY_EVENT-1]= BEGIN_LOAD_QUERY_HEADER_LEN;
      post_header_len[EXECUTE_LOAD_QUERY_EVENT-1]= EXECUTE_LOAD_QUERY_HEADER_LEN;
      /*
        The PRE_GA events are never be written to any binlog, but
        their lengths are included in Format_description_log_event.
        Hence, we need to be assign some value here, to avoid reading
        uninitialized memory when the array is written to disk.
      */
      post_header_len[PRE_GA_WRITE_ROWS_EVENT-1] = 0;
      post_header_len[PRE_GA_UPDATE_ROWS_EVENT-1] = 0;
      post_header_len[PRE_GA_DELETE_ROWS_EVENT-1] = 0;
2094

2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
      post_header_len[TABLE_MAP_EVENT-1]=       TABLE_MAP_HEADER_LEN;
      post_header_len[WRITE_ROWS_EVENT_V1-1]=   ROWS_HEADER_LEN_V1;
      post_header_len[UPDATE_ROWS_EVENT_V1-1]=  ROWS_HEADER_LEN_V1;
      post_header_len[DELETE_ROWS_EVENT_V1-1]=  ROWS_HEADER_LEN_V1;
      /*
        We here have the possibility to simulate a master of before we changed
        the table map id to be stored in 6 bytes: when it was stored in 4
        bytes (=> post_header_len was 6). This is used to test backward
        compatibility.
        This code can be removed after a few months (today is Dec 21st 2005),
        when we know that the 4-byte masters are not deployed anymore (check
        with Tomas Ulin first!), and the accompanying test (rpl_row_4_bytes)
        too.
      */
      DBUG_EXECUTE_IF("old_row_based_repl_4_byte_map_id_master",
                      post_header_len[TABLE_MAP_EVENT-1]=
                      post_header_len[WRITE_ROWS_EVENT_V1-1]=
                      post_header_len[UPDATE_ROWS_EVENT_V1-1]=
                      post_header_len[DELETE_ROWS_EVENT_V1-1]= 6;);
      post_header_len[INCIDENT_EVENT-1]= INCIDENT_HEADER_LEN;
      post_header_len[HEARTBEAT_LOG_EVENT-1]= 0;
      post_header_len[IGNORABLE_LOG_EVENT-1]= 0;
      post_header_len[ROWS_QUERY_LOG_EVENT-1]= 0;
      post_header_len[GTID_LOG_EVENT-1]= 0;
      post_header_len[ANONYMOUS_GTID_LOG_EVENT-1]= 0;
      post_header_len[PREVIOUS_GTIDS_LOG_EVENT-1]= 0;
      post_header_len[TRANSACTION_CONTEXT_EVENT-1]= 0;
      post_header_len[VIEW_CHANGE_EVENT-1]= 0;
      post_header_len[XA_PREPARE_LOG_EVENT-1]= 0;
      post_header_len[WRITE_ROWS_EVENT-1]=  ROWS_HEADER_LEN_V2;
      post_header_len[UPDATE_ROWS_EVENT-1]= ROWS_HEADER_LEN_V2;
      post_header_len[DELETE_ROWS_EVENT-1]= ROWS_HEADER_LEN_V2;
2127

2128 2129 2130
      // Set header length of the reserved events to 0
      memset(post_header_len + MYSQL_EVENTS_END - 1, 0,
             (MARIA_EVENTS_BEGIN - MYSQL_EVENTS_END)*sizeof(uint8));
2131

2132 2133 2134 2135 2136 2137 2138
      // Set header lengths of Maria events
      post_header_len[ANNOTATE_ROWS_EVENT-1]= ANNOTATE_ROWS_HEADER_LEN;
      post_header_len[BINLOG_CHECKPOINT_EVENT-1]=
        BINLOG_CHECKPOINT_HEADER_LEN;
      post_header_len[GTID_EVENT-1]= GTID_HEADER_LEN;
      post_header_len[GTID_LIST_EVENT-1]= GTID_LIST_HEADER_LEN;
      post_header_len[START_ENCRYPTION_EVENT-1]= START_ENCRYPTION_HEADER_LEN;
2139

2140 2141 2142 2143 2144 2145 2146 2147
      //compressed event
      post_header_len[QUERY_COMPRESSED_EVENT-1]= QUERY_HEADER_LEN;
      post_header_len[WRITE_ROWS_COMPRESSED_EVENT-1]=   ROWS_HEADER_LEN_V2;
      post_header_len[UPDATE_ROWS_COMPRESSED_EVENT-1]=  ROWS_HEADER_LEN_V2;
      post_header_len[DELETE_ROWS_COMPRESSED_EVENT-1]=  ROWS_HEADER_LEN_V2;
      post_header_len[WRITE_ROWS_COMPRESSED_EVENT_V1-1]=   ROWS_HEADER_LEN_V1;
      post_header_len[UPDATE_ROWS_COMPRESSED_EVENT_V1-1]=  ROWS_HEADER_LEN_V1;
      post_header_len[DELETE_ROWS_COMPRESSED_EVENT_V1-1]=  ROWS_HEADER_LEN_V1;
2148

2149 2150 2151 2152 2153 2154
      // Sanity-check that all post header lengths are initialized.
      int i;
      for (i=0; i<number_of_event_types; i++)
        DBUG_ASSERT(post_header_len[i] != 255);
    }
    break;
2155

2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
  case 1: /* 3.23 */
  case 3: /* 4.0.x x>=2 */
    /*
      We build an artificial (i.e. not sent by the master) event, which
      describes what those old master versions send.
    */
    if (binlog_ver==1)
      strmov(server_version, server_ver ? server_ver : "3.23");
    else
      strmov(server_version, server_ver ? server_ver : "4.0");
    common_header_len= binlog_ver==1 ? OLD_HEADER_LEN :
      LOG_EVENT_MINIMAL_HEADER_LEN;
    /*
      The first new event in binlog version 4 is Format_desc. So any event type
      after that does not exist in older versions. We use the events known by
      version 3, even if version 1 had only a subset of them (this is not a
      problem: it uses a few bytes for nothing but unifies code; it does not
      make the slave detect less corruptions).
    */
    number_of_event_types= FORMAT_DESCRIPTION_EVENT - 1;
2176 2177
    post_header_len=(uint8*) my_malloc(PSI_INSTRUMENT_ME,
                                  number_of_event_types*sizeof(uint8), MYF(0));
2178
    if (post_header_len)
2179
    {
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
      post_header_len[START_EVENT_V3-1]= START_V3_HEADER_LEN;
      post_header_len[QUERY_EVENT-1]= QUERY_HEADER_MINIMAL_LEN;
      post_header_len[STOP_EVENT-1]= 0;
      post_header_len[ROTATE_EVENT-1]= (binlog_ver==1) ? 0 : ROTATE_HEADER_LEN;
      post_header_len[INTVAR_EVENT-1]= 0;
      post_header_len[LOAD_EVENT-1]= LOAD_HEADER_LEN;
      post_header_len[SLAVE_EVENT-1]= 0;
      post_header_len[CREATE_FILE_EVENT-1]= CREATE_FILE_HEADER_LEN;
      post_header_len[APPEND_BLOCK_EVENT-1]= APPEND_BLOCK_HEADER_LEN;
      post_header_len[EXEC_LOAD_EVENT-1]= EXEC_LOAD_HEADER_LEN;
      post_header_len[DELETE_FILE_EVENT-1]= DELETE_FILE_HEADER_LEN;
      post_header_len[NEW_LOAD_EVENT-1]= post_header_len[LOAD_EVENT-1];
      post_header_len[RAND_EVENT-1]= 0;
      post_header_len[USER_VAR_EVENT-1]= 0;
2194
    }
2195 2196 2197 2198
    break;
  default: /* Includes binlog version 2 i.e. 4.0.x x<=1 */
    post_header_len= 0; /* will make is_valid() fail */
    break;
2199
  }
2200
  calc_server_version_split();
2201
  deduct_options_written_to_bin_log();
2202 2203
  checksum_alg= BINLOG_CHECKSUM_ALG_UNDEF;
  reset_crypto();
2204 2205
}

2206

2207
/**
2208 2209 2210 2211 2212
  The problem with this constructor is that the fixed header may have a
  length different from this version, but we don't know this length as we
  have not read the Format_description_log_event which says it, yet. This
  length is in the post-header of the event, but we don't know where the
  post-header starts.
2213

2214 2215 2216 2217 2218 2219
  So this type of event HAS to:
  - either have the header's length at the beginning (in the header, at a
  fixed position which will never be changed), not in the post-header. That
  would make the header be "shifted" compared to other events.
  - or have a header of size LOG_EVENT_MINIMAL_HEADER_LEN (19), in all future
  versions, so that we know for sure.
2220

2221 2222
  I (Guilhem) chose the 2nd solution. Rotate has the same constraint (because
  it is sent before Format_description_log_event).
2223 2224
*/

2225 2226 2227 2228 2229 2230 2231 2232
Format_description_log_event::
Format_description_log_event(const char* buf,
                             uint event_len,
                             const
                             Format_description_log_event*
                             description_event)
  :Start_log_event_v3(buf, event_len, description_event),
   common_header_len(0), post_header_len(NULL), event_type_permutation(0)
2233
{
2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
  DBUG_ENTER("Format_description_log_event::Format_description_log_event(char*,...)");
  if (!Start_log_event_v3::is_valid())
    DBUG_VOID_RETURN; /* sanity check */
  buf+= LOG_EVENT_MINIMAL_HEADER_LEN;
  if ((common_header_len=buf[ST_COMMON_HEADER_LEN_OFFSET]) < OLD_HEADER_LEN)
    DBUG_VOID_RETURN; /* sanity check */
  number_of_event_types=
    event_len - (LOG_EVENT_MINIMAL_HEADER_LEN + ST_COMMON_HEADER_LEN_OFFSET + 1);
  DBUG_PRINT("info", ("common_header_len=%d number_of_event_types=%d",
                      common_header_len, number_of_event_types));
  /* If alloc fails, we'll detect it in is_valid() */
2245

2246 2247
  post_header_len= (uint8*) my_memdup(PSI_INSTRUMENT_ME,
                                      buf+ST_COMMON_HEADER_LEN_OFFSET+1,
2248 2249 2250 2251 2252
                                      number_of_event_types*
                                      sizeof(*post_header_len),
                                      MYF(0));
  calc_server_version_split();
  if (!is_version_before_checksum(&server_version_split))
2253
  {
2254 2255 2256
    /* the last bytes are the checksum alg desc and value (or value's room) */
    number_of_event_types -= BINLOG_CHECKSUM_ALG_DESC_LEN;
    checksum_alg= (enum_binlog_checksum_alg)post_header_len[number_of_event_types];
2257
  }
2258
  else
2259 2260 2261
  {
    checksum_alg= BINLOG_CHECKSUM_ALG_UNDEF;
  }
2262
  deduct_options_written_to_bin_log();
2263
  reset_crypto();
2264

2265
  DBUG_VOID_RETURN;
2266 2267
}

2268
bool Format_description_log_event::start_decryption(Start_encryption_log_event* sele)
2269
{
2270
  DBUG_ASSERT(crypto_data.scheme == 0);
2271

2272 2273
  if (!sele->is_valid())
    return 1;
2274

2275 2276 2277
  memcpy(crypto_data.nonce, sele->nonce, BINLOG_NONCE_LENGTH);
  return crypto_data.init(sele->crypto_scheme, sele->key_version);
}
2278

2279 2280 2281 2282 2283 2284

Version::Version(const char *version, const char **endptr)
{
  const char *p= version;
  ulong number;
  for (uint i= 0; i<=2; i++)
2285
  {
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298
    char *r;
    number= strtoul(p, &r, 10);
    /*
      It is an invalid version if any version number greater than 255 or
      first number is not followed by '.'.
    */
    if (number < 256 && (*r == '.' || i != 0))
      m_ver[i]= (uchar) number;
    else
    {
      *this= Version();
      break;
    }
2299

2300 2301 2302 2303 2304 2305
    p= r;
    if (*r == '.')
      p++; // skip the dot
  }
  endptr[0]= p;
}
2306 2307


2308 2309 2310 2311 2312 2313 2314 2315 2316 2317
Format_description_log_event::
  master_version_split::master_version_split(const char *version)
{
  const char *p;
  static_cast<Version*>(this)[0]= Version(version, &p);
  if (strstr(p, "MariaDB") != 0 || strstr(p, "-maria-") != 0)
    kind= KIND_MARIADB;
  else
    kind= KIND_MYSQL;
}
2318 2319


2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
/**
   Splits the event's 'server_version' string into three numeric pieces stored
   into 'server_version_split':
   X.Y.Zabc (X,Y,Z numbers, a not a digit) -> {X,Y,Z}
   X.Yabc -> {X,Y,0}
   'server_version_split' is then used for lookups to find if the server which
   created this event has some known bug.
*/
void Format_description_log_event::calc_server_version_split()
{
  server_version_split= master_version_split(server_version);
2331

2332 2333 2334 2335 2336
  DBUG_PRINT("info",("Format_description_log_event::server_version_split:"
                     " '%s' %d %d %d", server_version,
                     server_version_split[0],
                     server_version_split[1], server_version_split[2]));
}
2337 2338


2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359
void Format_description_log_event::deduct_options_written_to_bin_log()
{
  options_written_to_bin_log= OPTION_AUTO_IS_NULL | OPTION_NOT_AUTOCOMMIT |
              OPTION_NO_FOREIGN_KEY_CHECKS | OPTION_RELAXED_UNIQUE_CHECKS;
  if (!server_version_split.version_is_valid() ||
      server_version_split.kind == master_version_split::KIND_MYSQL ||
      server_version_split < Version(10,5,2))
    return;
  options_written_to_bin_log|= OPTION_IF_EXISTS;
  if (server_version_split[0] == 10)
  {
    const static char v[10]={99,99,99,99,99,17,9,5,4,2};
    if (server_version_split[1] < 10 &&
        server_version_split[2] < v[server_version_split[1]])
      return;
  }
  options_written_to_bin_log|= OPTION_EXPLICIT_DEF_TIMESTAMP;

  DBUG_ASSERT(options_written_to_bin_log == OPTIONS_WRITTEN_TO_BIN_LOG);
}

2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371
/**
   @return TRUE is the event's version is earlier than one that introduced
   the replication event checksum. FALSE otherwise.
*/
bool
Format_description_log_event::is_version_before_checksum(const master_version_split
                                                         *version_split)
{
  return *version_split <
    (version_split->kind == master_version_split::KIND_MARIADB ?
     checksum_version_split_mariadb : checksum_version_split_mysql);
}
2372

2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385
/**
   @param buf buffer holding serialized FD event
   @param len netto (possible checksum is stripped off) length of the event buf
   
   @return  the version-safe checksum alg descriptor where zero
            designates no checksum, 255 - the orginator is
            checksum-unaware (effectively no checksum) and the actuall
            [1-254] range alg descriptor.
*/
enum enum_binlog_checksum_alg get_checksum_alg(const char* buf, ulong len)
{
  enum enum_binlog_checksum_alg ret;
  char version[ST_SERVER_VER_LEN];
2386

2387 2388
  DBUG_ENTER("get_checksum_alg");
  DBUG_ASSERT(buf[EVENT_TYPE_OFFSET] == FORMAT_DESCRIPTION_EVENT);
2389

2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
  memcpy(version,
         buf + LOG_EVENT_MINIMAL_HEADER_LEN + ST_SERVER_VER_OFFSET,
         ST_SERVER_VER_LEN);
  version[ST_SERVER_VER_LEN - 1]= 0;
  
  Format_description_log_event::master_version_split version_split(version);
  ret= Format_description_log_event::is_version_before_checksum(&version_split)
    ? BINLOG_CHECKSUM_ALG_UNDEF
    : (enum_binlog_checksum_alg)buf[len - BINLOG_CHECKSUM_LEN - BINLOG_CHECKSUM_ALG_DESC_LEN];
  DBUG_ASSERT(ret == BINLOG_CHECKSUM_ALG_OFF ||
              ret == BINLOG_CHECKSUM_ALG_UNDEF ||
              ret == BINLOG_CHECKSUM_ALG_CRC32);
  DBUG_RETURN(ret);
2403 2404
}

2405 2406 2407 2408
Start_encryption_log_event::Start_encryption_log_event(
    const char* buf, uint event_len,
    const Format_description_log_event* description_event)
  :Log_event(buf, description_event)
2409
{
2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
  if ((int)event_len ==
      LOG_EVENT_MINIMAL_HEADER_LEN + Start_encryption_log_event::get_data_size())
  {
    buf += LOG_EVENT_MINIMAL_HEADER_LEN;
    crypto_scheme = *(uchar*)buf;
    key_version = uint4korr(buf + BINLOG_CRYPTO_SCHEME_LENGTH);
    memcpy(nonce,
           buf + BINLOG_CRYPTO_SCHEME_LENGTH + BINLOG_KEY_VERSION_LENGTH,
           BINLOG_NONCE_LENGTH);
  }
  else
    crypto_scheme= ~0; // invalid
2422 2423
}

2424

2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440
  /**************************************************************************
        Load_log_event methods
   General note about Load_log_event: the binlogging of LOAD DATA INFILE is
   going to be changed in 5.0 (or maybe in 5.1; not decided yet).
   However, the 5.0 slave could still have to read such events (from a 4.x
   master), convert them (which just means maybe expand the header, when 5.0
   servers have a UID in events) (remember that whatever is after the header
   will be like in 4.x, as this event's format is not modified in 5.0 as we
   will use new types of events to log the new LOAD DATA INFILE features).
   To be able to read/convert, we just need to not assume that the common
   header is of length LOG_EVENT_HEADER_LEN (we must use the description
   event).
   Note that I (Guilhem) manually tested replication of a big LOAD DATA INFILE
   between 3.23 and 5.0, and between 4.0 and 5.0, and it works fine (and the
   positions displayed in SHOW SLAVE STATUS then are fine too).
  **************************************************************************/
2441 2442


2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474
/**
  @note
    The caller must do buf[event_len] = 0 before he starts using the
    constructed event.
*/
Load_log_event::Load_log_event(const char *buf, uint event_len,
                               const Format_description_log_event *description_event)
  :Log_event(buf, description_event), num_fields(0), fields(0),
   field_lens(0),field_block_len(0),
   table_name(0), db(0), fname(0), local_fname(FALSE),
   /*
     Load_log_event which comes from the binary log does not contain
     information about the type of insert which was used on the master.
     Assume that it was an ordinary, non-concurrent LOAD DATA.
    */
   is_concurrent(FALSE)
{
  DBUG_ENTER("Load_log_event");
  /*
    I (Guilhem) manually tested replication of LOAD DATA INFILE for 3.23->5.0,
    4.0->5.0 and 5.0->5.0 and it works.
  */
  if (event_len)
    copy_log_event(buf, event_len,
                   (((uchar)buf[EVENT_TYPE_OFFSET] == LOAD_EVENT) ?
                   LOAD_HEADER_LEN + 
                    description_event->common_header_len :
                    LOAD_HEADER_LEN + LOG_EVENT_HEADER_LEN),
                   description_event);
  /* otherwise it's a derived class, will call copy_log_event() itself */
  DBUG_VOID_RETURN;
}
2475

2476 2477 2478

/*
  Load_log_event::copy_log_event()
2479
*/
2480

2481 2482 2483 2484 2485 2486
int Load_log_event::copy_log_event(const char *buf, ulong event_len,
                                   int body_offset,
                                   const Format_description_log_event *description_event)
{
  DBUG_ENTER("Load_log_event::copy_log_event");
  uint data_len;
Marko Mäkelä's avatar
Marko Mäkelä committed
2487
  if ((int) event_len <= body_offset)
2488
    DBUG_RETURN(1);
2489 2490 2491 2492 2493 2494 2495 2496 2497
  char* buf_end = (char*)buf + event_len;
  /* this is the beginning of the post-header */
  const char* data_head = buf + description_event->common_header_len;
  thread_id= slave_proxy_id= uint4korr(data_head + L_THREAD_ID_OFFSET);
  exec_time = uint4korr(data_head + L_EXEC_TIME_OFFSET);
  skip_lines = uint4korr(data_head + L_SKIP_LINES_OFFSET);
  table_name_len = (uint)data_head[L_TBL_LEN_OFFSET];
  db_len = (uint)data_head[L_DB_LEN_OFFSET];
  num_fields = uint4korr(data_head + L_NUM_FIELDS_OFFSET);
2498

2499 2500 2501 2502 2503 2504 2505 2506
  /*
    Sql_ex.init() on success returns the pointer to the first byte after
    the sql_ex structure, which is the start of field lengths array.
  */
  if (!(field_lens= (uchar*)sql_ex.init((char*)buf + body_offset,
                                        buf_end,
                                        (uchar)buf[EVENT_TYPE_OFFSET] != LOAD_EVENT)))
    DBUG_RETURN(1);
2507

2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
  data_len = event_len - body_offset;
  if (num_fields > data_len) // simple sanity check against corruption
    DBUG_RETURN(1);
  for (uint i = 0; i < num_fields; i++)
    field_block_len += (uint)field_lens[i] + 1;

  fields = (char*)field_lens + num_fields;
  table_name  = fields + field_block_len;
  if (strlen(table_name) > NAME_LEN)
    goto err;
2518

2519 2520 2521 2522 2523 2524 2525 2526 2527 2528
  db = table_name + table_name_len + 1;
  DBUG_EXECUTE_IF ("simulate_invalid_address",
                   db_len = data_len;);
  fname = db + db_len + 1;
  if ((db_len > data_len) || (fname > buf_end))
    goto err;
  fname_len = (uint) strlen(fname);
  if ((fname_len > data_len) || (fname + fname_len > buf_end))
    goto err;
  // null termination is accomplished by the caller doing buf[event_len]=0
2529

2530
  DBUG_RETURN(0);
2531

2532 2533 2534 2535 2536
err:
  // Invalid event.
  table_name = 0;
  DBUG_RETURN(1);
}
2537 2538


2539 2540 2541
/**************************************************************************
  Rotate_log_event methods
**************************************************************************/
2542

2543 2544 2545 2546 2547 2548 2549 2550
Rotate_log_event::Rotate_log_event(const char* buf, uint event_len,
                                   const Format_description_log_event* description_event)
  :Log_event(buf, description_event) ,new_log_ident(0), flags(DUP_NAME)
{
  DBUG_ENTER("Rotate_log_event::Rotate_log_event(char*,...)");
  // The caller will ensure that event_len is what we have at EVENT_LEN_OFFSET
  uint8 post_header_len= description_event->post_header_len[ROTATE_EVENT-1];
  uint ident_offset;
2551
  if (event_len < (uint)(LOG_EVENT_MINIMAL_HEADER_LEN + post_header_len))
2552 2553 2554 2555 2556 2557
    DBUG_VOID_RETURN;
  buf+= LOG_EVENT_MINIMAL_HEADER_LEN;
  pos= post_header_len ? uint8korr(buf + R_POS_OFFSET) : 4;
  ident_len= (uint)(event_len - (LOG_EVENT_MINIMAL_HEADER_LEN + post_header_len));
  ident_offset= post_header_len;
  set_if_smaller(ident_len,FN_REFLEN-1);
2558
  new_log_ident= my_strndup(PSI_INSTRUMENT_ME, buf + ident_offset, (uint) ident_len, MYF(MY_WME));
2559 2560 2561
  DBUG_PRINT("debug", ("new_log_ident: '%s'", new_log_ident));
  DBUG_VOID_RETURN;
}
2562 2563


2564 2565 2566
/**************************************************************************
  Binlog_checkpoint_log_event methods
**************************************************************************/
2567

2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584
Binlog_checkpoint_log_event::Binlog_checkpoint_log_event(
       const char *buf, uint event_len,
       const Format_description_log_event *description_event)
  :Log_event(buf, description_event), binlog_file_name(0)
{
  uint8 header_size= description_event->common_header_len;
  uint8 post_header_len=
    description_event->post_header_len[BINLOG_CHECKPOINT_EVENT-1];
  if (event_len < (uint) header_size + (uint) post_header_len ||
      post_header_len < BINLOG_CHECKPOINT_HEADER_LEN)
    return;
  buf+= header_size;
  /* See uint4korr and int4store below */
  compile_time_assert(BINLOG_CHECKPOINT_HEADER_LEN == 4);
  binlog_file_len= uint4korr(buf);
  if (event_len - (header_size + post_header_len) < binlog_file_len)
    return;
2585
  binlog_file_name= my_strndup(PSI_INSTRUMENT_ME, buf + post_header_len, binlog_file_len,
2586 2587 2588
                               MYF(MY_WME));
  return;
}
2589 2590


2591 2592 2593
/**************************************************************************
        Global transaction ID stuff
**************************************************************************/
2594

2595 2596 2597 2598 2599 2600 2601 2602 2603
Gtid_log_event::Gtid_log_event(const char *buf, uint event_len,
               const Format_description_log_event *description_event)
  : Log_event(buf, description_event), seq_no(0), commit_id(0)
{
  uint8 header_size= description_event->common_header_len;
  uint8 post_header_len= description_event->post_header_len[GTID_EVENT-1];
  if (event_len < (uint) header_size + (uint) post_header_len ||
      post_header_len < GTID_HEADER_LEN)
    return;
2604

2605 2606 2607 2608 2609
  buf+= header_size;
  seq_no= uint8korr(buf);
  buf+= 8;
  domain_id= uint4korr(buf);
  buf+= 4;
2610
  flags2= *(buf++);
2611
  if (flags2 & FL_GROUP_COMMIT_ID)
2612
  {
2613 2614 2615 2616 2617 2618
    if (event_len < (uint)header_size + GTID_HEADER_LEN + 2)
    {
      seq_no= 0;                                // So is_valid() returns false
      return;
    }
    commit_id= uint8korr(buf);
2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632
    buf+= 8;
  }
  if (flags2 & (FL_PREPARED_XA | FL_COMPLETED_XA))
  {
    xid.formatID= uint4korr(buf);
    buf+= 4;

    xid.gtrid_length= (long) buf[0];
    xid.bqual_length= (long) buf[1];
    buf+= 2;

    long data_length= xid.bqual_length + xid.gtrid_length;
    memcpy(xid.data, buf, data_length);
    buf+= data_length;
2633 2634 2635
  }
}

2636

2637
/* GTID list. */
2638

2639 2640 2641
Gtid_list_log_event::Gtid_list_log_event(const char *buf, uint event_len,
               const Format_description_log_event *description_event)
  : Log_event(buf, description_event), count(0), list(0), sub_id_list(0)
2642
{
2643 2644 2645 2646 2647 2648 2649
  uint32 i;
  uint32 val;
  uint8 header_size= description_event->common_header_len;
  uint8 post_header_len= description_event->post_header_len[GTID_LIST_EVENT-1];
  if (event_len < (uint) header_size + (uint) post_header_len ||
      post_header_len < GTID_LIST_HEADER_LEN)
    return;
2650

2651 2652 2653 2654 2655 2656
  buf+= header_size;
  val= uint4korr(buf);
  count= val & ((1<<28)-1);
  gl_flags= val & ((uint32)0xf << 28);
  buf+= 4;
  if (event_len - (header_size + post_header_len) < count*element_size ||
2657 2658
      (!(list= (rpl_gtid *)my_malloc(PSI_INSTRUMENT_ME,
                            count*sizeof(*list) + (count == 0), MYF(MY_WME)))))
2659
    return;
2660

2661 2662 2663 2664 2665 2666 2667 2668 2669
  for (i= 0; i < count; ++i)
  {
    list[i].domain_id= uint4korr(buf);
    buf+= 4;
    list[i].server_id= uint4korr(buf);
    buf+= 4;
    list[i].seq_no= uint8korr(buf);
    buf+= 8;
  }
2670

2671 2672
#if defined(HAVE_REPLICATION) && !defined(MYSQL_CLIENT)
  if ((gl_flags & FLAG_IGN_GTIDS))
2673
  {
2674
    uint32 i;
2675 2676
    if (!(sub_id_list= (uint64 *)my_malloc(PSI_INSTRUMENT_ME,
                                           count*sizeof(uint64), MYF(MY_WME))))
2677 2678 2679 2680 2681 2682
    {
      my_free(list);
      list= NULL;
      return;
    }
    for (i= 0; i < count; ++i)
2683
    {
2684 2685
      if (!(sub_id_list[i]=
            rpl_global_gtid_slave_state->next_sub_id(list[i].domain_id)))
2686
      {
2687 2688 2689 2690 2691
        my_free(list);
        my_free(sub_id_list);
        list= NULL;
        sub_id_list= NULL;
        return;
2692 2693 2694
      }
    }
  }
2695
#endif
2696 2697
}

Konstantin Osipov's avatar
Konstantin Osipov committed
2698

2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711
/*
  Used to record gtid_list event while sending binlog to slave, without having to
  fully contruct the event object.
*/
bool
Gtid_list_log_event::peek(const char *event_start, size_t event_len,
                          enum enum_binlog_checksum_alg checksum_alg,
                          rpl_gtid **out_gtid_list, uint32 *out_list_len,
                          const Format_description_log_event *fdev)
{
  const char *p;
  uint32 count_field, count;
  rpl_gtid *gtid_list;
2712

2713
  if (checksum_alg == BINLOG_CHECKSUM_ALG_CRC32)
2714
  {
2715 2716 2717 2718
    if (event_len > BINLOG_CHECKSUM_LEN)
      event_len-= BINLOG_CHECKSUM_LEN;
    else
      event_len= 0;
2719
  }
2720 2721 2722
  else
    DBUG_ASSERT(checksum_alg == BINLOG_CHECKSUM_ALG_UNDEF ||
                checksum_alg == BINLOG_CHECKSUM_ALG_OFF);
2723

2724 2725 2726 2727 2728 2729 2730 2731 2732
  if (event_len < (uint32)fdev->common_header_len + GTID_LIST_HEADER_LEN)
    return true;
  p= event_start + fdev->common_header_len;
  count_field= uint4korr(p);
  p+= 4;
  count= count_field & ((1<<28)-1);
  if (event_len < (uint32)fdev->common_header_len + GTID_LIST_HEADER_LEN +
      16 * count)
    return true;
2733 2734
  if (!(gtid_list= (rpl_gtid *)my_malloc(PSI_INSTRUMENT_ME,
                          sizeof(rpl_gtid)*count + (count == 0), MYF(MY_WME))))
2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747
    return true;
  *out_gtid_list= gtid_list;
  *out_list_len= count;
  while (count--)
  {
    gtid_list->domain_id= uint4korr(p);
    p+= 4;
    gtid_list->server_id= uint4korr(p);
    p+= 4;
    gtid_list->seq_no= uint8korr(p);
    p+= 8;
    ++gtid_list;
  }
2748

2749
  return false;
2750 2751 2752
}


2753 2754 2755
/**************************************************************************
	Intvar_log_event methods
**************************************************************************/
2756 2757

/*
2758 2759
  Intvar_log_event::Intvar_log_event()
*/
2760

2761 2762 2763
Intvar_log_event::Intvar_log_event(const char* buf,
                                   const Format_description_log_event* description_event)
  :Log_event(buf, description_event)
2764
{
2765
  /* The Post-Header is empty. The Variable Data part begins immediately. */
2766 2767 2768 2769
  buf+= description_event->common_header_len +
    description_event->post_header_len[INTVAR_EVENT-1];
  type= buf[I_TYPE_OFFSET];
  val= uint8korr(buf+I_VAL_OFFSET);
2770
}
2771

2772

2773 2774 2775
/*
  Intvar_log_event::get_var_type_name()
*/
2776

2777
const char* Intvar_log_event::get_var_type_name()
2778
{
2779 2780 2781 2782
  switch(type) {
  case LAST_INSERT_ID_EVENT: return "LAST_INSERT_ID";
  case INSERT_ID_EVENT: return "INSERT_ID";
  default: /* impossible */ return "UNKNOWN";
2783 2784
  }
}
2785

2786 2787

/**************************************************************************
2788
  Rand_log_event methods
2789 2790
**************************************************************************/

2791 2792 2793
Rand_log_event::Rand_log_event(const char* buf,
                               const Format_description_log_event* description_event)
  :Log_event(buf, description_event)
2794
{
2795 2796 2797 2798 2799
  /* The Post-Header is empty. The Variable Data part begins immediately. */
  buf+= description_event->common_header_len +
    description_event->post_header_len[RAND_EVENT-1];
  seed1= uint8korr(buf+RAND_SEED1_OFFSET);
  seed2= uint8korr(buf+RAND_SEED2_OFFSET);
2800
}
vinchen's avatar
vinchen committed
2801 2802


2803 2804 2805
/**************************************************************************
  Xid_log_event methods
**************************************************************************/
2806

2807 2808 2809 2810 2811 2812 2813 2814
/**
  @note
  It's ok not to use int8store here,
  as long as xid_t::set(ulonglong) and
  xid_t::get_my_xid doesn't do it either.
  We don't care about actual values of xids as long as
  identical numbers compare identically
*/
vinchen's avatar
vinchen committed
2815

2816 2817 2818
Xid_log_event::
Xid_log_event(const char* buf,
              const Format_description_log_event *description_event)
2819
  :Xid_apply_log_event(buf, description_event)
vinchen's avatar
vinchen committed
2820
{
2821 2822 2823 2824
  /* The Post-Header is empty. The Variable Data part begins immediately. */
  buf+= description_event->common_header_len +
    description_event->post_header_len[XID_EVENT-1];
  memcpy((char*) &xid, buf, sizeof(xid));
vinchen's avatar
vinchen committed
2825
}
2826

2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863
/**************************************************************************
  XA_prepare_log_event methods
**************************************************************************/
XA_prepare_log_event::
XA_prepare_log_event(const char* buf,
                     const Format_description_log_event *description_event)
  :Xid_apply_log_event(buf, description_event)
{
  buf+= description_event->common_header_len +
    description_event->post_header_len[XA_PREPARE_LOG_EVENT-1];
  one_phase= * (bool *) buf;
  buf+= 1;

  m_xid.formatID= uint4korr(buf);
  buf+= 4;
  m_xid.gtrid_length= uint4korr(buf);
  buf+= 4;
  // Todo: validity here and elsewhere checks to be replaced by MDEV-21839 fixes
  if (m_xid.gtrid_length <= 0 || m_xid.gtrid_length > MAXGTRIDSIZE)
  {
    m_xid.formatID= -1;
    return;
  }
  m_xid.bqual_length= uint4korr(buf);
  buf+= 4;
  if (m_xid.bqual_length < 0 || m_xid.bqual_length > MAXBQUALSIZE)
  {
    m_xid.formatID= -1;
    return;
  }
  DBUG_ASSERT(m_xid.gtrid_length + m_xid.bqual_length <= XIDDATASIZE);

  memcpy(m_xid.data, buf, m_xid.gtrid_length + m_xid.bqual_length);

  xid= NULL;
}

2864

2865 2866 2867
/**************************************************************************
  User_var_log_event methods
**************************************************************************/
2868

2869 2870 2871 2872 2873 2874 2875 2876 2877 2878
User_var_log_event::
User_var_log_event(const char* buf, uint event_len,
                   const Format_description_log_event* description_event)
  :Log_event(buf, description_event)
#ifndef MYSQL_CLIENT
  , deferred(false), query_id(0)
#endif
{
  bool error= false;
  const char* buf_start= buf, *buf_end= buf + event_len;
2879

2880 2881 2882 2883 2884 2885
  /* The Post-Header is empty. The Variable Data part begins immediately. */
  buf+= description_event->common_header_len +
    description_event->post_header_len[USER_VAR_EVENT-1];
  name_len= uint4korr(buf);
  /* Avoid reading out of buffer */
  if ((buf - buf_start) + UV_NAME_LEN_SIZE + name_len > event_len)
2886
  {
2887 2888
    error= true;
    goto err;
2889 2890
  }

2891
  name= (char *) buf + UV_NAME_LEN_SIZE;
2892

2893 2894 2895 2896 2897 2898
  /*
    We don't know yet is_null value, so we must assume that name_len
    may have the bigger value possible, is_null= True and there is no
    payload for val, or even that name_len is 0.
  */
  if (name + name_len + UV_VAL_IS_NULL > buf_end)
2899
  {
2900 2901
    error= true;
    goto err;
2902
  }
2903

2904 2905 2906 2907
  buf+= UV_NAME_LEN_SIZE + name_len;
  is_null= (bool) *buf;
  flags= User_var_log_event::UNDEF_F;    // defaults to UNDEF_F
  if (is_null)
2908
  {
2909 2910 2911 2912
    type= STRING_RESULT;
    charset_number= my_charset_bin.number;
    val_len= 0;
    val= 0;  
2913 2914
  }
  else
2915
  {
2916 2917
    val= (char *) (buf + UV_VAL_IS_NULL + UV_VAL_TYPE_SIZE +
                   UV_CHARSET_NUMBER_SIZE + UV_VAL_LEN_SIZE);
2918

2919 2920 2921 2922 2923
    if (val > buf_end)
    {
      error= true;
      goto err;
    }
2924

2925 2926 2927 2928
    type= (Item_result) buf[UV_VAL_IS_NULL];
    charset_number= uint4korr(buf + UV_VAL_IS_NULL + UV_VAL_TYPE_SIZE);
    val_len= uint4korr(buf + UV_VAL_IS_NULL + UV_VAL_TYPE_SIZE +
                       UV_CHARSET_NUMBER_SIZE);
2929

2930 2931 2932 2933 2934 2935 2936
    /**
      We need to check if this is from an old server
      that did not pack information for flags.
      We do this by checking if there are extra bytes
      after the packed value. If there are we take the
      extra byte and it's value is assumed to contain
      the flags value.
2937

2938 2939 2940 2941
      Old events will not have this extra byte, thence,
      we keep the flags set to UNDEF_F.
    */
    size_t bytes_read= (val + val_len) - buf_start;
2942 2943 2944 2945 2946
    if (bytes_read > event_len)
    {
      error= true;
      goto err;
    }
2947 2948 2949 2950 2951 2952 2953
    if ((data_written - bytes_read) > 0)
    {
      flags= (uint) *(buf + UV_VAL_IS_NULL + UV_VAL_TYPE_SIZE +
                    UV_CHARSET_NUMBER_SIZE + UV_VAL_LEN_SIZE +
                    val_len);
    }
  }
2954

2955 2956 2957 2958
err:
  if (unlikely(error))
    name= 0;
}
2959 2960


2961 2962 2963
/**************************************************************************
	Create_file_log_event methods
**************************************************************************/
2964

2965 2966 2967
/*
  Create_file_log_event ctor
*/
2968

2969 2970 2971
Create_file_log_event::Create_file_log_event(const char* buf, uint len,
                                             const Format_description_log_event* description_event)
  :Load_log_event(buf,0,description_event),fake_base(0),block(0),inited_from_old(0)
2972
{
2973 2974 2975 2976 2977
  DBUG_ENTER("Create_file_log_event::Create_file_log_event(char*,...)");
  uint block_offset;
  uint header_len= description_event->common_header_len;
  uint8 load_header_len= description_event->post_header_len[LOAD_EVENT-1];
  uint8 create_file_header_len= description_event->post_header_len[CREATE_FILE_EVENT-1];
2978
  if (!(event_buf= (char*) my_memdup(PSI_INSTRUMENT_ME, buf, len, MYF(MY_WME))) ||
2979 2980 2981 2982 2983 2984 2985 2986 2987
      copy_log_event(event_buf,len,
                     (((uchar)buf[EVENT_TYPE_OFFSET] == LOAD_EVENT) ?
                      load_header_len + header_len :
                      (fake_base ? (header_len+load_header_len) :
                       (header_len+load_header_len) +
                       create_file_header_len)),
                     description_event))
    DBUG_VOID_RETURN;
  if (description_event->binlog_version!=1)
2988
  {
2989 2990 2991
    file_id= uint4korr(buf + 
                       header_len +
		       load_header_len + CF_FILE_ID_OFFSET);
2992
    /*
2993 2994 2995 2996 2997 2998 2999
      Note that it's ok to use get_data_size() below, because it is computed
      with values we have already read from this event (because we called
      copy_log_event()); we are not using slave's format info to decode
      master's format, we are really using master's format info.
      Anyway, both formats should be identical (except the common_header_len)
      as these Load events are not changed between 4.0 and 5.0 (as logging of
      LOAD DATA INFILE does not use Load_log_event in 5.0).
3000

3001
      The + 1 is for \0 terminating fname  
3002
    */
3003 3004 3005 3006 3007 3008 3009
    block_offset= (description_event->common_header_len +
                   Load_log_event::get_data_size() +
                   create_file_header_len + 1);
    if (len < block_offset)
      DBUG_VOID_RETURN;
    block = (uchar*)buf + block_offset;
    block_len = len - block_offset;
3010
  }
3011
  else
3012
  {
3013 3014
    sql_ex.force_new_format();
    inited_from_old = 1;
3015
  }
3016 3017
  DBUG_VOID_RETURN;
}
3018

3019

3020 3021 3022
/**************************************************************************
	Append_block_log_event methods
**************************************************************************/
3023

3024 3025 3026
/*
  Append_block_log_event ctor
*/
3027

3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043
Append_block_log_event::Append_block_log_event(const char* buf, uint len,
                                               const Format_description_log_event* description_event)
  :Log_event(buf, description_event),block(0)
{
  DBUG_ENTER("Append_block_log_event::Append_block_log_event(char*,...)");
  uint8 common_header_len= description_event->common_header_len; 
  uint8 append_block_header_len=
    description_event->post_header_len[APPEND_BLOCK_EVENT-1];
  uint total_header_len= common_header_len+append_block_header_len;
  if (len < total_header_len)
    DBUG_VOID_RETURN;
  file_id= uint4korr(buf + common_header_len + AB_FILE_ID_OFFSET);
  block= (uchar*)buf + total_header_len;
  block_len= len - total_header_len;
  DBUG_VOID_RETURN;
}
3044

3045

3046 3047 3048
/**************************************************************************
	Delete_file_log_event methods
**************************************************************************/
3049

3050 3051 3052
/*
  Delete_file_log_event ctor
*/
3053

3054 3055 3056 3057 3058 3059 3060 3061 3062 3063
Delete_file_log_event::Delete_file_log_event(const char* buf, uint len,
                                             const Format_description_log_event* description_event)
  :Log_event(buf, description_event),file_id(0)
{
  uint8 common_header_len= description_event->common_header_len;
  uint8 delete_file_header_len= description_event->post_header_len[DELETE_FILE_EVENT-1];
  if (len < (uint)(common_header_len + delete_file_header_len))
    return;
  file_id= uint4korr(buf + common_header_len + DF_FILE_ID_OFFSET);
}
3064

3065

3066 3067 3068
/**************************************************************************
	Execute_load_log_event methods
**************************************************************************/
3069

3070 3071 3072
/*
  Execute_load_log_event ctor
*/
3073

3074 3075 3076 3077 3078 3079 3080 3081 3082 3083
Execute_load_log_event::Execute_load_log_event(const char* buf, uint len,
                                               const Format_description_log_event* description_event)
  :Log_event(buf, description_event), file_id(0)
{
  uint8 common_header_len= description_event->common_header_len;
  uint8 exec_load_header_len= description_event->post_header_len[EXEC_LOAD_EVENT-1];
  if (len < (uint)(common_header_len+exec_load_header_len))
    return;
  file_id= uint4korr(buf + common_header_len + EL_FILE_ID_OFFSET);
}
3084 3085


3086 3087 3088
/**************************************************************************
	Begin_load_query_log_event methods
**************************************************************************/
3089

3090 3091 3092 3093 3094 3095
Begin_load_query_log_event::
Begin_load_query_log_event(const char* buf, uint len,
                           const Format_description_log_event* desc_event)
  :Append_block_log_event(buf, len, desc_event)
{
}
3096

3097

3098 3099 3100
/**************************************************************************
	Execute_load_query_log_event methods
**************************************************************************/
3101

3102

3103 3104 3105 3106 3107
Execute_load_query_log_event::
Execute_load_query_log_event(const char* buf, uint event_len,
                             const Format_description_log_event* desc_event):
  Query_log_event(buf, event_len, desc_event, EXECUTE_LOAD_QUERY_EVENT),
  file_id(0), fn_pos_start(0), fn_pos_end(0)
3108
{
3109 3110
  if (!Query_log_event::is_valid())
    return;
3111

3112
  buf+= desc_event->common_header_len;
3113

3114 3115 3116
  fn_pos_start= uint4korr(buf + ELQ_FN_POS_START_OFFSET);
  fn_pos_end= uint4korr(buf + ELQ_FN_POS_END_OFFSET);
  dup_handling= (enum_load_dup_handling)(*(buf + ELQ_DUP_HANDLING_OFFSET));
3117

3118 3119 3120
  if (fn_pos_start > q_len || fn_pos_end > q_len ||
      dup_handling > LOAD_DUP_REPLACE)
    return;
3121

3122 3123
  file_id= uint4korr(buf + ELQ_FILE_ID_OFFSET);
}
3124

3125

3126
ulong Execute_load_query_log_event::get_post_header_size_for_derived()
3127
{
3128
  return EXECUTE_LOAD_QUERY_EXTRA_HEADER_LEN;
3129
}
3130

3131

3132 3133 3134 3135 3136 3137 3138
/**************************************************************************
	sql_ex_info methods
**************************************************************************/

/*
  sql_ex_info::init()
*/
vinchen's avatar
vinchen committed
3139

3140 3141
const char *sql_ex_info::init(const char *buf, const char *buf_end,
                              bool use_new_format)
vinchen's avatar
vinchen committed
3142
{
3143 3144
  cached_new_format = use_new_format;
  if (use_new_format)
vinchen's avatar
vinchen committed
3145
  {
3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160
    empty_flags=0;
    /*
      The code below assumes that buf will not disappear from
      under our feet during the lifetime of the event. This assumption
      holds true in the slave thread if the log is in new format, but is not
      the case when we have old format because we will be reusing net buffer
      to read the actual file before we write out the Create_file event.
    */
    if (read_str(&buf, buf_end, &field_term, &field_term_len) ||
        read_str(&buf, buf_end, &enclosed,   &enclosed_len) ||
        read_str(&buf, buf_end, &line_term,  &line_term_len) ||
        read_str(&buf, buf_end, &line_start, &line_start_len) ||
        read_str(&buf, buf_end, &escaped,    &escaped_len))
      return 0;
    opt_flags = *buf++;
vinchen's avatar
vinchen committed
3161 3162 3163
  }
  else
  {
Marko Mäkelä's avatar
Marko Mäkelä committed
3164 3165
    if (buf_end - buf < 7)
      return 0;                                 // Wrong data
3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183
    field_term_len= enclosed_len= line_term_len= line_start_len= escaped_len=1;
    field_term = buf++;			// Use first byte in string
    enclosed=	 buf++;
    line_term=   buf++;
    line_start=  buf++;
    escaped=     buf++;
    opt_flags =  *buf++;
    empty_flags= *buf++;
    if (empty_flags & FIELD_TERM_EMPTY)
      field_term_len=0;
    if (empty_flags & ENCLOSED_EMPTY)
      enclosed_len=0;
    if (empty_flags & LINE_TERM_EMPTY)
      line_term_len=0;
    if (empty_flags & LINE_START_EMPTY)
      line_start_len=0;
    if (empty_flags & ESCAPED_EMPTY)
      escaped_len=0;
vinchen's avatar
vinchen committed
3184
  }
3185
  return buf;
vinchen's avatar
vinchen committed
3186
}
3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208



/**************************************************************************
	Rows_log_event member functions
**************************************************************************/


Rows_log_event::Rows_log_event(const char *buf, uint event_len,
                               const Format_description_log_event
                               *description_event)
  : Log_event(buf, description_event),
    m_row_count(0),
#ifndef MYSQL_CLIENT
    m_table(NULL),
#endif
    m_table_id(0), m_rows_buf(0), m_rows_cur(0), m_rows_end(0),
    m_extra_row_data(0)
#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION)
    , m_curr_row(NULL), m_curr_row_end(NULL),
    m_key(NULL), m_key_info(NULL), m_key_nr(0),
    master_had_triggers(0)
3209
#endif
3210
{
3211 3212 3213 3214
  DBUG_ENTER("Rows_log_event::Rows_log_event(const char*,...)");
  uint8 const common_header_len= description_event->common_header_len;
  Log_event_type event_type= (Log_event_type)(uchar)buf[EVENT_TYPE_OFFSET];
  m_type= event_type;
3215 3216
  m_cols_ai.bitmap= 0;

3217
  uint8 const post_header_len= description_event->post_header_len[event_type-1];
3218

Marko Mäkelä's avatar
Marko Mäkelä committed
3219
  if (event_len < (uint)(common_header_len + post_header_len))
3220
  {
Marko Mäkelä's avatar
Marko Mäkelä committed
3221 3222
    m_cols.bitmap= 0;
    DBUG_VOID_RETURN;
3223 3224
  }

3225 3226 3227 3228
  DBUG_PRINT("enter",("event_len: %u  common_header_len: %d  "
		      "post_header_len: %d",
		      event_len, common_header_len,
		      post_header_len));
3229

3230 3231 3232
  const char *post_start= buf + common_header_len;
  post_start+= RW_MAPID_OFFSET;
  if (post_header_len == 6)
3233
  {
3234 3235 3236
    /* Master is of an intermediate source tree before 5.1.4. Id is 4 bytes */
    m_table_id= uint4korr(post_start);
    post_start+= 4;
3237
  }
3238
  else
3239
  {
3240 3241
    m_table_id= (ulong) uint6korr(post_start);
    post_start+= RW_FLAGS_OFFSET;
3242 3243
  }

3244 3245 3246 3247 3248 3249
  m_flags_pos= post_start - buf;
  m_flags= uint2korr(post_start);
  post_start+= 2;

  uint16 var_header_len= 0;
  if (post_header_len == ROWS_HEADER_LEN_V2)
3250
  {
3251 3252 3253
    /*
      Have variable length header, check length,
      which includes length bytes
3254
    */
3255
    var_header_len= uint2korr(post_start);
3256 3257 3258 3259 3260 3261 3262 3263
    /* Check length and also avoid out of buffer read */
    if (var_header_len < 2 ||
        event_len < static_cast<unsigned int>(var_header_len +
          (post_start - buf)))
    {
      m_cols.bitmap= 0;
      DBUG_VOID_RETURN;
    }
3264 3265 3266 3267 3268 3269
    var_header_len-= 2;

    /* Iterate over var-len header, extracting 'chunks' */
    const char* start= post_start + 2;
    const char* end= start + var_header_len;
    for (const char* pos= start; pos < end;)
3270
    {
3271 3272 3273
      switch(*pos++)
      {
      case RW_V_EXTRAINFO_TAG:
3274
      {
3275 3276 3277 3278 3279 3280 3281
        /* Have an 'extra info' section, read it in */
        assert((end - pos) >= EXTRA_ROW_INFO_HDR_BYTES);
        uint8 infoLen= pos[EXTRA_ROW_INFO_LEN_OFFSET];
        assert((end - pos) >= infoLen);
        /* Just store/use the first tag of this type, skip others */
        if (likely(!m_extra_row_data))
        {
3282
          m_extra_row_data= (uchar*) my_malloc(PSI_INSTRUMENT_ME, infoLen,
3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294
                                               MYF(MY_WME));
          if (likely(m_extra_row_data != NULL))
          {
            memcpy(m_extra_row_data, pos, infoLen);
          }
        }
        pos+= infoLen;
        break;
      }
      default:
        /* Unknown code, we will not understand anything further here */
        pos= end; /* Break loop */
3295
      }
3296
    }
3297
  }
3298

3299 3300 3301 3302 3303 3304 3305
  uchar const *const var_start=
    (const uchar *)buf + common_header_len + post_header_len + var_header_len;
  uchar const *const ptr_width= var_start;
  uchar *ptr_after_width= (uchar*) ptr_width;
  DBUG_PRINT("debug", ("Reading from %p", ptr_after_width));
  m_width = net_field_length(&ptr_after_width);
  DBUG_PRINT("debug", ("m_width=%lu", m_width));
3306

3307 3308
  /* Avoid reading out of buffer */
  if (ptr_after_width + (m_width + 7) / 8 > (uchar*)buf + event_len)
3309
  {
3310 3311
    m_cols.bitmap= NULL;
    DBUG_VOID_RETURN;
3312 3313
  }

3314
  /* if my_bitmap_init fails, caught in is_valid() */
3315 3316 3317 3318
  if (likely(!my_bitmap_init(&m_cols,
                          m_width <= sizeof(m_bitbuf)*8 ? m_bitbuf : NULL,
                          m_width,
                          false)))
3319
  {
3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330
    DBUG_PRINT("debug", ("Reading from %p", ptr_after_width));
    memcpy(m_cols.bitmap, ptr_after_width, (m_width + 7) / 8);
    create_last_word_mask(&m_cols);
    ptr_after_width+= (m_width + 7) / 8;
    DBUG_DUMP("m_cols", (uchar*) m_cols.bitmap, no_bytes_in_map(&m_cols));
  }
  else
  {
    // Needed because my_bitmap_init() does not set it to null on failure
    m_cols.bitmap= NULL;
    DBUG_VOID_RETURN;
3331 3332
  }

3333
  m_cols_ai.bitmap= m_cols.bitmap; /* See explanation in is_valid() */
3334

3335
  if (LOG_EVENT_IS_UPDATE_ROW(event_type))
3336
  {
3337
    DBUG_PRINT("debug", ("Reading from %p", ptr_after_width));
3338

3339 3340 3341 3342 3343
    /* if my_bitmap_init fails, caught in is_valid() */
    if (likely(!my_bitmap_init(&m_cols_ai,
                            m_width <= sizeof(m_bitbuf_ai)*8 ? m_bitbuf_ai : NULL,
                            m_width,
                            false)))
3344
    {
3345 3346 3347 3348 3349 3350
      DBUG_PRINT("debug", ("Reading from %p", ptr_after_width));
      memcpy(m_cols_ai.bitmap, ptr_after_width, (m_width + 7) / 8);
      create_last_word_mask(&m_cols_ai);
      ptr_after_width+= (m_width + 7) / 8;
      DBUG_DUMP("m_cols_ai", (uchar*) m_cols_ai.bitmap,
                no_bytes_in_map(&m_cols_ai));
3351
    }
3352
    else
3353
    {
3354 3355 3356
      // Needed because my_bitmap_init() does not set it to null on failure
      m_cols_ai.bitmap= 0;
      DBUG_VOID_RETURN;
3357 3358 3359
    }
  }

3360
  const uchar* const ptr_rows_data= (const uchar*) ptr_after_width;
3361

3362 3363
  size_t const read_size= ptr_rows_data - (const unsigned char *) buf;
  if (read_size > event_len)
3364
  {
3365
    DBUG_VOID_RETURN;
3366
  }
3367 3368 3369
  size_t const data_size= event_len - read_size;
  DBUG_PRINT("info",("m_table_id: %llu  m_flags: %d  m_width: %lu  data_size: %lu",
                     m_table_id, m_flags, m_width, (ulong) data_size));
3370

3371
  m_rows_buf= (uchar*) my_malloc(PSI_INSTRUMENT_ME, data_size, MYF(MY_WME));
3372
  if (likely((bool)m_rows_buf))
3373
  {
3374 3375
#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION)
    m_curr_row= m_rows_buf;
3376
#endif
3377 3378 3379 3380 3381 3382 3383
    m_rows_end= m_rows_buf + data_size;
    m_rows_cur= m_rows_end;
    memcpy(m_rows_buf, ptr_rows_data, data_size);
    m_rows_before_size= ptr_rows_data - (const uchar *) buf; // Get the size that before SET part
  }
  else
    m_cols.bitmap= 0; // to not free it
3384

3385 3386
  DBUG_VOID_RETURN;
}
3387

3388 3389 3390 3391 3392
void Rows_log_event::uncompress_buf()
{
  uint32 un_len = binlog_get_uncompress_len((char *)m_rows_buf);
  if (!un_len)
    return;
3393

3394
  uchar *new_buf= (uchar*) my_malloc(PSI_INSTRUMENT_ME, ALIGN_SIZE(un_len), MYF(MY_WME));
3395 3396 3397 3398
  if (new_buf)
  {
    if(!binlog_buf_uncompress((char *)m_rows_buf, (char *)new_buf,
                              (uint32)(m_rows_cur - m_rows_buf), &un_len))
3399
    {
3400 3401 3402 3403 3404 3405 3406 3407
      my_free(m_rows_buf);
      m_rows_buf = new_buf;
#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION)
      m_curr_row= m_rows_buf;
#endif
      m_rows_end= m_rows_buf + un_len;
      m_rows_cur= m_rows_end;
      return;
3408
    }
3409
    else
3410
    {
3411
      my_free(new_buf);
3412
    }
3413 3414 3415
  }
  m_cols.bitmap= 0; // catch it in is_valid
}
3416

3417 3418 3419 3420 3421 3422 3423 3424
Rows_log_event::~Rows_log_event()
{
  if (m_cols.bitmap == m_bitbuf) // no my_malloc happened
    m_cols.bitmap= 0; // so no my_free in my_bitmap_free
  my_bitmap_free(&m_cols); // To pair with my_bitmap_init().
  my_free(m_rows_buf);
  my_free(m_extra_row_data);
}
3425

3426 3427 3428
int Rows_log_event::get_data_size()
{
  int const general_type_code= get_general_type_code();
3429

3430 3431
  uchar buf[MAX_INT_WIDTH];
  uchar *end= net_store_length(buf, m_width);
3432

3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449
  DBUG_EXECUTE_IF("old_row_based_repl_4_byte_map_id_master",
                  return (int)(6 + no_bytes_in_map(&m_cols) + (end - buf) +
                  (general_type_code == UPDATE_ROWS_EVENT ? no_bytes_in_map(&m_cols_ai) : 0) +
                  m_rows_cur - m_rows_buf););
  int data_size= 0;
  Log_event_type type = get_type_code();
  bool is_v2_event= LOG_EVENT_IS_ROW_V2(type);
  if (is_v2_event)
  {
    data_size= ROWS_HEADER_LEN_V2 +
      (m_extra_row_data ?
       RW_V_TAG_LEN + m_extra_row_data[EXTRA_ROW_INFO_LEN_OFFSET]:
       0);
  }
  else
  {
    data_size= ROWS_HEADER_LEN_V1;
3450
  }
3451 3452 3453 3454 3455
  data_size+= no_bytes_in_map(&m_cols);
  data_size+= (uint) (end - buf);

  if (general_type_code == UPDATE_ROWS_EVENT)
    data_size+= no_bytes_in_map(&m_cols_ai);
3456

3457 3458
  data_size+= (uint) (m_rows_cur - m_rows_buf);
  return data_size; 
3459
}
3460

3461

3462 3463 3464
/**************************************************************************
	Annotate_rows_log_event member functions
**************************************************************************/
3465

3466 3467 3468 3469 3470 3471 3472 3473
Annotate_rows_log_event::Annotate_rows_log_event(const char *buf,
                                                 uint event_len,
                                      const Format_description_log_event *desc)
  : Log_event(buf, desc),
    m_save_thd_query_txt(0),
    m_save_thd_query_len(0),
    m_saved_thd_query(false),
    m_used_query_txt(0)
3474
{
3475 3476
  m_query_len= event_len - desc->common_header_len;
  m_query_txt= (char*) buf + desc->common_header_len;
3477
}
vinchen's avatar
vinchen committed
3478

3479
Annotate_rows_log_event::~Annotate_rows_log_event()
vinchen's avatar
vinchen committed
3480
{
3481 3482 3483 3484 3485 3486 3487 3488
  DBUG_ENTER("Annotate_rows_log_event::~Annotate_rows_log_event");
#ifndef MYSQL_CLIENT
  if (m_saved_thd_query)
    thd->set_query(m_save_thd_query_txt, m_save_thd_query_len);
  else if (m_used_query_txt)
    thd->reset_query();
#endif
  DBUG_VOID_RETURN;
vinchen's avatar
vinchen committed
3489 3490
}

3491
int Annotate_rows_log_event::get_data_size()
vinchen's avatar
vinchen committed
3492
{
3493
  return m_query_len;
vinchen's avatar
vinchen committed
3494
}
3495

3496
Log_event_type Annotate_rows_log_event::get_type_code()
3497
{
3498
  return ANNOTATE_ROWS_EVENT;
3499
}
vinchen's avatar
vinchen committed
3500

3501
bool Annotate_rows_log_event::is_valid() const
vinchen's avatar
vinchen committed
3502
{
3503
  return (m_query_txt != NULL && m_query_len != 0);
vinchen's avatar
vinchen committed
3504
}
3505 3506


3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558
/**************************************************************************
	Table_map_log_event member functions and support functions
**************************************************************************/

/**
  @page How replication of field metadata works.
  
  When a table map is created, the master first calls 
  Table_map_log_event::save_field_metadata() which calculates how many 
  values will be in the field metadata. Only those fields that require the 
  extra data are added. The method also loops through all of the fields in 
  the table calling the method Field::save_field_metadata() which returns the
  values for the field that will be saved in the metadata and replicated to
  the slave. Once all fields have been processed, the table map is written to
  the binlog adding the size of the field metadata and the field metadata to
  the end of the body of the table map.

  When a table map is read on the slave, the field metadata is read from the 
  table map and passed to the table_def class constructor which saves the 
  field metadata from the table map into an array based on the type of the 
  field. Field metadata values not present (those fields that do not use extra 
  data) in the table map are initialized as zero (0). The array size is the 
  same as the columns for the table on the slave.

  Additionally, values saved for field metadata on the master are saved as a 
  string of bytes (uchar) in the binlog. A field may require 1 or more bytes
  to store the information. In cases where values require multiple bytes 
  (e.g. values > 255), the endian-safe methods are used to properly encode 
  the values on the master and decode them on the slave. When the field
  metadata values are captured on the slave, they are stored in an array of
  type uint16. This allows the least number of casts to prevent casting bugs
  when the field metadata is used in comparisons of field attributes. When
  the field metadata is used for calculating addresses in pointer math, the
  type used is uint32. 
*/

/*
  Constructor used by slave to read the event from the binary log.
 */
#if defined(HAVE_REPLICATION)
Table_map_log_event::Table_map_log_event(const char *buf, uint event_len,
                                         const Format_description_log_event
                                         *description_event)

  : Log_event(buf, description_event),
#ifndef MYSQL_CLIENT
    m_table(NULL),
#endif
    m_dbnam(NULL), m_dblen(0), m_tblnam(NULL), m_tbllen(0),
    m_colcnt(0), m_coltype(0),
    m_memory(NULL), m_table_id(ULONGLONG_MAX), m_flags(0),
    m_data_size(0), m_field_metadata(0), m_field_metadata_size(0),
3559 3560
    m_null_bits(0), m_meta_memory(NULL),
    m_optional_metadata_len(0), m_optional_metadata(NULL)
3561
{
3562 3563 3564 3565 3566 3567 3568 3569
  unsigned int bytes_read= 0;
  DBUG_ENTER("Table_map_log_event::Table_map_log_event(const char*,uint,...)");

  uint8 common_header_len= description_event->common_header_len;
  uint8 post_header_len= description_event->post_header_len[TABLE_MAP_EVENT-1];
  DBUG_PRINT("info",("event_len: %u  common_header_len: %d  post_header_len: %d",
                     event_len, common_header_len, post_header_len));

3570
  /*
3571 3572
    Don't print debug messages when running valgrind since they can
    trigger false warnings.
3573
   */
3574 3575 3576 3577
#ifndef HAVE_valgrind
  DBUG_DUMP("event buffer", (uchar*) buf, event_len);
#endif

3578 3579 3580
	if (event_len < (uint)(common_header_len + post_header_len))
		DBUG_VOID_RETURN;

3581 3582
  /* Read the post-header */
  const char *post_start= buf + common_header_len;
3583

3584
  post_start+= TM_MAPID_OFFSET;
Marko Mäkelä's avatar
Marko Mäkelä committed
3585
  VALIDATE_BYTES_READ(post_start, buf, event_len);
3586
  if (post_header_len == 6)
3587
  {
3588 3589 3590 3591 3592 3593 3594 3595 3596
    /* Master is of an intermediate source tree before 5.1.4. Id is 4 bytes */
    m_table_id= uint4korr(post_start);
    post_start+= 4;
  }
  else
  {
    DBUG_ASSERT(post_header_len == TABLE_MAP_HEADER_LEN);
    m_table_id= (ulong) uint6korr(post_start);
    post_start+= TM_FLAGS_OFFSET;
3597 3598
  }

3599
  DBUG_ASSERT(m_table_id != ~0ULL);
3600

3601
  m_flags= uint2korr(post_start);
3602

3603 3604
  /* Read the variable part of the event */
  const char *const vpart= buf + common_header_len + post_header_len;
3605

3606 3607
  /* Extract the length of the various parts from the buffer */
  uchar const *const ptr_dblen= (uchar const*)vpart + 0;
3608
  VALIDATE_BYTES_READ(ptr_dblen, buf, event_len);
3609
  m_dblen= *(uchar*) ptr_dblen;
3610

3611 3612
  /* Length of database name + counter + terminating null */
  uchar const *const ptr_tbllen= ptr_dblen + m_dblen + 2;
3613
  VALIDATE_BYTES_READ(ptr_tbllen, buf, event_len);
3614 3615 3616 3617 3618
  m_tbllen= *(uchar*) ptr_tbllen;

  /* Length of table name + counter + terminating null */
  uchar const *const ptr_colcnt= ptr_tbllen + m_tbllen + 2;
  uchar *ptr_after_colcnt= (uchar*) ptr_colcnt;
3619
  VALIDATE_BYTES_READ(ptr_after_colcnt, buf, event_len);
3620
  m_colcnt= net_field_length(&ptr_after_colcnt);
3621

3622 3623 3624 3625
  DBUG_PRINT("info",("m_dblen: %lu  off: %ld  m_tbllen: %lu  off: %ld  m_colcnt: %lu  off: %ld",
                     (ulong) m_dblen, (long) (ptr_dblen-(const uchar*)vpart), 
                     (ulong) m_tbllen, (long) (ptr_tbllen-(const uchar*)vpart),
                     m_colcnt, (long) (ptr_colcnt-(const uchar*)vpart)));
3626

3627
  /* Allocate mem for all fields in one go. If fails, caught in is_valid() */
3628
  m_memory= (uchar*) my_multi_malloc(PSI_INSTRUMENT_ME, MYF(MY_WME),
3629 3630 3631 3632
                                     &m_dbnam, (uint) m_dblen + 1,
                                     &m_tblnam, (uint) m_tbllen + 1,
                                     &m_coltype, (uint) m_colcnt,
                                     NullS);
vinchen's avatar
vinchen committed
3633

3634
  if (m_memory)
vinchen's avatar
vinchen committed
3635
  {
3636 3637 3638 3639 3640 3641
    /* Copy the different parts into their memory */
    strncpy(const_cast<char*>(m_dbnam), (const char*)ptr_dblen  + 1, m_dblen + 1);
    strncpy(const_cast<char*>(m_tblnam), (const char*)ptr_tbllen + 1, m_tbllen + 1);
    memcpy(m_coltype, ptr_after_colcnt, m_colcnt);

    ptr_after_colcnt= ptr_after_colcnt + m_colcnt;
3642 3643 3644
    VALIDATE_BYTES_READ(ptr_after_colcnt, buf, event_len);
    m_field_metadata_size= net_field_length(&ptr_after_colcnt);
    if (m_field_metadata_size <= (m_colcnt * 2))
3645 3646
    {
      uint num_null_bytes= (m_colcnt + 7) / 8;
3647
      m_meta_memory= (uchar *)my_multi_malloc(PSI_INSTRUMENT_ME, MYF(MY_WME),
3648 3649 3650
          &m_null_bits, num_null_bytes,
          &m_field_metadata, m_field_metadata_size,
          NULL);
3651 3652 3653
      memcpy(m_field_metadata, ptr_after_colcnt, m_field_metadata_size);
      ptr_after_colcnt= (uchar*)ptr_after_colcnt + m_field_metadata_size;
      memcpy(m_null_bits, ptr_after_colcnt, num_null_bytes);
3654 3655
      ptr_after_colcnt= (unsigned char*)ptr_after_colcnt + num_null_bytes;
    }
3656 3657 3658 3659 3660 3661 3662
    else
    {
      m_coltype= NULL;
      my_free(m_memory);
      m_memory= NULL;
      DBUG_VOID_RETURN;
    }
3663 3664 3665 3666 3667 3668 3669 3670

    bytes_read= (uint) (ptr_after_colcnt - (uchar *)buf);

    /* After null_bits field, there are some new fields for extra metadata. */
    if (bytes_read < event_len)
    {
      m_optional_metadata_len= event_len - bytes_read;
      m_optional_metadata=
3671
        static_cast<unsigned char*>(my_malloc(PSI_INSTRUMENT_ME, m_optional_metadata_len, MYF(MY_WME)));
3672
      memcpy(m_optional_metadata, ptr_after_colcnt, m_optional_metadata_len);
3673
    }
vinchen's avatar
vinchen committed
3674
  }
3675 3676 3677 3678 3679 3680 3681 3682
#ifdef MYSQL_SERVER
  if (!m_table)
    DBUG_VOID_RETURN;
  binlog_type_info_array= (Binlog_type_info *)thd->alloc(m_table->s->fields *
                                                         sizeof(Binlog_type_info));
  for (uint i= 0; i <  m_table->s->fields; i++)
    binlog_type_info_array[i]= m_table->field[i]->binlog_type_info();
#endif
3683

3684
  DBUG_VOID_RETURN;
vinchen's avatar
vinchen committed
3685
}
3686 3687
#endif

3688
Table_map_log_event::~Table_map_log_event()
3689
{
3690 3691
  my_free(m_meta_memory);
  my_free(m_memory);
3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922
  my_free(m_optional_metadata);
  m_optional_metadata= NULL;
}

/**
   Parses SIGNEDNESS field.

   @param[out] vec     stores the signedness flags extracted from field.
   @param[in]  field   SIGNEDNESS field in table_map_event.
   @param[in]  length  length of the field
 */
static void parse_signedness(std::vector<bool> &vec,
                             unsigned char *field, unsigned int length)
{
  for (unsigned int i= 0; i < length; i++)
  {
    for (unsigned char c= 0x80; c != 0; c>>= 1)
      vec.push_back(field[i] & c);
  }
}

/**
   Parses DEFAULT_CHARSET field.

   @param[out] default_charset  stores collation numbers extracted from field.
   @param[in]  field   DEFAULT_CHARSET field in table_map_event.
   @param[in]  length  length of the field
 */
static void parse_default_charset(Table_map_log_event::Optional_metadata_fields::
                                  Default_charset &default_charset,
                                  unsigned char *field, unsigned int length)
{
  unsigned char* p= field;

  default_charset.default_charset= net_field_length(&p);
  while (p < field + length)
  {
    unsigned int col_index= net_field_length(&p);
    unsigned int col_charset= net_field_length(&p);

    default_charset.charset_pairs.push_back(std::make_pair(col_index,
                                                           col_charset));
  }
}

/**
   Parses COLUMN_CHARSET field.

   @param[out] vec     stores collation numbers extracted from field.
   @param[in]  field   COLUMN_CHARSET field in table_map_event.
   @param[in]  length  length of the field
 */
static void parse_column_charset(std::vector<unsigned int> &vec,
                                 unsigned char *field, unsigned int length)
{
  unsigned char* p= field;

  while (p < field + length)
    vec.push_back(net_field_length(&p));
}

/**
   Parses COLUMN_NAME field.

   @param[out] vec     stores column names extracted from field.
   @param[in]  field   COLUMN_NAME field in table_map_event.
   @param[in]  length  length of the field
 */
static void parse_column_name(std::vector<std::string> &vec,
                              unsigned char *field, unsigned int length)
{
  unsigned char* p= field;

  while (p < field + length)
  {
    unsigned len= net_field_length(&p);
    vec.push_back(std::string(reinterpret_cast<char *>(p), len));
    p+= len;
  }
}

/**
   Parses SET_STR_VALUE/ENUM_STR_VALUE field.

   @param[out] vec     stores SET/ENUM column's string values extracted from
                       field. Each SET/ENUM column's string values are stored
                       into a string separate vector. All of them are stored
                       in 'vec'.
   @param[in]  field   COLUMN_NAME field in table_map_event.
   @param[in]  length  length of the field
 */
static void parse_set_str_value(std::vector<Table_map_log_event::
                                Optional_metadata_fields::str_vector> &vec,
                                unsigned char *field, unsigned int length)
{
  unsigned char* p= field;

  while (p < field + length)
  {
    unsigned int count= net_field_length(&p);

    vec.push_back(std::vector<std::string>());
    for (unsigned int i= 0; i < count; i++)
    {
      unsigned len1= net_field_length(&p);
      vec.back().push_back(std::string(reinterpret_cast<char *>(p), len1));
      p+= len1;
    }
  }
}

/**
   Parses GEOMETRY_TYPE field.

   @param[out] vec     stores geometry column's types extracted from field.
   @param[in]  field   GEOMETRY_TYPE field in table_map_event.
   @param[in]  length  length of the field
 */
static void parse_geometry_type(std::vector<unsigned int> &vec,
                                unsigned char *field, unsigned int length)
{
  unsigned char* p= field;

  while (p < field + length)
    vec.push_back(net_field_length(&p));
}

/**
   Parses SIMPLE_PRIMARY_KEY field.

   @param[out] vec     stores primary key's column information extracted from
                       field. Each column has an index and a prefix which are
                       stored as a unit_pair. prefix is always 0 for
                       SIMPLE_PRIMARY_KEY field.
   @param[in]  field   SIMPLE_PRIMARY_KEY field in table_map_event.
   @param[in]  length  length of the field
 */
static void parse_simple_pk(std::vector<Table_map_log_event::
                            Optional_metadata_fields::uint_pair> &vec,
                            unsigned char *field, unsigned int length)
{
  unsigned char* p= field;

  while (p < field + length)
    vec.push_back(std::make_pair(net_field_length(&p), 0));
}

/**
   Parses PRIMARY_KEY_WITH_PREFIX field.

   @param[out] vec     stores primary key's column information extracted from
                       field. Each column has an index and a prefix which are
                       stored as a unit_pair.
   @param[in]  field   PRIMARY_KEY_WITH_PREFIX field in table_map_event.
   @param[in]  length  length of the field
 */

static void parse_pk_with_prefix(std::vector<Table_map_log_event::
                                 Optional_metadata_fields::uint_pair> &vec,
                                 unsigned char *field, unsigned int length)
{
  unsigned char* p= field;

  while (p < field + length)
  {
    unsigned int col_index= net_field_length(&p);
    unsigned int col_prefix= net_field_length(&p);
    vec.push_back(std::make_pair(col_index, col_prefix));
  }
}

Table_map_log_event::Optional_metadata_fields::
Optional_metadata_fields(unsigned char* optional_metadata,
                         unsigned int optional_metadata_len)
{
  unsigned char* field= optional_metadata;

  if (optional_metadata == NULL)
    return;

  while (field < optional_metadata + optional_metadata_len)
  {
    unsigned int len;
    Optional_metadata_field_type type=
      static_cast<Optional_metadata_field_type>(field[0]);

    // Get length and move field to the value.
    field++;
    len= net_field_length(&field);

    switch(type)
    {
    case SIGNEDNESS:
      parse_signedness(m_signedness, field, len);
      break;
    case DEFAULT_CHARSET:
      parse_default_charset(m_default_charset, field, len);
      break;
    case COLUMN_CHARSET:
      parse_column_charset(m_column_charset, field, len);
      break;
    case COLUMN_NAME:
      parse_column_name(m_column_name, field, len);
      break;
    case SET_STR_VALUE:
      parse_set_str_value(m_set_str_value, field, len);
      break;
    case ENUM_STR_VALUE:
      parse_set_str_value(m_enum_str_value, field, len);
      break;
    case GEOMETRY_TYPE:
      parse_geometry_type(m_geometry_type, field, len);
      break;
    case SIMPLE_PRIMARY_KEY:
      parse_simple_pk(m_primary_key, field, len);
      break;
    case PRIMARY_KEY_WITH_PREFIX:
      parse_pk_with_prefix(m_primary_key, field, len);
      break;
    case ENUM_AND_SET_DEFAULT_CHARSET:
      parse_default_charset(m_enum_and_set_default_charset, field, len);
      break;
    case ENUM_AND_SET_COLUMN_CHARSET:
      parse_column_charset(m_enum_and_set_column_charset, field, len);
      break;
    default:
      DBUG_ASSERT(0);
    }
    // next field
    field+= len;
  }
3923
}
3924

3925

3926
/**************************************************************************
3927
	Write_rows_log_event member functions
3928 3929
**************************************************************************/

3930

3931
/*
3932
  Constructor used by slave to read the event from the binary log.
3933
 */
3934 3935 3936 3937 3938
#ifdef HAVE_REPLICATION
Write_rows_log_event::Write_rows_log_event(const char *buf, uint event_len,
                                           const Format_description_log_event
                                           *description_event)
: Rows_log_event(buf, event_len, description_event)
3939
{
3940 3941
}

3942 3943 3944 3945 3946
Write_rows_compressed_log_event::Write_rows_compressed_log_event(
                                           const char *buf, uint event_len,
                                           const Format_description_log_event
                                           *description_event)
: Write_rows_log_event(buf, event_len, description_event)
vinchen's avatar
vinchen committed
3947
{
3948
  uncompress_buf();
vinchen's avatar
vinchen committed
3949
}
3950 3951 3952 3953 3954 3955
#endif


/**************************************************************************
	Delete_rows_log_event member functions
**************************************************************************/
vinchen's avatar
vinchen committed
3956

3957 3958 3959 3960 3961 3962 3963 3964
/*
  Constructor used by slave to read the event from the binary log.
 */
#ifdef HAVE_REPLICATION
Delete_rows_log_event::Delete_rows_log_event(const char *buf, uint event_len,
                                             const Format_description_log_event
                                             *description_event)
  : Rows_log_event(buf, event_len, description_event)
vinchen's avatar
vinchen committed
3965 3966 3967
{
}

3968 3969 3970 3971 3972
Delete_rows_compressed_log_event::Delete_rows_compressed_log_event(
                                           const char *buf, uint event_len,
                                           const Format_description_log_event
                                           *description_event)
  : Delete_rows_log_event(buf, event_len, description_event)
3973
{
3974
  uncompress_buf();
3975
}
3976
#endif
3977

3978 3979 3980
/**************************************************************************
	Update_rows_log_event member functions
**************************************************************************/
3981 3982 3983

Update_rows_log_event::~Update_rows_log_event()
{
3984 3985 3986 3987 3988 3989
  if (m_cols_ai.bitmap)
  {
    if (m_cols_ai.bitmap == m_bitbuf_ai) // no my_malloc happened
      m_cols_ai.bitmap= 0; // so no my_free in my_bitmap_free
    my_bitmap_free(&m_cols_ai); // To pair with my_bitmap_init().
  }
3990 3991 3992
}


3993 3994 3995 3996 3997 3998 3999 4000
/*
  Constructor used by slave to read the event from the binary log.
 */
#ifdef HAVE_REPLICATION
Update_rows_log_event::Update_rows_log_event(const char *buf, uint event_len,
                                             const
                                             Format_description_log_event
                                             *description_event)
4001
  : Rows_log_event(buf, event_len, description_event)
4002 4003
{
}
vinchen's avatar
vinchen committed
4004

4005 4006
Update_rows_compressed_log_event::Update_rows_compressed_log_event(
                                             const char *buf, uint event_len,
vinchen's avatar
vinchen committed
4007 4008 4009 4010
                                             const Format_description_log_event
                                             *description_event)
  : Update_rows_log_event(buf, event_len, description_event)
{
4011
  uncompress_buf();
vinchen's avatar
vinchen committed
4012
}
4013 4014
#endif

4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027
Incident_log_event::Incident_log_event(const char *buf, uint event_len,
                                       const Format_description_log_event *descr_event)
  : Log_event(buf, descr_event)
{
  DBUG_ENTER("Incident_log_event::Incident_log_event");
  uint8 const common_header_len=
    descr_event->common_header_len;
  uint8 const post_header_len=
    descr_event->post_header_len[INCIDENT_EVENT-1];

  DBUG_PRINT("info",("event_len: %u; common_header_len: %d; post_header_len: %d",
                     event_len, common_header_len, post_header_len));

4028 4029
  m_message.str= NULL;
  m_message.length= 0;
4030 4031 4032 4033 4034 4035 4036
  int incident_number= uint2korr(buf + common_header_len);
  if (incident_number >= INCIDENT_COUNT ||
      incident_number <= INCIDENT_NONE)
  {
    // If the incident is not recognized, this binlog event is
    // invalid.  If we set incident_number to INCIDENT_NONE, the
    // invalidity will be detected by is_valid().
4037
    m_incident= INCIDENT_NONE;
4038 4039 4040
    DBUG_VOID_RETURN;
  }
  m_incident= static_cast<Incident>(incident_number);
4041 4042
  char const *ptr= buf + common_header_len + post_header_len;
  char const *const str_end= buf + event_len;
unknown's avatar
unknown committed
4043 4044
  uint8 len= 0;                   // Assignment to keep compiler happy
  const char *str= NULL;          // Assignment to keep compiler happy
4045 4046 4047 4048 4049 4050
  if (read_str(&ptr, str_end, &str, &len))
  {
    /* Mark this event invalid */
    m_incident= INCIDENT_NONE;
    DBUG_VOID_RETURN;
  }
4051
  if (!(m_message.str= (char*) my_malloc(key_memory_log_event, len+1, MYF(MY_WME))))
4052 4053 4054 4055 4056 4057
  {
    /* Mark this event invalid */
    m_incident= INCIDENT_NONE;
    DBUG_VOID_RETURN;
  }
  strmake(m_message.str, str, len);
4058 4059 4060 4061 4062 4063 4064 4065
  m_message.length= len;
  DBUG_PRINT("info", ("m_incident: %d", m_incident));
  DBUG_VOID_RETURN;
}


Incident_log_event::~Incident_log_event()
{
4066 4067
  if (m_message.str)
    my_free(m_message.str);
4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083
}


const char *
Incident_log_event::description() const
{
  static const char *const description[]= {
    "NOTHING",                                  // Not used
    "LOST_EVENTS"
  };

  DBUG_PRINT("info", ("m_incident: %d", m_incident));
  return description[m_incident];
}


4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098
Ignorable_log_event::Ignorable_log_event(const char *buf,
                                         const Format_description_log_event
                                         *descr_event,
                                         const char *event_name)
  :Log_event(buf, descr_event), number((int) (uchar) buf[EVENT_TYPE_OFFSET]),
   description(event_name)
{
  DBUG_ENTER("Ignorable_log_event::Ignorable_log_event");
  DBUG_VOID_RETURN;
}

Ignorable_log_event::~Ignorable_log_event()
{
}

4099 4100
bool copy_event_cache_to_file_and_reinit(IO_CACHE *cache, FILE *file)
{
Oleksandr Byelkin's avatar
Oleksandr Byelkin committed
4101
  return (my_b_copy_all_to_file(cache, file) ||
4102 4103
          reinit_io_cache(cache, WRITE_CACHE, 0, FALSE, TRUE));
}