title: zlib's uncompress() strangely returning Z_BUF_ERROR
body: <p>I'm writing Qt-based client application. It connects to remote server using <code>QTcpSocket</code>. Before sending any actual data it needs to send login info, which is zlib-compressed json.</p>
  
  <p>As far as I know from server sources, to make everything work I need to send X bytes of compressed data following 4 bytes with length of uncompressed data.</p>
  
  <p>Uncompressing on server-side looks like this:</p>
  
  <pre><code>/* look at first 32 bits of buffer, which contains uncompressed len */
  unc_len = le32toh(*((uint32_t *)buf));
  if (unc_len &gt; CLI_MAX_MSG)
      return NULL;
  
  /* alloc buffer for uncompressed data */
  obj_unc = malloc(unc_len + 1);
  if (!obj_unc)
      return NULL;
  
  /* decompress buffer (excluding first 32 bits) */
  comp_p = buf + 4;
  if (uncompress(obj_unc, &amp;dest_len, comp_p, buflen - 4) != Z_OK)
      goto out;
  if (dest_len != unc_len)
      goto out;
  memcpy(obj_unc + unc_len, &amp;zero, 1);    /* null terminate */
  </code></pre>
  
  <p>I'm compressing json using Qt built-in zlib (I've just downloaded headers and placed it in mingw's <code>include</code> folder):</p>
  
  <pre><code>char json[] = "{\"version\":1,\"user\":\"test\"}";
  char pass[] = "test";
  
  std::auto_ptr&lt;Bytef&gt; message(new Bytef[             // allocate memory for:
                               sizeof(ubbp_header)    //  + msg header
                               + sizeof(uLongf)       //  + uncompressed data size
                               + strlen(json)         //  + compressed data itself
                               + 64                   //  + reserve (if compressed size &gt; uncompressed size)
                               + SHA256_DIGEST_LENGTH]);//+ SHA256 digest
  
  uLongf unc_len = strlen(json);
  uLongf enc_len = strlen(json) + 64;
  
  // header goes first, so server will determine that we want to login
  Bytef* pHdr = message.get();
  
  // after that: uncompressed data length and data itself
  Bytef* pLen = pHdr + sizeof(ubbp_header);
  Bytef* pDat = pLen + sizeof(uLongf);
  
  // hash of compressed message updated with user pass
  Bytef* pSha;
  
  if (Z_OK != compress(pLen, &amp;enc_len, (Bytef*)json, unc_len))
  {
      qDebug("Compression failed.");
      return false;
  }
  </code></pre>
  
  <p>Complete function code here: <a href="http://pastebin.com/hMY2C4n5" rel="nofollow">http://pastebin.com/hMY2C4n5</a></p>
  
  <p>Even though server correctly recieves uncompressed length, <code>uncompress()</code> returning <code>Z_BUF_ERROR</code>.</p>
  
  <p>P.S.: I'm actually writing pushpool's client to figure out how it's binary protocol works. I've asked this question on official bitcoin forum, but no luck there. <a href="http://forum.bitcoin.org/index.php?topic=24257.0" rel="nofollow">http://forum.bitcoin.org/index.php?topic=24257.0</a></p>