validate.c 27.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
/* vim:set et sw=2 cin cino=t0,f0,(0,{s,>2s,n-s,^-s,e2s: */
/*
 * Copyright © Philip Withnall 2016 <philip@tecnocode.co.uk>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation; either version 2.1 of the License, or (at your
 * option) any later version.
 *
 * 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 Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

#include "validate.h"

/**
 * SECTION:validate
 * @short_description: E-mail address validation
 * @stability: Stable
 * @include: validate.h
 *
 * E-mail addresses are formally defined in a number of RFCs (references are
 * linked below), and the range of formally allowed addresses is surprisingly
 * larger than what is conventionally accepted by e-mail address validation
 * functions. The common approach of validating that an address contains
 * exactly one `@` symbol is not incorrect, and is the most appropriate level of
 * validation in most situations. Ultimately, the validity of an e-mail address
 * is determined by whether the receiving mail server accepts it. Many large
 * mail service providers restrict the addresses they hand out to (for example)
 * alphanumeric identifiers plus hyphens.
 *
 * However, in some cases, full validation against the syntax for e-mail
 * addresses defined in the RFCs is necessary. For example, when implementing
 * another RFC which deals with e-mail addresses at some point. This library
 * does that — it aims to be absolutely compliant with all existing RFCs, and
 * may be updated to comply with future RFCs as they are released.
 *
 * Some examples of valid e-mail addresses:
 *  * `x@example.com`
 *  * `"much.more unusual"@example.com`
 *  * `" "@[IPv6:2001:db8::1]`
 *
 * The final example is an address which is almost certainly not useful to
 * anybody, but it is valid nonetheless.
 *
 * E-mail address syntax has changed over time, and RFCs define some obsolete
 * syntax which **must not** be generated, but which **must** be accepted when
 * parsing. So if you are using emv_validate_email_address() to check generated
 * e-mail addresses, pass `EMV_VALIDATE_FLAGS_DISABLE_OBSOLETE` to disallow all
 * obsolete syntax. If using emv_validate_email_address() to check received or
 * inputted e-mail addresses, do not pass that flag. See
 * [RFC 5322, §4](https://tools.ietf.org/html/rfc5322#section-4) for details.
 *
 * E-mail address syntax is also closely tied to the definition of SMTP, and
 * hence to its line-based structure and support for folding whitespace, which
 * allows lines to be unambiguously wrapped with multiple newline characters.
 * This makes sense to accept when validating e-mail addresses in the context of
 * SMTP, but potentially not when validating user input, for example. Whether
 * folding whitespace is accepted is controlled by the
 * `EMV_VALIDATE_FLAGS_DISABLE_FOLDING_WHITESPACE` flag.
 *
 * Since 2012, e-mail addresses have supported internationalised characters
 * using UTF-8 due to [RFC 6532](https://tools.ietf.org/html/rfc6532). Support
 * for internationalised characters is enabled by default; pass the
 * `EMV_VALIDATE_FLAGS_DISABLE_UTF8` flag to disable it.
 *
 * Example
 * ===
 *
 * ```
 * const char *input_string = …;
 * size_t error_pos;
 *
 * if (!emv_validate_email_address (input_string,
 *                                  EMV_VALIDATE_FLAGS_NONE,
 *                                  &error_pos))
 *   {
 *     fprintf (stderr, "E-mail address invalid at offset %u\n",
 *              (unsigned int) error_pos);
 *   }
 * else
 *   {
 *     fprintf (stdout, "E-mail address valid!\n");
 *   }
 * ```
 *
 * References
 * ===
 *
 * The code is up to date with the following RFCs any their errata as of
 * September 2016:
 *  * [RFC 3629](https://tools.ietf.org/html/rfc3629)
 *  * [RFC 3696](https://tools.ietf.org/html/rfc3696)
 *  * [RFC 5234](https://tools.ietf.org/html/rfc5234)
 *  * [RFC 5321](https://tools.ietf.org/html/rfc5321)
 *  * [RFC 5322](https://tools.ietf.org/html/rfc5322)
 *  * [RFC 6532](https://tools.ietf.org/html/rfc6532)
 */

