/* CFS adapter for the PostgreSQL built-in PGLZ codec. */ #include "postgres.h" #include #include "common/pg_lzcompress.h" #include "storage/cfs/cfs_codec.h" bool cfs_codec_pglz_available(void) { return true; } Size cfs_codec_pglz_bound(Size srclen) { if (srclen > (Size) BLCKSZ) return 0; return (Size) PGLZ_MAX_OUTPUT((int32) srclen); } CfsCodecResult cfs_codec_pglz_compress(const char *src, Size srclen, char *dst, Size dstlen, int level, Size *result_len) { Size bound; int32 len; /* PGLZ has strategies, not numeric levels. Use PostgreSQL default. */ (void) level; if (src == NULL || dst == NULL || result_len == NULL || srclen > (Size) BLCKSZ) return CFS_CODEC_ERROR; if (srclen == 0) return CFS_CODEC_OVERFLOW; bound = cfs_codec_pglz_bound(srclen); if (bound == 0) return CFS_CODEC_ERROR; /* * pglz_compress() does not accept dst capacity. Its documented minimum * buffer size is PGLZ_MAX_OUTPUT(srclen). Never call it with less space. */ if (dstlen < bound) return CFS_CODEC_OVERFLOW; len = pglz_compress(src, (int32) srclen, dst, PGLZ_strategy_default); if (len < 0 || (Size) len >= srclen) return CFS_CODEC_OVERFLOW; *result_len = (Size) len; return CFS_CODEC_OK; } /* * Strict PGLZ stream-size validation for full CFS pages. * * PostgreSQL's pglz_decompress(check_complete=true) can accept a smaller * destination when the final match tag is clipped to destend. CFS requires * an exact decoded page size. Inspect tags BEFORE calling the upstream * routine so malformed input never reaches a truncating success path. */ static bool cfs_pglz_valid_size(const unsigned char *src, Size srclen, Size dstlen) { Size ipos = 0; Size opos = 0; while (ipos < srclen) { unsigned char ctrl = src[ipos++]; int i; for (i = 0; i < 8 && ipos < srclen; i++, ctrl >>= 1) { if (ctrl & 1) { Size run; Size offset; if (srclen - ipos < 2) return false; run = (Size) (src[ipos] & 0x0f) + 3; offset = (Size) ((src[ipos] & 0xf0) << 4) | src[ipos + 1]; ipos += 2; if (run == 18) { if (ipos == srclen) return false; run += src[ipos++]; } if (offset == 0 || offset > opos || run > dstlen - opos) return false; opos += run; } else { if (opos == dstlen) return false; ipos++; opos++; } } } return opos == dstlen; } CfsCodecResult cfs_codec_pglz_decompress(const char *src, Size srclen, char *dst, Size dstlen) { int32 len; if (src == NULL || dst == NULL || srclen == 0 || dstlen == 0 || srclen > (Size) BLCKSZ || dstlen > (Size) BLCKSZ) return CFS_CODEC_ERROR; if (!cfs_pglz_valid_size((const unsigned char *) src, srclen, dstlen)) return CFS_CODEC_ERROR; /* This is always a whole-page decode, never a TOAST slice. */ len = pglz_decompress(src, (int32) srclen, dst, (int32) dstlen, true); return len == (int32) dstlen ? CFS_CODEC_OK : CFS_CODEC_ERROR; }