* Escaping arbitrary strings to get valid SQL literal strings. * * Replaces "'" with "''", and if not std_strings, replaces "\" with "\\". * * length is the length of the source string. (Note: if a terminating NUL * is encountered sooner, PQescapeString stops short of "length"; the behavior * is thus rather like strncpy.) * * For safety the buffer at "to" must be at least 2*length + 1 byt
| 3871 | * Returns the actual length of the output (not counting the terminating NUL). |
| 3872 | */ |
| 3873 | static size_t |
| 3874 | PQescapeStringInternal(PGconn *conn, |
| 3875 | char *to, const char *from, size_t length, |
| 3876 | int *error, |
| 3877 | int encoding, bool std_strings) |
| 3878 | { |
| 3879 | const char *source = from; |
| 3880 | char *target = to; |
| 3881 | size_t remaining = strnlen(from, length); |
| 3882 | |
| 3883 | if (error) |
| 3884 | *error = 0; |
| 3885 | |
| 3886 | while (remaining > 0) |
| 3887 | { |
| 3888 | char c = *source; |
| 3889 | int charlen; |
| 3890 | int i; |
| 3891 | |
| 3892 | /* Fast path for plain ASCII */ |
| 3893 | if (!IS_HIGHBIT_SET(c)) |
| 3894 | { |
| 3895 | /* Apply quoting if needed */ |
| 3896 | if (SQL_STR_DOUBLE(c, !std_strings)) |
| 3897 | *target++ = c; |
| 3898 | /* Copy the character */ |
| 3899 | *target++ = c; |
| 3900 | source++; |
| 3901 | remaining--; |
| 3902 | continue; |
| 3903 | } |
| 3904 | |
| 3905 | /* Slow path for possible multibyte characters */ |
| 3906 | charlen = pg_encoding_mblen(encoding, source); |
| 3907 | |
| 3908 | if (remaining < charlen) |
| 3909 | { |
| 3910 | /* |
| 3911 | * If the character is longer than the available input, report an |
| 3912 | * error if possible, and replace the string with an invalid |
| 3913 | * sequence. The invalid sequence ensures that the escaped string |
| 3914 | * will trigger an error on the server-side, even if we can't |
| 3915 | * directly report an error here. |
| 3916 | * |
| 3917 | * This isn't *that* crucial when we can report an error to the |
| 3918 | * caller, but if we can't, the caller will use this string |
| 3919 | * unmodified and it needs to be safe for parsing. |
| 3920 | * |
| 3921 | * We know there's enough space for the invalid sequence because |
| 3922 | * the "to" buffer needs to be at least 2 * length + 1 long, and |
| 3923 | * at worst we're replacing a single input byte with two invalid |
| 3924 | * bytes. |
| 3925 | */ |
| 3926 | if (error) |
| 3927 | *error = 1; |
| 3928 | if (conn) |
| 3929 | appendPQExpBufferStr(&conn->errorMessage, |
| 3930 | libpq_gettext("incomplete multibyte character\n")); |
no test coverage detected