/* https://tools.ietf.org/html/rfc6532#section-3.1
 * https://tools.ietf.org/html/rfc3629#section-4 */
static bool
validate_utf8_non_ascii (const char       **utf8_non_ascii,
                         EmvValidateFlags   flags)
{
  unsigned char c1 = 0, c2 = 0, c3 = 0, c4 = 0;

  if (flags & EMV_VALIDATE_FLAGS_DISABLE_UTF8)
    return false;

  c1 = **utf8_non_ascii;
  c2 = (c1 != 0) ? *(*utf8_non_ascii + 1) : 0;
  c3 = (c2 != 0) ? *(*utf8_non_ascii + 2) : 0;
  c4 = (c3 != 0) ? *(*utf8_non_ascii + 3) : 0;

  if (c1 >= 0xc2 && c1 <= 0xdf &&
      c2 >= 0x80 && c2 <= 0xbf)
    {
      /* UTF8-2 */
      *utf8_non_ascii = *utf8_non_ascii + 2;
      return true;
    }
  else if ((c1 == 0xe0 &&
            c2 >= 0xa0 && c2 <= 0xbf &&
            c3 >= 0x80 && c3 <= 0xbf) ||
           (c1 >= 0xe1 && c1 <= 0xec &&
            c2 >= 0x80 && c2 <= 0xbf &&
            c3 >= 0x80 && c3 <= 0xbf) ||
           (c1 == 0xed &&
            c2 >= 0x80 && c2 <= 0x9f &&
            c3 >= 0x80 && c3 <= 0xbf) ||
           (c1 >= 0xee && c1 <= 0xef &&
            c2 >= 0x80 && c2 <= 0xbf &&
            c3 >= 0x80 && c3 <= 0xbf))
    {
      /* UTF8-3 */
      *utf8_non_ascii = *utf8_non_ascii + 3;
      return true;
    }
  else if ((c1 == 0xf0 &&
            c2 >= 0x90 && c2 <= 0xbf &&
            c3 >= 0x80 && c3 <= 0xbf &&
            c4 >= 0x80 && c4 <= 0xbf) ||
           (c1 >= 0xf1 && c1 <= 0xf3 &&
            c2 >= 0x80 && c2 <= 0xbf &&
            c3 >= 0x80 && c3 <= 0xbf &&
            c4 >= 0x80 && c4 <= 0xbf) ||
           (c1 == 0xf4 &&
            c2 >= 0x80 && c2 <= 0x8f &&
            c3 >= 0x80 && c3 <= 0xbf &&
            c4 >= 0x80 && c4 <= 0xbf))
    {
      /* UTF8-4 */
      *utf8_non_ascii = *utf8_non_ascii + 4;
      return true;
    }

  return false;
}

/* https://tools.ietf.org/html/rfc5234#section-B-1 */
static bool
validate_wsp (const char       **wsp,
              EmvValidateFlags   flags __attribute__((unused)))
{
  char a = **wsp;

  if (a == ' ' || a == '\t')
    {
      *wsp = *wsp + 1;
      return true;
    }

  return false;
}

/* https://tools.ietf.org/html/rfc5234#section-B-1 */
static bool
validate_crlf (const char       **crlf,
               EmvValidateFlags   flags)
{
  const char *a = *crlf;

  if (flags & EMV_VALIDATE_FLAGS_DISABLE_FOLDING_WHITESPACE)
    return false;

  if (*a == '\r' && *(a + 1) == '\n')
    {
      *crlf = *crlf + 2;
      return true;
    }

  return false;
}

