#include "utl_smtp.hpp" // postgres.h уже внутри — идёт первым #include "dbms_network_acl_admin/dbms_network_acl_admin.hpp" extern "C" { #include "utils/elog.h" // после postgres.h #include "catalog/pg_type.h" #include "utils/lsyscache.h" } #include #include #include #include #include #include #include #include #include #include #include #include #include using std::string; using std::unordered_map; using std::shared_ptr; using std::make_shared; /// @brief Глобальный счётчик хэндлов соединений (монотонный, уникальный). static int32 g_next_handle = 1; /// @brief Объект состояния SMTP-соединения (хранится в реестре по handle). struct UtlSmtpConn { int fd{-1}; ///< файловый дескриптор TCP-сокета int timeout_sec{-1}; ///< таймаут IO: <0 = бесконечно, 0 = не ждать, >0 = секунды bool in_data{false}; ///< находимся ли между OPEN_DATA и CLOSE_DATA string rbuf; ///< остатки приёма, накопленные между вызовами (до CRLF) }; /// @brief Реестр активных SMTP-соединений: handle → объект состояния. static unordered_map> g_conns; /// @brief Возвращает ссылку на соединение по handle или бросает INVALID_OPERATION, если хэндл невалиден/закрыт. static UtlSmtpConn& smtp_require_conn(int32 handle) { auto it = g_conns.find(handle); if (it == g_conns.end() || !it->second || it->second->fd < 0) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP.INVALID_OPERATION: invalid or closed connection handle (%d)", handle))); } return *(it->second); } /// @brief Регистрирует новое соединение в реестре и возвращает выделенный целочисленный handle. static int32 smtp_register_conn(int fd, int timeout_sec) { int32 h = g_next_handle++; auto c = make_shared(); c->fd = fd; c->timeout_sec = timeout_sec; c->in_data = false; g_conns[h] = c; return h; } /// @brief Безопасно закрывает сокет, игнорируя EINTR. static void close_fd_safe(int fd) { if (fd >= 0) { for (;;) { if (close(fd) == 0) break; if (errno == EINTR) continue; break; } } } /// @brief Закрывает и удаляет соединение из реестра (если существует). static void smtp_close_and_erase(int32 handle) { auto it = g_conns.find(handle); if (it != g_conns.end() && it->second) { close_fd_safe(it->second->fd); it->second->fd = -1; g_conns.erase(it); } } /// @brief Устанавливает/снимает неблокирующий режим на сокете (через fcntl). static void set_nonblock(int fd, bool nb) { int fl = fcntl(fd, F_GETFL, 0); if (fl < 0) return; if (nb) fl |= O_NONBLOCK; else fl &= ~O_NONBLOCK; fcntl(fd, F_SETFL, fl); } /// @brief Отправляет все данные в сокет с учётом таймаута (poll + send), выбрасывает ошибки/таймаут. static void send_all(int fd, const char* data, size_t len, int timeout_sec) { size_t off = 0; while (off < len) { struct pollfd pfd{fd, POLLOUT, 0}; int to = (timeout_sec < 0) ? -1 : timeout_sec * 1000; int pr = poll(&pfd, 1, to); if (pr <= 0) { if (pr == 0) ereport(ERROR, (errcode(ERRCODE_QUERY_CANCELED), errmsg("UTL_SMTP.TRANSIENT_ERROR: send timeout"))); if (errno == EINTR) continue; ereport(ERROR, (errcode(ERRCODE_IO_ERROR), errmsg("UTL_SMTP.TRANSIENT_ERROR: poll(send) failed: %m"))); } ssize_t wr = ::send(fd, data + off, len - off, 0); if (wr < 0) { if (errno == EINTR) continue; ereport(ERROR, (errcode(ERRCODE_IO_ERROR), errmsg("UTL_SMTP.TRANSIENT_ERROR: send failed: %m"))); } off += (size_t)wr; } } /// @brief Читает одну строку, завершающуюся CRLF, с таймаутом; строка без CRLF накапливается в rbuf. static bool recv_line(int fd, string& rbuf, string& out_line, int timeout_sec) { for (;;) { size_t pos = rbuf.find("\r\n"); if (pos != string::npos) { out_line.assign(rbuf.data(), pos); rbuf.erase(0, pos + 2); return true; } struct pollfd pfd{fd, POLLIN, 0}; int to = (timeout_sec < 0) ? -1 : timeout_sec * 1000; int pr = poll(&pfd, 1, to); if (pr <= 0) { if (pr == 0) return false; // таймаут ожидания данных if (errno == EINTR) continue; ereport(ERROR, (errcode(ERRCODE_IO_ERROR), errmsg("UTL_SMTP.TRANSIENT_ERROR: poll(recv) failed: %m"))); } char buf[4096]; ssize_t rd = ::recv(fd, buf, sizeof(buf), 0); if (rd < 0) { if (errno == EINTR) continue; ereport(ERROR, (errcode(ERRCODE_IO_ERROR), errmsg("UTL_SMTP.TRANSIENT_ERROR: recv failed: %m"))); } if (rd == 0) { ereport(ERROR, (errcode(ERRCODE_CONNECTION_FAILURE), errmsg("UTL_SMTP.TRANSIENT_ERROR: connection closed by peer"))); } rbuf.append(buf, (size_t)rd); } } /// @brief Возвращает код ответа SMTP из строки (первые 3 цифры) либо -1, если формат не соответствует. static int parse_smtp_code(const string& line) { if (line.size() < 3) return -1; if (!std::isdigit((unsigned char)line[0]) || !std::isdigit((unsigned char)line[1]) || !std::isdigit((unsigned char)line[2])) return -1; return (line[0]-'0')*100 + (line[1]-'0')*10 + (line[2]-'0'); } /// @brief Считывает весь многострочный ответ SMTP (xyz- промежуточные строки, xyz — последняя). static std::vector read_smtp_replies(int fd, string& rbuf, int timeout_sec) { std::vector lines; string line; if (!recv_line(fd, rbuf, line, timeout_sec)) { ereport(ERROR, (errcode(ERRCODE_QUERY_CANCELED), errmsg("UTL_SMTP.TRANSIENT_ERROR: timeout waiting for reply"))); } lines.push_back(line); int code = parse_smtp_code(line); if (code < 0) { ereport(ERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), errmsg("UTL_SMTP.PERMANENT_ERROR: invalid reply format: \"%s\"", line.c_str()))); } while (line.size() >= 4 && line[3] == '-') { // продолжение if (!recv_line(fd, rbuf, line, timeout_sec)) { ereport(ERROR, (errcode(ERRCODE_QUERY_CANCELED), errmsg("UTL_SMTP.TRANSIENT_ERROR: timeout waiting for multi-line reply"))); } lines.push_back(line); int c2 = parse_smtp_code(line); if (c2 != code) { ereport(ERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), errmsg("UTL_SMTP.PERMANENT_ERROR: mixed reply codes in multi-line response"))); } } return lines; } /// @brief Бросает исключение пакета при кодах 4xx/5xx; для 2xx/3xx — ничего не делает. static void raise_on_error_code(int code, const std::vector& lines) { if (code >= 400 && code <= 499) { string all; for (auto& s : lines) { all += s; all += "\n"; } ereport(ERROR, (errcode(ERRCODE_IO_ERROR), errmsg("UTL_SMTP.TRANSIENT_ERROR: %d %s", code, all.c_str()))); } else if (code >= 500) { string all; for (auto& s : lines) { all += s; all += "\n"; } ereport(ERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), errmsg("UTL_SMTP.PERMANENT_ERROR: %d %s", code, all.c_str()))); } } /// @brief Отправляет SMTP-команду cmd [arg] с CRLF и возвращает все строки ответа (с проверкой кодов). static std::vector smtp_command(int fd, string& rbuf, int timeout_sec, const string& cmd, const string& arg) { string wire = cmd; if (!arg.empty()) { wire.push_back(' '); wire += arg; } wire += "\r\n"; send_all(fd, wire.data(), wire.size(), timeout_sec); auto lines = read_smtp_replies(fd, rbuf, timeout_sec); int code = parse_smtp_code(lines.back()); raise_on_error_code(code, lines); return lines; } /// @brief Обрезает ведущие/замыкающие пробельные символы (ASCII ≤ ' '). static string trim(const string& s) { size_t i = 0, j = s.size(); while (i < j && (unsigned char)s[i] <= ' ') ++i; while (j > i && (unsigned char)s[j-1] <= ' ') --j; return s.substr(i, j - i); } /// @brief Нормализует тело письма: перевод строк → CRLF, dot-stuffing для строк, начинающихся с '.'. static string normalize_body_for_data(const string& body) { // Переводы строк → CRLF string tmp; tmp.reserve(body.size()*2); for (size_t i=0; i int { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); return -1; }; // Новый формат: \xDEADBEEF... if (n >= 2 && s[0] == '\\' && (s[1] == 'x' || s[1] == 'X')) { for (size_t i = 2; i + 1 < n; i += 2) { int hi = hexval(s[i]); int lo = hexval(s[i+1]); if (hi < 0 || lo < 0) break; // обрываемся на мусоре, но не падаем out.push_back(static_cast((hi << 4) | lo)); } return out; } // Старый escape-формат: обычные символы, \\ и \ooo (восьмеричное) for (size_t i = 0; i < n; ++i) { char c = s[i]; if (c != '\\') { out.push_back(c); continue; } // backslash if (i + 1 < n && s[i+1] == '\\') { out.push_back('\\'); ++i; continue; } if (i + 3 < n) { char c1 = s[i+1], c2 = s[i+2], c3 = s[i+3]; if ((c1 >= '0' && c1 <= '7') && (c2 >= '0' && c2 <= '7') && (c3 >= '0' && c3 <= '7')) { int val = ((c1 - '0') << 6) | ((c2 - '0') << 3) | (c3 - '0'); out.push_back(static_cast(val)); i += 3; continue; } } // Неформатная последовательность — примем следующий символ как есть (если он есть) if (i + 1 < n) { out.push_back(s[i+1]); ++i; } } return out; } /// @brief Простая Base64 (RFC 4648) для аутентификации AUTH PLAIN/LOGIN. static string b64_encode(const unsigned char* data, size_t len) { static const char* tbl = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; string out; out.reserve(((len + 2) / 3) * 4); size_t i = 0; while (i + 3 <= len) { unsigned v = (data[i] << 16) | (data[i+1] << 8) | data[i+2]; out.push_back(tbl[(v >> 18) & 0x3F]); out.push_back(tbl[(v >> 12) & 0x3F]); out.push_back(tbl[(v >> 6) & 0x3F]); out.push_back(tbl[v & 0x3F]); i += 3; } if (i + 1 == len) { unsigned v = (data[i] << 16); out.push_back(tbl[(v >> 18) & 0x3F]); out.push_back(tbl[(v >> 12) & 0x3F]); out.push_back('='); out.push_back('='); } else if (i + 2 == len) { unsigned v = (data[i] << 16) | (data[i+1] << 8); out.push_back(tbl[(v >> 18) & 0x3F]); out.push_back(tbl[(v >> 12) & 0x3F]); out.push_back(tbl[(v >> 6) & 0x3F]); out.push_back('='); } return out; } extern "C" { PG_FUNCTION_INFO_V1(utl_smtp_open_connection); // работает PG_FUNCTION_INFO_V1(utl_smtp_starttls); PG_FUNCTION_INFO_V1(utl_smtp_ehlo); // работает PG_FUNCTION_INFO_V1(utl_smtp_helo); // работает PG_FUNCTION_INFO_V1(utl_smtp_auth); PG_FUNCTION_INFO_V1(utl_smtp_mail); // работает PG_FUNCTION_INFO_V1(utl_smtp_rcpt); // работает PG_FUNCTION_INFO_V1(utl_smtp_open_data); // работает PG_FUNCTION_INFO_V1(utl_smtp_write_data); // работает PG_FUNCTION_INFO_V1(utl_smtp_write_raw_data); // без UTL_RAW не будет работать PG_FUNCTION_INFO_V1(utl_smtp_close_data); // работает PG_FUNCTION_INFO_V1(utl_smtp_data); // работает PG_FUNCTION_INFO_V1(utl_smtp_data_ext); PG_FUNCTION_INFO_V1(utl_smtp_command); PG_FUNCTION_INFO_V1(utl_smtp_command_replies); PG_FUNCTION_INFO_V1(utl_smtp_help); PG_FUNCTION_INFO_V1(utl_smtp_noop); // работает PG_FUNCTION_INFO_V1(utl_smtp_rset); // работает PG_FUNCTION_INFO_V1(utl_smtp_quit); // работает PG_FUNCTION_INFO_V1(utl_smtp_close_connection); PG_FUNCTION_INFO_V1(utl_smtp_vrfy); PG_FUNCTION_INFO_V1(utl_smtp_get_version); /// @brief Версия RUDB пакета UTL_SMTP (Oracle UTL_SMTP пакет) #define RUDB_UTL_SMTP_VERSION "1.0.0" } /* * @qdb_func: utl_smtp_open_connection(text, int4, int4, text, text, boolean, text) * @ora_func: UTL_SMTP.OPEN_CONNECTION(VARCHAR2, BINARY_INTEGER, C PL/SQL_RECORD, BINARY_INTEGER, VARCHAR2, VARCHAR2, BOOLEAN, VARCHAR2) * @ora_func: UTL_SMTP.OPEN_CONNECTION(VARCHAR2, BINARY_INTEGER, BINARY_INTEGER, VARCHAR2, VARCHAR2, BOOLEAN, VARCHAR2) */ Datum utl_smtp_open_connection(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP: host must not be NULL"))); text* host_t = PG_GETARG_TEXT_PP(0); int32 port = PG_ARGISNULL(1) ? 25 : PG_GETARG_INT32(1); bool has_timeout = !PG_ARGISNULL(2); int32 tx_timeout = has_timeout ? PG_GETARG_INT32(2) : -1; // -1 = ждать бесконечно string host = pgtext_to_string(host_t); dbms_network_acl_admin_check_connect(host.c_str(), port); // Resolve: AF_UNSPEC, STREAM struct addrinfo hints{}; memset(&hints, 0, sizeof(hints)); hints.ai_socktype = SOCK_STREAM; hints.ai_family = AF_UNSPEC; struct addrinfo* res = nullptr; int gai = getaddrinfo(host.c_str(), nullptr, &hints, &res); if (gai != 0) { ereport(ERROR, (errcode(ERRCODE_CONNECTION_FAILURE), errmsg("UTL_SMTP.TRANSIENT_ERROR: getaddrinfo(%s) failed: %s", host.c_str(), gai_strerror(gai)))); } int fd = -1; for (auto rp = res; rp; rp = rp->ai_next) { // проставим порт if (rp->ai_family == AF_INET) { ((struct sockaddr_in*)rp->ai_addr)->sin_port = htons((uint16)port); } else if (rp->ai_family == AF_INET6) { ((struct sockaddr_in6*)rp->ai_addr)->sin6_port = htons((uint16)port); } fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (fd < 0) continue; set_nonblock(fd, true); int cr = ::connect(fd, rp->ai_addr, rp->ai_addrlen); if (cr < 0) { if (errno != EINPROGRESS) { close_fd_safe(fd); fd = -1; continue; } struct pollfd pfd{fd, POLLOUT, 0}; int to = (tx_timeout < 0) ? -1 : tx_timeout * 1000; int pr = poll(&pfd, 1, to); if (pr <= 0) { close_fd_safe(fd); fd = -1; continue; } int err = 0; socklen_t elen = sizeof(err); if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &elen) < 0 || err != 0) { close_fd_safe(fd); fd = -1; continue; } } // успех break; } freeaddrinfo(res); if (fd < 0) { ereport(ERROR, (errcode(ERRCODE_CONNECTION_FAILURE), errmsg("UTL_SMTP.TRANSIENT_ERROR: connect to %s:%d failed", host.c_str(), port))); } // Приветствие 220... string rbuf; auto lines = read_smtp_replies(fd, rbuf, tx_timeout); int code = parse_smtp_code(lines.back()); raise_on_error_code(code, lines); int32 handle = smtp_register_conn(fd, tx_timeout); g_conns[handle]->rbuf = std::move(rbuf); PG_RETURN_INT32(handle); } /* * @qdb_func: utl_smtp_helo(int4, text) * @ora_func: UTL_SMTP.HELO(C PL/SQL_RECORD, VARCHAR2) */ Datum utl_smtp_helo(PG_FUNCTION_ARGS) { int32 handle = PG_GETARG_INT32(0); if (PG_ARGISNULL(1)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP: domain must not be NULL"))); string domain = pgtext_to_string(PG_GETARG_TEXT_PP(1)); UtlSmtpConn& c = smtp_require_conn(handle); (void)smtp_command(c.fd, c.rbuf, c.timeout_sec, "HELO", domain); PG_RETURN_VOID(); } /* * @qdb_func: utl_smtp_mail(int4, text, text) * @ora_func: UTL_SMTP.MAIL(C PL/SQL_RECORD, VARCHAR2, VARCHAR2) */ Datum utl_smtp_mail(PG_FUNCTION_ARGS) { int32 handle = PG_GETARG_INT32(0); if (PG_ARGISNULL(1)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP: sender must not be NULL"))); string sender = pgtext_to_string(PG_GETARG_TEXT_PP(1)); string params = PG_ARGISNULL(2) ? string() : pgtext_to_string(PG_GETARG_TEXT_PP(2)); UtlSmtpConn& c = smtp_require_conn(handle); string arg = string("FROM:<") + trim(sender) + ">"; if (!params.empty()) { arg += " "; arg += trim(params); } (void)smtp_command(c.fd, c.rbuf, c.timeout_sec, "MAIL", arg); PG_RETURN_VOID(); } /* * @qdb_func: utl_smtp_rcpt(int4, text, text) * @ora_func: UTL_SMTP.RCPT(C PL/SQL_RECORD, VARCHAR2, VARCHAR2) */ Datum utl_smtp_rcpt(PG_FUNCTION_ARGS) { int32 handle = PG_GETARG_INT32(0); if (PG_ARGISNULL(1)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP: recipient must not be NULL"))); string rcpt = pgtext_to_string(PG_GETARG_TEXT_PP(1)); string params = PG_ARGISNULL(2) ? string() : pgtext_to_string(PG_GETARG_TEXT_PP(2)); UtlSmtpConn& c = smtp_require_conn(handle); string arg = string("TO:<") + trim(rcpt) + ">"; if (!params.empty()) { arg += " "; arg += trim(params); } auto lines = smtp_command(c.fd, c.rbuf, c.timeout_sec, "RCPT", arg); PG_RETURN_VOID(); } /* * @qdb_func: utl_smtp_open_data(int4) * @ora_func: UTL_SMTP.OPEN_DATA(C PL/SQL_RECORD) */ Datum utl_smtp_open_data(PG_FUNCTION_ARGS) { int32 handle = PG_GETARG_INT32(0); UtlSmtpConn& c = smtp_require_conn(handle); if (c.in_data) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP.INVALID_OPERATION: already in DATA state"))); } // DATA → 354 auto lines = smtp_command(c.fd, c.rbuf, c.timeout_sec, "DATA", ""); int code = parse_smtp_code(lines.back()); if (code != 354) { raise_on_error_code(code, lines); ereport(ERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), errmsg("UTL_SMTP.PERMANENT_ERROR: expected 354 after DATA"))); } c.in_data = true; PG_RETURN_VOID(); } /* * @qdb_func: utl_smtp_write_data(int4, text) * @ora_func: UTL_SMTP.WRITE_DATA(C PL/SQL_RECORD, VARCHAR2) */ Datum utl_smtp_write_data(PG_FUNCTION_ARGS) { int32 handle = PG_GETARG_INT32(0); UtlSmtpConn& c = smtp_require_conn(handle); if (!c.in_data) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP.INVALID_OPERATION: WRITE_DATA without OPEN_DATA"))); } if (PG_ARGISNULL(1)) PG_RETURN_TEXT_P(string_to_pgtext("OK")); string data = pgtext_to_string(PG_GETARG_TEXT_PP(1)); string wire = normalize_body_for_data(data); if (!wire.empty()) send_all(c.fd, wire.data(), wire.size(), c.timeout_sec); PG_RETURN_VOID(); } /* * @qdb_func: utl_smtp_close_data(int4) * @ora_func: UTL_SMTP.CLOSE_DATA(C PL/SQL_RECORD) */ Datum utl_smtp_close_data(PG_FUNCTION_ARGS) { int32 handle = PG_GETARG_INT32(0); UtlSmtpConn& c = smtp_require_conn(handle); if (!c.in_data) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP.INVALID_OPERATION: CLOSE_DATA without OPEN_DATA"))); } static const char* term = "\r\n.\r\n"; send_all(c.fd, term, strlen(term), c.timeout_sec); c.in_data = false; auto lines = read_smtp_replies(c.fd, c.rbuf, c.timeout_sec); // должно быть 250 ... int code = parse_smtp_code(lines.back()); raise_on_error_code(code, lines); PG_RETURN_VOID(); } /* * @qdb_func: utl_smtp_quit(int4) * @ora_func: UTL_SMTP.QUIT(C PL/SQL_RECORD) */ Datum utl_smtp_quit(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_VOID(); int32 handle = PG_GETARG_INT32(0); auto it = g_conns.find(handle); if (it != g_conns.end() && it->second) { UtlSmtpConn& c = *it->second; try { (void)smtp_command(c.fd, c.rbuf, c.timeout_sec, "QUIT", ""); } catch (...) { // игнор — соединение всё равно закрываем } } smtp_close_and_erase(handle); PG_RETURN_VOID(); } /* * @qdb_func: utl_smtp_starttls(int4, text) * @ora_func: UTL_SMTP.STARTTLS(C PL/SQL_RECORD, VARCHAR2) */ Datum utl_smtp_starttls(PG_FUNCTION_ARGS) { int32 handle = PG_GETARG_INT32(0); string secure_host = PG_ARGISNULL(1) ? string() : pgtext_to_string(PG_GETARG_TEXT_PP(1)); UtlSmtpConn& c = smtp_require_conn(handle); // RFC: сначала EHLO должен показать STARTTLS, но мы НЕ проверяем — просто шлём команду: auto lines = smtp_command(c.fd, c.rbuf, c.timeout_sec, "STARTTLS", ""); int code = parse_smtp_code(lines.back()); if (code == 220) { // На этом этапе сервер ждёт TLS-рукопожатие; TODO: Сделать ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("UTL_SMTP.PERMANENT_ERROR: TLS handshake is not supported in this build"))); } // Если пришёл не 220, raise_on_error_code уже бросит исключение. PG_RETURN_TEXT_P(string_to_pgtext(lines.back())); } /* * @qdb_func: utl_smtp_ehlo(int4, text) * @ora_func: UTL_SMTP.EHLO(C PL/SQL_RECORD, VARCHAR2) */ Datum utl_smtp_ehlo(PG_FUNCTION_ARGS) { int32 handle = PG_GETARG_INT32(0); if (PG_ARGISNULL(1)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP: domain must not be NULL"))); string domain = pgtext_to_string(PG_GETARG_TEXT_PP(1)); UtlSmtpConn& c = smtp_require_conn(handle); (void)smtp_command(c.fd, c.rbuf, c.timeout_sec, "EHLO", domain); PG_RETURN_VOID(); } /* * @qdb_func: utl_smtp_auth(int4, text, text, text) * @ora_func: UTL_SMTP.AUTH(C PL/SQL_RECORD, VARCHAR2, VARCHAR2, VARCHAR2) */ Datum utl_smtp_auth(PG_FUNCTION_ARGS) { int32 handle = PG_GETARG_INT32(0); if (PG_ARGISNULL(1) || PG_ARGISNULL(2)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP: username and password must not be NULL"))); string username = pgtext_to_string(PG_GETARG_TEXT_PP(1)); string password = pgtext_to_string(PG_GETARG_TEXT_PP(2)); string schemes = PG_ARGISNULL(3) ? string("PLAIN LOGIN") : pgtext_to_string(PG_GETARG_TEXT_PP(3)); UtlSmtpConn& c = smtp_require_conn(handle); auto contains_ci = [](const string& haystack, const char* needle) { auto lower = [](char ch){ return (char)std::tolower((unsigned char)ch); }; string h; h.reserve(haystack.size()); for (char ch: haystack) h.push_back(lower(ch)); string n; for (const char* p=needle; *p; ++p) n.push_back(lower(*p)); return h.find(n) != string::npos; }; if (contains_ci(schemes, "PLAIN")) { // AUTH PLAIN base64(\0 username \0 password) string blob; blob.push_back('\0'); blob += username; blob.push_back('\0'); blob += password; string b64 = b64_encode((const unsigned char*)blob.data(), blob.size()); auto lines = smtp_command(c.fd, c.rbuf, c.timeout_sec, "AUTH", string("PLAIN ") + b64); PG_RETURN_TEXT_P(string_to_pgtext(lines.back())); } if (contains_ci(schemes, "LOGIN")) { // AUTH LOGIN (334 VXNlcm5hbWU6) → b64(username) → (334 UGFzc3dvcmQ6) → b64(password) → 235 ... auto lines1 = smtp_command(c.fd, c.rbuf, c.timeout_sec, "AUTH", "LOGIN"); int code1 = parse_smtp_code(lines1.back()); if (code1 != 334) raise_on_error_code(code1, lines1); string u64 = b64_encode((const unsigned char*)username.data(), username.size()); send_all(c.fd, (u64 + "\r\n").c_str(), u64.size()+2, c.timeout_sec); auto lines2 = read_smtp_replies(c.fd, c.rbuf, c.timeout_sec); int code2 = parse_smtp_code(lines2.back()); if (code2 != 334) raise_on_error_code(code2, lines2); string p64 = b64_encode((const unsigned char*)password.data(), password.size()); send_all(c.fd, (p64 + "\r\n").c_str(), p64.size()+2, c.timeout_sec); auto lines3 = read_smtp_replies(c.fd, c.rbuf, c.timeout_sec); int code3 = parse_smtp_code(lines3.back()); raise_on_error_code(code3, lines3); // должен быть 235 (2.7.0) PG_RETURN_TEXT_P(string_to_pgtext(lines3.back())); } if (contains_ci(schemes, "CRAM-MD5")) { // Можно реализовать позже через HMAC-MD5; TODO: Сделать, пока выдаём ошибочку. ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("UTL_SMTP.PERMANENT_ERROR: AUTH CRAM-MD5 is not supported in this build"))); } ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP.PERMANENT_ERROR: none of the requested auth schemes are supported"))); PG_RETURN_TEXT_P(string_to_pgtext("")); // недостижимо } /* * @qdb_func: utl_smtp_write_raw_data(int4, blob) * @ora_func: UTL_SMTP.WRITE_RAW_DATA(C PL/SQL_RECORD, RAW) */ Datum utl_smtp_write_raw_data(PG_FUNCTION_ARGS) { int32 handle = PG_GETARG_INT32(0); UtlSmtpConn& c = smtp_require_conn(handle); if (!c.in_data) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP.INVALID_OPERATION: WRITE_RAW_DATA without OPEN_DATA"))); } if (PG_ARGISNULL(1)) PG_RETURN_TEXT_P(string_to_pgtext("OK")); // Получаем текстовое представление bytea через встроенную out-функцию типа . Datum d = PG_GETARG_DATUM(1); Oid outfunc; bool isvarlena; // не используем, но нужен для getTypeOutputInfo getTypeOutputInfo(BYTEAOID, &outfunc, &isvarlena); char* cstr = OidOutputFunctionCall(outfunc, d); // palloc-строка // Декодируем "\x..." или escape-представление в сырые байты std::string raw = bytea_text_to_raw(cstr); pfree(cstr); // Dot-stuffing: на началах строк (после CRLF) удваиваем '.' std::string wire; wire.reserve(raw.size() + 16); bool at_line_start = true; unsigned char prev = 0; for (size_t i = 0; i < raw.size(); ++i) { unsigned char ch = static_cast(raw[i]); if (at_line_start && ch == '.') wire.push_back('.'); wire.push_back(static_cast(ch)); // начало строки считаем только после пары CRLF if (prev == '\r' && ch == '\n') at_line_start = true; else if (ch == '\r') at_line_start = false; // ждём '\n' else if (ch == '\n') at_line_start = false; // одиночный LF — не считаем else at_line_start = false; prev = ch; } if (!wire.empty()) send_all(c.fd, wire.data(), wire.size(), c.timeout_sec); PG_RETURN_VOID(); } /* * @qdb_func: utl_smtp_data(int4, text) * @ora_func: UTL_SMTP.DATA(C PL/SQL_RECORD, VARCHAR2) */ Datum utl_smtp_data(PG_FUNCTION_ARGS) { LOCAL_FCINFO(fcinfo2, 3); InitFunctionCallInfoData(*fcinfo2, fcinfo->flinfo, 3, PG_GET_COLLATION(), fcinfo->context, NULL); fcinfo2->args[0].value = fcinfo->args[0].value; fcinfo2->args[0].isnull = fcinfo->args[0].isnull; fcinfo2->args[1].value = fcinfo->args[1].value; fcinfo2->args[1].isnull = fcinfo->args[1].isnull; fcinfo2->args[2].value = Int32GetDatum(0); fcinfo2->args[2].isnull = false; return utl_smtp_data_ext(fcinfo2); } Datum utl_smtp_data_ext(PG_FUNCTION_ARGS) { int32 handle = PG_GETARG_INT32(0); int32 options = PG_ARGISNULL(2) ? 0 : PG_GETARG_INT32(2); const int32 minimum_options = -64; const int32 supported_option_mask = 0x03; bool compatibility_mode = (options & 0x01) != 0; bool canonicalize_body = (options & 0x02) != 0; if (options < minimum_options) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP.INVALID_OPERATION: invalid options"))); if (PG_ARGISNULL(1)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP: body must not be NULL"))); options &= supported_option_mask; string body = pgtext_to_string(PG_GETARG_TEXT_PP(1)); UtlSmtpConn& c = smtp_require_conn(handle); if (compatibility_mode && !body.empty()) body.reserve(body.size()); // DATA → 354 auto pre = smtp_command(c.fd, c.rbuf, c.timeout_sec, "DATA", ""); int code = parse_smtp_code(pre.back()); if (code != 354) { raise_on_error_code(code, pre); ereport(ERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), errmsg("UTL_SMTP.PERMANENT_ERROR: expected 354 after DATA"))); } string wire = normalize_body_for_data(body); if (canonicalize_body && !wire.empty()) wire.reserve(wire.size()); if (!wire.empty()) send_all(c.fd, wire.data(), wire.size(), c.timeout_sec); static const char* term = "\r\n.\r\n"; send_all(c.fd, term, strlen(term), c.timeout_sec); auto post = read_smtp_replies(c.fd, c.rbuf, c.timeout_sec); // 250 ... int code2 = parse_smtp_code(post.back()); raise_on_error_code(code2, post); (void) options; PG_RETURN_VOID(); } /* * @qdb_func: utl_smtp_command(int4, text, text) * @ora_func: UTL_SMTP.COMMAND(C PL/SQL_RECORD, VARCHAR2, VARCHAR2) */ Datum utl_smtp_command(PG_FUNCTION_ARGS) { int32 handle = PG_GETARG_INT32(0); if (PG_ARGISNULL(1)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP: cmd must not be NULL"))); string cmd = pgtext_to_string(PG_GETARG_TEXT_PP(1)); string arg = PG_ARGISNULL(2) ? string() : pgtext_to_string(PG_GETARG_TEXT_PP(2)); UtlSmtpConn& c = smtp_require_conn(handle); auto lines = smtp_command(c.fd, c.rbuf, c.timeout_sec, trim(cmd), trim(arg)); PG_RETURN_TEXT_P(string_to_pgtext(lines.back())); } /* * @qdb_func: utl_smtp_command_replies(int4, text, text) * @ora_func: UTL_SMTP.COMMAND_REPLIES(C PL/SQL_RECORD, VARCHAR2, VARCHAR2) */ Datum utl_smtp_command_replies(PG_FUNCTION_ARGS) { int32 handle = PG_GETARG_INT32(0); if (PG_ARGISNULL(1)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("UTL_SMTP: cmd must not be NULL"))); string cmd = pgtext_to_string(PG_GETARG_TEXT_PP(1)); string arg = PG_ARGISNULL(2) ? string() : pgtext_to_string(PG_GETARG_TEXT_PP(2)); UtlSmtpConn& c = smtp_require_conn(handle); auto lines = smtp_command(c.fd, c.rbuf, c.timeout_sec, trim(cmd), trim(arg)); // Склеим многострочный ответ в один text (по \n) string all; for (size_t i=0; i