/* https://tools.ietf.org/html/rfc5322#section-4.2 plus erratum 1908 */
static bool
validate_obs_fws (const char       **obs_fws,
                  EmvValidateFlags   flags)
{
  const char *crlf, *wsp;
  size_t wsp_count;

  if (flags & EMV_VALIDATE_FLAGS_DISABLE_OBSOLETE)
    return false;

  /* 1*([CRLF] WSP) */
  wsp_count = 0;

  while (true)
    {
      wsp = *obs_fws;

      crlf = wsp;
      if (validate_crlf (&crlf, flags))
        wsp = crlf;

      if (!validate_wsp (&wsp, flags))
        break;

      *obs_fws = wsp;
      wsp_count++;
    }

  return (wsp_count > 0);
}

/* https://tools.ietf.org/html/rfc5322#section-3.2.2 */
static bool
validate_fws (const char       **fws,
              EmvValidateFlags   flags)
{
  const char *obs_fws = *fws;
  const char *crlf;
  bool consumed_whitespace = false;

  if (validate_obs_fws (&obs_fws, flags))
    {
      *fws = obs_fws;
      return true;
    }

  while (validate_wsp (fws, flags))
    consumed_whitespace = true;

  crlf = *fws;

  if (!validate_crlf (&crlf, flags) ||
      !validate_wsp (&crlf, flags))
    return consumed_whitespace;

  *fws = crlf;

  while (validate_wsp (fws, flags));

  return true;
}

static bool validate_obs_no_ws_ctl (const char       **obs_no_ws_ctl,
                                    EmvValidateFlags   flags);

/* https://tools.ietf.org/html/rfc5322#section-4.1 */
static bool
validate_obs_ctext (const char       **obs_ctext,
                    EmvValidateFlags   flags)
{
  if (flags & (EMV_VALIDATE_FLAGS_DISABLE_OBSOLETE |
               EMV_VALIDATE_FLAGS_DISABLE_FOLDING_WHITESPACE))
    return false;

  return validate_obs_no_ws_ctl (obs_ctext, flags);
}

/* https://tools.ietf.org/html/rfc5322#section-3.2.2
 * https://tools.ietf.org/html/rfc6532#section-3.2 */
static bool
validate_ctext (const char       **ctext,
                EmvValidateFlags   flags)
{
  char a = **ctext;
  const char *utf8;

  if (flags & EMV_VALIDATE_FLAGS_DISABLE_FOLDING_WHITESPACE)
    return false;

  if ((a >= 33 && a <= 39) ||
      (a >= 42 && a <= 91) ||
      (a >= 93 && a <= 126))
    {
      *ctext = *ctext + 1;
      return true;
    }

  utf8 = *ctext;
  if (validate_utf8_non_ascii (&utf8, flags))
    {
      *ctext = utf8;
      return true;
    }

  return validate_obs_ctext (ctext, flags);
}

/* comment and ccontent are mutually recursive. */
static bool validate_ccontent    (const char       **ccontent,
                                  EmvValidateFlags   flags);
static bool validate_quoted_pair (const char       **quoted_pair,
                                  EmvValidateFlags   flags);

/* https://tools.ietf.org/html/rfc5322#section-3.2.2 */
static bool
validate_comment (const char       **comment,
                  EmvValidateFlags   flags)
{
  const char *fws, *ccontent;

  if (flags & EMV_VALIDATE_FLAGS_DISABLE_FOLDING_WHITESPACE)
    return false;

  if (**comment != '(')
    return false;
  *comment = *comment + 1;

  /* *([FWS] ccontent) */
  while (true)
    {
      ccontent = *comment;

      fws = ccontent;
      if (validate_fws (&fws, flags))
        ccontent = fws;

      if (!validate_ccontent (&ccontent, flags))
        break;

      *comment = ccontent;
    }

  fws = *comment;
  if (validate_fws (&fws, flags))
    *comment = fws;

  if (**comment != ')')
    return false;
  *comment = *comment + 1;

  return true;
}

/* https://tools.ietf.org/html/rfc5322#section-3.2.2 */
static bool
validate_ccontent (const char       **ccontent,
                   EmvValidateFlags   flags)
{
  const char *ctext, *quoted_pair, *comment;

  if (flags & EMV_VALIDATE_FLAGS_DISABLE_FOLDING_WHITESPACE)
    return false;

  ctext = *ccontent;
  quoted_pair = *ccontent;
  comment = *ccontent;

  if (validate_ctext (&ctext, flags))
    {
      *ccontent = ctext;
      return true;
    }

  if (validate_quoted_pair (&quoted_pair, flags))
    {
      *ccontent = quoted_pair;
      return true;
    }

  if (validate_comment (&comment, flags))
    {
      *ccontent = comment;
      return true;
    }

  /* Return the pointer which got further. */
  if (ctext >= quoted_pair && ctext >= comment)
    *ccontent = ctext;
  else if (quoted_pair >= ctext && quoted_pair >= comment)
    *ccontent = quoted_pair;
  else
    *ccontent = comment;

  return false;
}

/* https://tools.ietf.org/html/rfc5322#section-3.2.2
 *
 * CFWS = (1*([FWS] comment) [FWS]) / FWS
 */
static bool
validate_cfws (const char       **cfws,
               EmvValidateFlags   flags)
{
  const char *fws, *comment;
  size_t comment_count;

  /* 1*([FWS] comment) */
  comment_count = 0;

  while (true)
    {
      comment = *cfws;

      fws = comment;
      if (validate_fws (&fws, flags))
        comment = fws;

      if (!validate_comment (&comment, flags))
        break;

      *cfws = comment;
      comment_count++;
    }

  /* We can combine the parsing of the trailing FWSs; if we parsed zero of the
   * ([FWS] comment) strings, there *must* be a trailing FWS to be valid.
   * Otherwise, it is optional. */
  return (validate_fws (cfws, flags) || comment_count >= 1);
}

/* https://tools.ietf.org/html/rfc5322#section-3.2.3
 * https://tools.ietf.org/html/rfc5234#appendix-B.1
 * https://tools.ietf.org/html/rfc6532#section-3.2 */
static bool
validate_atext (const char       **atext,
                EmvValidateFlags   flags)
{
  char a = **atext;

  if ((a >= 'A' && a <= 'Z') ||
      (a >= 'a' && a <= 'z') ||
      (a >= '0' && a <= '9') ||
      a == '!' || a == '#' ||
      a == '$' || a == '%' ||
      a == '&' || a == '\'' ||
      a == '*' || a == '+' ||
      a == '-' || a == '/' ||
      a == '=' || a == '?' ||
      a == '^' || a == '_' ||
      a == '`' || a == '{' ||
      a == '|' || a == '}' ||
      a == '~')
    {
      *atext = *atext + 1;
      return true;
    }

  return validate_utf8_non_ascii (atext, flags);
}

/* https://tools.ietf.org/html/rfc5322#section-3.2.3 */
static bool
validate_dot_atom_text (const char       **dot_atom_text,
                        EmvValidateFlags   flags)
{
  if (!validate_atext (dot_atom_text, flags))
    return false;

  while (validate_atext (dot_atom_text, flags));

  /* *("." 1*atext) */
  while (true)
    {
      const char *inner;

      inner = *dot_atom_text;

      if (*inner != '.')
        break;
      inner++;

      if (!validate_atext (&inner, flags))
        break;

      while (validate_atext (&inner, flags));

      *dot_atom_text = inner;
    }

  return true;
}

/* https://tools.ietf.org/html/rfc5322#section-3.2.3 */
static bool
validate_dot_atom (const char       **dot_atom,
                   EmvValidateFlags   flags)
{
  const char *comment;

  comment = *dot_atom;
  if (validate_cfws (&comment, flags))
    *dot_atom = comment;

  if (!validate_dot_atom_text (dot_atom, flags))
    return false;

  comment = *dot_atom;
  if (validate_cfws (&comment, flags))
    *dot_atom = comment;

  return true;
}

/* https://tools.ietf.org/html/rfc5322#section-4.1 */
static bool
validate_obs_no_ws_ctl (const char       **obs_no_ws_ctl,
                        EmvValidateFlags   flags)
{
  char c = **obs_no_ws_ctl;

  if (flags & EMV_VALIDATE_FLAGS_DISABLE_OBSOLETE)
    return false;

  if ((c >= 1 && c <= 8) ||
      c == 11 ||
      c == 12 ||
      (c >= 14 && c <= 31) ||
      c == 127)
    {
      *obs_no_ws_ctl = *obs_no_ws_ctl + 1;
      return true;
    }

  return false;
}

/* https://tools.ietf.org/html/rfc5322#section-3.2.4 plus erratum 4692
 * https://tools.ietf.org/html/rfc6532#section-3.2 */
static bool
validate_qtext (const char       **qtext,
                EmvValidateFlags   flags)
{
  char c = **qtext;
  const char *utf8;

  if (c == ' ' || c == '!' ||
      (c >= '#' && c <= '[') ||
      (c >= ']' && c <= '~'))
    {
      *qtext = *qtext + 1;
      return true;
    }

  utf8 = *qtext;
  if (validate_utf8_non_ascii (&utf8, flags))
    {
      *qtext = utf8;
      return true;
    }

  /* obs-qtext: */
  return validate_obs_no_ws_ctl (qtext, flags);
}

/* https://tools.ietf.org/html/rfc5234#appendix-B.1
 * https://tools.ietf.org/html/rfc6532#section-3.2 */
static bool
validate_vchar (const char       **vchar,
                EmvValidateFlags   flags)
{
  char c = **vchar;

  if (c >= '\x21' && c <= '\x7e')
    {
      *vchar = *vchar + 1;
      return true;
    }

  return validate_utf8_non_ascii (vchar, flags);
}

/* https://tools.ietf.org/html/rfc5322#section-3.2.1 */
static bool
validate_quoted_pair (const char       **quoted_pair,
                      EmvValidateFlags   flags)
{
  char c;

  if (**quoted_pair != '\\')
    return false;
  *quoted_pair = *quoted_pair + 1;

  c = **quoted_pair;

  if (validate_vchar (quoted_pair, flags) ||
      validate_wsp (quoted_pair, flags))
    return true;

  /* obs-qp: */
  if (!(flags & EMV_VALIDATE_FLAGS_DISABLE_OBSOLETE) &&
      (c == 0 ||
       c == '\r' ||
       c == '\n'))
    {
      *quoted_pair = *quoted_pair + 1;
      return true;
    }

  return validate_obs_no_ws_ctl (quoted_pair, flags);
}

static bool
validate_qcontent (const char       **qcontent,
                   EmvValidateFlags   flags)
{
  const char *qtext, *quoted_pair;

  qtext = *qcontent;
  quoted_pair = *qcontent;

  if (validate_qtext (&qtext, flags))
    {
      *qcontent = qtext;
      return true;
    }

  if (validate_quoted_pair (&quoted_pair, flags))
    {
      *qcontent = quoted_pair;
      return true;
    }

  if (quoted_pair > qtext)
    *qcontent = quoted_pair;
  else
    *qcontent = qtext;

  return false;
}

/* https://tools.ietf.org/html/rfc5322#section-3.2.4 plus erratum 3135 */
static bool
validate_quoted_string (const char       **quoted_string,
                        EmvValidateFlags   flags)
{
  const char *cfws, *fws, *qcontent;
  size_t qcontent_count;

  cfws = *quoted_string;
  if (validate_cfws (&cfws, flags))
    *quoted_string = cfws;

  if (**quoted_string != '"')
    return false;
  *quoted_string = *quoted_string + 1;

  /* (1*([FWS] qcontent) [FWS]) / FWS */

  /* 1*([FWS] qcontent) */
  qcontent_count = 0;

  while (true)
    {
      qcontent = *quoted_string;

      fws = qcontent;
      if (validate_fws (&fws, flags))
        qcontent = fws;

      if (!validate_qcontent (&qcontent, flags))
        break;

      *quoted_string = qcontent;
      qcontent_count++;
    }

  /* We can combine the parsing of the trailing FWSs; if we parsed zero of the
   * ([FWS] qcontent) strings, there *must* be a trailing FWS to be valid.
   * Otherwise, it is optional. */
  if (!validate_fws (quoted_string, flags) && qcontent_count == 0)
    return false;

  if (**quoted_string != '"')
    return false;
  *quoted_string = *quoted_string + 1;

  cfws = *quoted_string;
  if (validate_cfws (&cfws, flags))
    *quoted_string = cfws;

  return true;
}

/* https://tools.ietf.org/html/rfc5322#section-3.2.3 */
static bool
validate_atom (const char       **atom,
               EmvValidateFlags   flags)
{
  const char *cfws;

  cfws = *atom;
  if (validate_cfws (&cfws, flags))
    *atom = cfws;

  if (!validate_atext (atom, flags))
    return false;

  while (validate_atext (atom, flags));

  cfws = *atom;
  if (validate_cfws (&cfws, flags))
    *atom = cfws;

  return true;
}

/* https://tools.ietf.org/html/rfc5322#section-3.2.5 */
static bool
validate_word (const char       **word,
               EmvValidateFlags   flags)
{
  const char *atom, *quoted_string;

  atom = *word;
  quoted_string = *word;

  if (validate_atom (&atom, flags))
    {
      *word = atom;
      return true;
    }

  if (validate_quoted_string (&quoted_string, flags))
    {
      *word = quoted_string;
      return true;
    }

  /* Return the pointer which got further. */
  if (atom >= quoted_string)
    *word = atom;
  else
    *word = quoted_string;

  return false;
}

/* https://tools.ietf.org/html/rfc5322#section-4.4 */
static bool
validate_obs_local_part (const char       **obs_local_part,
                         EmvValidateFlags   flags)
{
  const char *word;

  if (flags & EMV_VALIDATE_FLAGS_DISABLE_OBSOLETE)
    return false;

  if (!validate_word (obs_local_part, flags))
    return false;

  while (true)
    {
      word = *obs_local_part;

      if (*word != '.')
        break;

      word++;

      if (!validate_word (&word, flags))
        break;

      *obs_local_part = word;
    }

  return true;
}

/* https://tools.ietf.org/html/rfc5322#section-3.4.1 */
static bool
validate_local_part (const char       **local_part,
                     EmvValidateFlags   flags)
{
  const char *dot_atom, *quoted_string, *obs_local_part;
  bool is_valid_dot_atom, is_valid_quoted_string, is_valid_obs_local_part;

  dot_atom = *local_part;
  quoted_string = *local_part;
  obs_local_part = *local_part;

  is_valid_dot_atom = validate_dot_atom (&dot_atom, flags);
  is_valid_quoted_string = validate_quoted_string (&quoted_string, flags);
  is_valid_obs_local_part = validate_obs_local_part (&obs_local_part, flags);

  /* Return the pointer which got further. */
  if (is_valid_dot_atom && dot_atom >= quoted_string && dot_atom >= obs_local_part)
    *local_part = dot_atom;
  else if (is_valid_quoted_string && quoted_string >= dot_atom && quoted_string >= obs_local_part)
    *local_part = quoted_string;
  else if (is_valid_obs_local_part && obs_local_part >= dot_atom && obs_local_part >= quoted_string)
    *local_part = obs_local_part;
  else if (is_valid_dot_atom)
    *local_part = dot_atom;
  else if (is_valid_quoted_string)
    *local_part = quoted_string;
  else if (is_valid_obs_local_part)
    *local_part = obs_local_part;
  if (dot_atom >= quoted_string && dot_atom >= obs_local_part)
    *local_part = dot_atom;
  else if (quoted_string >= dot_atom && quoted_string >= obs_local_part)
    *local_part = quoted_string;
  else
    *local_part = obs_local_part;

  return (is_valid_dot_atom || is_valid_quoted_string || is_valid_obs_local_part);
}

/* https://tools.ietf.org/html/rfc5322#section-4.4 */
static bool
validate_obs_dtext (const char **obs_dtext __attribute__((unused)),
                    EmvValidateFlags flags)
{
  const char *obs_no_ws_ctl, *quoted_pair;

  if (flags & EMV_VALIDATE_FLAGS_DISABLE_OBSOLETE)
    return false;

  obs_no_ws_ctl = *obs_dtext;
  quoted_pair = *obs_dtext;

  if (validate_obs_no_ws_ctl (&obs_no_ws_ctl, flags))
    {
      *obs_dtext = obs_no_ws_ctl;
      return true;
    }

  if (validate_quoted_pair (&quoted_pair, flags))
    {
      *obs_dtext = quoted_pair;
      return true;
    }

  /* Return the pointer which got further. */
  if (obs_no_ws_ctl >= quoted_pair)
    *obs_dtext = obs_no_ws_ctl;
  else
    *obs_dtext = quoted_pair;

  return false;
}

/* https://tools.ietf.org/html/rfc5322#section-3.4.1
 * https://tools.ietf.org/html/rfc6532#section-3.2 */
static bool
validate_dtext (const char       **dtext,
                EmvValidateFlags   flags)
{
  char c = **dtext;
  const char *utf8;

  if ((c >= 33 && c <= 90) ||
      (c >= 94 && c <= 126))
    {
      *dtext = *dtext + 1;
      return true;
    }

  utf8 = *dtext;
  if (validate_utf8_non_ascii (&utf8, flags))
    {
      *dtext = utf8;
      return true;
    }

  return validate_obs_dtext (dtext, flags);
}

/* https://tools.ietf.org/html/rfc5322#section-3.4.1 */
static bool
validate_domain_literal (const char       **domain_literal,
                         EmvValidateFlags   flags)
{
  const char *comment, *dtext;

  comment = *domain_literal;
  if (validate_cfws (&comment, flags))
    *domain_literal = comment;

  if (**domain_literal != '[')
    return false;
  *domain_literal = *domain_literal + 1;

  /* *([FWS] dtext) */
  while (true)
    {
      dtext = *domain_literal;

      comment = dtext;
      if (validate_fws (&comment, flags))
        dtext = comment;

      if (!validate_dtext (&dtext, flags))
        break;

      *domain_literal = dtext;
    }

  comment = *domain_literal;
  if (validate_fws (&comment, flags))
    *domain_literal = comment;

  if (**domain_literal != ']')
    return false;
  *domain_literal = *domain_literal + 1;

  comment = *domain_literal;
  if (validate_cfws (&comment, flags))
    *domain_literal = comment;

  return true;
}

/* https://tools.ietf.org/html/rfc5322#section-4.4 */
static bool
validate_obs_domain (const char **obs_domain __attribute__((unused)),
                     EmvValidateFlags flags)
{
  const char *atom;

  if (flags & EMV_VALIDATE_FLAGS_DISABLE_OBSOLETE)
    return false;

  if (!validate_atom (obs_domain, flags))
    return false;

  while (true)
    {
      atom = *obs_domain;

      if (*atom != '.')
        break;

      atom++;

      if (!validate_atom (&atom, flags))
        break;

      *obs_domain = atom;
    }

  return true;
}

/* https://tools.ietf.org/html/rfc5322#section-3.4.1 */
static bool
validate_domain (const char       **domain,
                 EmvValidateFlags   flags)
{
  const char *dot_atom, *domain_literal, *obs_domain;
  bool is_valid_dot_atom, is_valid_domain_literal, is_valid_obs_domain;

  dot_atom = *domain;
  domain_literal = *domain;
  obs_domain = *domain;

  is_valid_dot_atom = validate_dot_atom (&dot_atom, flags);
  is_valid_domain_literal = validate_domain_literal (&domain_literal, flags);
  is_valid_obs_domain = validate_obs_domain (&obs_domain, flags);

  /* Return the pointer which got further. */
  if (is_valid_dot_atom && dot_atom >= domain_literal && dot_atom >= obs_domain)
    *domain = dot_atom;
  else if (is_valid_domain_literal && domain_literal >= dot_atom && domain_literal >= obs_domain)
    *domain = domain_literal;
  else if (is_valid_obs_domain && obs_domain >= dot_atom && obs_domain >= domain_literal)
    *domain = obs_domain;
  else if (is_valid_dot_atom)
    *domain = dot_atom;
  else if (is_valid_domain_literal)
    *domain = domain_literal;
  else if (is_valid_obs_domain)
    *domain = obs_domain;
  else if (dot_atom >= domain_literal && dot_atom >= obs_domain)
    *domain = dot_atom;
  else if (domain_literal >= dot_atom && domain_literal >= obs_domain)
    *domain = domain_literal;
  else
    *domain = obs_domain;

  return (is_valid_dot_atom || is_valid_domain_literal || is_valid_obs_domain);
}

/**
 * emv_validate_email_address:
 * @address: a string to validate
 * @address_len: number of bytes in @address, or -1 if it’s nul-terminated
 * @flags: flags which affect features enabled during validation
 * @error_pos: (out caller-allocates) (optional): return location for the offset
 *    into @address of an error, in bytes
 *
 * Validate the string given in @address to determine whether it
 * is a valid e-mail address.If it is valid, `true` is returned; otherwise,
 * `false` is returned, and @error_pos is set to the offset of the first invalid
 * byte in @address. This is guaranteed to be less than the length of @address.
 * If @error_pos is `NULL`, it is not set.
 *
 * @flags may be used to enable or disable certain features during validation,
 * such as whether to allow obsolete e-mail address syntax, or folding
 * whitespace. See the documentation for #EmvValidateFlags for details.
 *
 * Note that if handling addresses which use obsolete syntax, it is possible
 * for @address to contain nul bytes, and hence @address_len should be used
 * explicitly. If @flags contains %EMV_VALIDATE_FLAGS_DISABLE_OBSOLETE this is
 * not necessary, and all valid addresses can be handled as nul-terminated.
 *
 * Returns: `true` if @address is a valid e-mail address; `false` otherwise
 * Since: UNRELEASED
 */
bool
emv_validate_email_address (const char       *address,
                            ssize_t           address_len,
                            EmvValidateFlags  flags,
                            size_t           *error_pos)
{
  const char *original_address = address;
  const char *start_of_domain;
  size_t original_address_len;
  size_t _error_pos = 0;
  bool retval = false;

  assert (address != NULL);
  assert (!(flags & EMV_VALIDATE_FLAGS_DISABLE_OBSOLETE) || address_len >= 0);

  original_address_len = (address_len >= 0) ? (size_t) address_len : strlen (address);

  if (!validate_local_part (&address, flags))
    {
      _error_pos = address - original_address;
      goto done;
    }

  /* https://tools.ietf.org/html/rfc3696#section-3 */
  if (!(flags & EMV_VALIDATE_FLAGS_DISABLE_LENGTH) &&
      address - original_address > 64)
    {
      _error_pos = 64;
      goto done;
    }

  if (*address != '@')
    {
      _error_pos = address - original_address;
      goto done;
    }

  address += 1;  /* skip '@' */
  start_of_domain = address;

  if (!validate_domain (&address, flags))
    {
      _error_pos = address - original_address;
      goto done;
    }

  /* https://tools.ietf.org/html/rfc3696#section-3 */
  if (!(flags & EMV_VALIDATE_FLAGS_DISABLE_LENGTH) &&
      address - start_of_domain > 255)
    {
      _error_pos = start_of_domain - original_address + 255;
      goto done;
    }

  if (!(flags & EMV_VALIDATE_FLAGS_DISABLE_LENGTH) &&
      address - original_address > 320)
    {
      _error_pos = 320;
      goto done;
    }

  /* Are there any remaining characters? */
  if (*address != '\0')
    {
      _error_pos = address - original_address;
      goto done;
    }

  retval = true;

done:
  if (error_pos != NULL)
    *error_pos = _error_pos;

  assert (!retval || _error_pos == 0);
  assert (_error_pos <= original_address_len);

  return retval;
}