/* Copyright (c) 2008-2010 TrueCrypt Developers Association. All rights reserved. Governed by the TrueCrypt License 3.0 the full text of which is contained in the file License.txt included in TrueCrypt binary and source code distribution packages. */ #include #include #include #include #include #include #include #include #include "CoreLinux.h" #include "Platform/SystemInfo.h" #include "Platform/TextReader.h" #include "Volume/EncryptionModeLRW.h" #include "Volume/EncryptionModeXTS.h" #include "Driver/Fuse/FuseService.h" #include "Core/Unix/CoreServiceProxy.h" namespace VeraCrypt { CoreLinux::CoreLinux () { } CoreLinux::~CoreLinux () { } DevicePath CoreLinux::AttachFileToLoopDevice (const FilePath &filePath, bool readOnly) const { list loopPaths; loopPaths.push_back ("/dev/loop"); loopPaths.push_back ("/dev/loop/"); loopPaths.push_back ("/dev/.static/dev/loop"); for (int devIndex = 0; devIndex < 256; devIndex++) { string loopDev; foreach (const string &loopPath, loopPaths) { loopDev = loopPath + StringConverter::ToSingle (devIndex); if (FilesystemPath (loopDev).IsBlockDevice()) break; } if (loopDev.empty()) continue; list args; list ::iterator readOnlyArg; if (readOnly) { args.push_back ("-r"); readOnlyArg = --args.end(); } args.push_back ("--"); args.push_back (loopDev); args.push_back (filePath); try { Process::Execute ("losetup", args); return loopDev; } catch (ExecutedProcessFailed&) { if (readOnly) { try { args.erase (readOnlyArg); Process::Execute ("losetup", args); return loopDev; } catch (ExecutedProcessFailed&) { } } } } throw LoopDeviceSetupFailed (SRC_POS, wstring (filePath)); } void CoreLinux::DetachLoopDevice (const DevicePath &devicePath) const { list args; args.push_back ("-d"); args.push_back (devicePath); for (int t = 0; true; t++) { try { Process::Execute ("losetup", args); break; } catch (ExecutedProcessFailed&) { if (t > 5) throw; Thread::Sleep (200); } } } void CoreLinux::DismountNativeVolume (shared_ptr mountedVolume) const { string devPath = mountedVolume->VirtualDevice; if (devPath.find ("/dev/mapper/veracrypt") != 0) throw NotApplicable (SRC_POS); size_t devCount = 0; while (FilesystemPath (devPath).IsBlockDevice()) { list dmsetupArgs; dmsetupArgs.push_back ("remove"); dmsetupArgs.push_back (StringConverter::Split (devPath, "/").back()); for (int t = 0; true; t++) { try { Process::Execute ("dmsetup", dmsetupArgs); break; } catch (...) { if (t > 20) throw; Thread::Sleep (100); } } for (int t = 0; FilesystemPath (devPath).IsBlockDevice() && t < 20; t++) { Thread::Sleep (100); } devPath = string (mountedVolume->VirtualDevice) + "_" + StringConverter::ToSingle (devCount++); } } HostDeviceList CoreLinux::GetHostDevices (bool pathListOnly) const { HostDeviceList devices; TextReader tr ("/proc/partitions"); string line; while (tr.ReadLine (line)) { vector fields = StringConverter::Split (line); if (fields.size() != 4 || fields[3].find ("loop") == 0 // skip loop devices || fields[3].find ("cloop") == 0 || fields[3].find ("ram") == 0 // skip RAM devices || fields[3].find ("dm-") == 0 // skip device mapper devices || fields[2] == "1" // skip extended partitions ) continue; try { StringConverter::ToUInt32 (fields[0]); } catch (...) { continue; } try { make_shared_auto (HostDevice, hostDevice); hostDevice->Path = string (fields[3].find ("/dev/") == string::npos ? "/dev/" : "") + fields[3]; if (!pathListOnly) { hostDevice->Size = StringConverter::ToUInt64 (fields[2]) * 1024; hostDevice->MountPoint = GetDeviceMountPoint (hostDevice->Path); hostDevice->SystemNumber = 0; } try { StringConverter::GetTrailingNumber (fields[3]); if (devices.size() > 0) { HostDevice &prevDev = **--devices.end(); if (string (hostDevice->Path).find (prevDev.Path) == 0) { prevDev.Partitions.push_back (hostDevice); continue; } } } catch (...) { } devices.push_back (hostDevice); continue; } catch (...) { continue; } } return devices; } MountedFilesystemList CoreLinux::GetMountedFilesystems (const DevicePath &devicePath, const DirectoryPath &mountPoint) const { MountedFilesystemList mountedFilesystems; DevicePath realDevicePath = devicePath; if (!devicePath.IsEmpty()) { char *resolvedPath = realpath (string (devicePath).c_str(), NULL); if (resolvedPath) { realDevicePath = resolvedPath; free (resolvedPath); } } FILE *mtab = fopen ("/etc/mtab", "r"); if (!mtab) mtab = fopen ("/proc/mounts", "r"); throw_sys_sub_if (!mtab, "/proc/mounts"); finally_do_arg (FILE *, mtab, { fclose (finally_arg); }); static Mutex mutex; ScopeLock sl (mutex); struct mntent *entry; while ((entry = getmntent (mtab)) != nullptr) { make_shared_auto (MountedFilesystem, mf); if (entry->mnt_fsname) mf->Device = DevicePath (entry->mnt_fsname); else continue; if (entry->mnt_dir) mf->MountPoint = DirectoryPath (entry->mnt_dir); if (entry->mnt_type) mf->Type = entry->mnt_type; if ((devicePath.IsEmpty() || devicePath == mf->Device || realDevicePath == mf->Device) && (mountPoint.IsEmpty() || mountPoint == mf->MountPoint)) mountedFilesystems.push_back (mf); } return mountedFilesystems; } void CoreLinux::MountFilesystem (const DevicePath &devicePath, const DirectoryPath &mountPoint, const string &filesystemType, bool readOnly, const string &systemMountOptions) const { bool fsMounted = false; try { if (!FilesystemSupportsUnixPermissions (devicePath)) { stringstream userMountOptions; userMountOptions << "uid=" << GetRealUserId() << ",gid=" << GetRealGroupId() << ",umask=077" << (!systemMountOptions.empty() ? "," : ""); CoreUnix::MountFilesystem (devicePath, mountPoint, filesystemType, readOnly, userMountOptions.str() + systemMountOptions); fsMounted = true; } } catch (...) { } if (!fsMounted) CoreUnix::MountFilesystem (devicePath, mountPoint, filesystemType, readOnly, systemMountOptions); } void CoreLinux::MountVolumeNative (shared_ptr volume, MountOptions &options, const DirectoryPath &auxMountPoint) const { bool xts = (typeid (*volume->GetEncryptionMode()) == typeid (EncryptionModeXTS)); bool lrw = (typeid (*volume->GetEncryptionMode()) == typeid (EncryptionModeLRW)); if (options.NoKernelCrypto || (!xts && (!lrw || volume->GetEncryptionAlgorithm()->GetCiphers().size() > 1 || volume->GetEncryptionAlgorithm()->GetMinBlockSize() != 16)) || volume->GetProtectionType() == VolumeProtection::HiddenVolumeReadOnly) { throw NotApplicable (SRC_POS); } if (!SystemInfo::IsVersionAtLeast (2, 6, xts ? 24 : 20)) throw NotApplicable (SRC_POS); // Load device mapper kernel module list execArgs; foreach (const string &dmModule, StringConverter::Split ("dm_mod dm-mod dm")) { execArgs.clear(); execArgs.push_back (dmModule); try { Process::Execute ("modprobe", execArgs); break; } catch (...) { } } bool loopDevAttached = false; bool nativeDevCreated = false; bool filesystemMounted = false; // Attach volume to loopback device if required VolumePath volumePath = volume->GetPath(); if (!volumePath.IsDevice()) { volumePath = AttachFileToLoopDevice (volumePath, options.Protection == VolumeProtection::ReadOnly); loopDevAttached = true; } string nativeDevPath; try { // Create virtual device using device mapper size_t nativeDevCount = 0; size_t secondaryKeyOffset = volume->GetEncryptionMode()->GetKey().Size(); size_t cipherCount = volume->GetEncryptionAlgorithm()->GetCiphers().size(); foreach_reverse_ref (const Cipher &cipher, volume->GetEncryptionAlgorithm()->GetCiphers()) { stringstream dmCreateArgs; dmCreateArgs << "0 " << volume->GetSize() / ENCRYPTION_DATA_UNIT_SIZE << " crypt "; // Mode dmCreateArgs << StringConverter::ToLower (StringConverter::ToSingle (cipher.GetName())) << (xts ? (SystemInfo::IsVersionAtLeast (2, 6, 33) ? "-xts-plain64 " : "-xts-plain ") : "-lrw-benbi "); size_t keyArgOffset = dmCreateArgs.str().size(); dmCreateArgs << setw (cipher.GetKeySize() * (xts ? 4 : 2) + (xts ? 0 : 16 * 2)) << 0 << setw (0); // Sector and data unit offset uint64 startSector = volume->GetLayout()->GetDataOffset (volume->GetHostSize()) / ENCRYPTION_DATA_UNIT_SIZE; dmCreateArgs << ' ' << (xts ? startSector + volume->GetEncryptionMode()->GetSectorOffset() : 0) << ' '; if (nativeDevCount == 0) dmCreateArgs << string (volumePath) << ' ' << startSector; else dmCreateArgs << nativeDevPath << " 0"; SecureBuffer dmCreateArgsBuf (dmCreateArgs.str().size()); dmCreateArgsBuf.CopyFrom (ConstBufferPtr ((byte *) dmCreateArgs.str().c_str(), dmCreateArgs.str().size())); // Keys const SecureBuffer &cipherKey = cipher.GetKey(); secondaryKeyOffset -= cipherKey.Size(); ConstBufferPtr secondaryKey = volume->GetEncryptionMode()->GetKey().GetRange (xts ? secondaryKeyOffset : 0, xts ? cipherKey.Size() : 16); SecureBuffer hexStr (3); for (size_t i = 0; i < cipherKey.Size(); ++i) { sprintf ((char *) hexStr.Ptr(), "%02x", (int) cipherKey[i]); dmCreateArgsBuf.GetRange (keyArgOffset + i * 2, 2).CopyFrom (hexStr.GetRange (0, 2)); if (lrw && i >= 16) continue; sprintf ((char *) hexStr.Ptr(), "%02x", (int) secondaryKey[i]); dmCreateArgsBuf.GetRange (keyArgOffset + cipherKey.Size() * 2 + i * 2, 2).CopyFrom (hexStr.GetRange (0, 2)); } stringstream nativeDevName; nativeDevName << "veracrypt" << options.SlotNumber; if (nativeDevCount != cipherCount - 1) nativeDevName << "_" << cipherCount - nativeDevCount - 2; nativeDevPath = "/dev/mapper/" + nativeDevName.str(); execArgs.clear(); execArgs.push_back ("create"); execArgs.push_back (nativeDevName.str()); Process::Execute ("dmsetup", execArgs, -1, nullptr, &dmCreateArgsBuf); // Wait for the device to be created for (int t = 0; true; t++) { try { FilesystemPath (nativeDevPath).GetType(); break; } catch (...) { if (t > 20) throw; Thread::Sleep (100); } } nativeDevCreated = true; ++nativeDevCount; } // Test whether the device mapper is able to read and decrypt the last sector SecureBuffer lastSectorBuf (volume->GetSectorSize()); uint64 lastSectorOffset = volume->GetSize() - volume->GetSectorSize(); File nativeDev; nativeDev.Open (nativeDevPath); nativeDev.ReadAt (lastSectorBuf, lastSectorOffset); SecureBuffer lastSectorBuf2 (volume->GetSectorSize()); volume->ReadSectors (lastSectorBuf2, lastSectorOffset); if (memcmp (lastSectorBuf.Ptr(), lastSectorBuf2.Ptr(), volume->GetSectorSize()) != 0) throw KernelCryptoServiceTestFailed (SRC_POS); // Mount filesystem if (!options.NoFilesystem && options.MountPoint && !options.MountPoint->IsEmpty()) { MountFilesystem (nativeDevPath, *options.MountPoint, StringConverter::ToSingle (options.FilesystemType), options.Protection == VolumeProtection::ReadOnly, StringConverter::ToSingle (options.FilesystemOptions)); filesystemMounted = true; } FuseService::SendAuxDeviceInfo (auxMountPoint, nativeDevPath, volumePath); } catch (...) { try { if (filesystemMounted) DismountFilesystem (*options.MountPoint, true); } catch (...) { } try { if (nativeDevCreated) { make_shared_auto (VolumeInfo, vol); vol->VirtualDevice = nativeDevPath; DismountNativeVolume (vol); } } catch (...) { } try { if (loopDevAttached) DetachLoopDevice (volumePath); } catch (...) { } throw; } } auto_ptr Core (new CoreServiceProxy ); auto_ptr CoreDirect (new CoreLinux); } id='n273' href='#n273'>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
/*
  puff.c
  Copyright (C) 2002-2004 Mark Adler, all rights reserved
  version 1.8, 9 Jan 2004

  This software is provided 'as-is', without any express or implied
  warranty.  In no event will the author be held liable for any damages
  arising from the use of this software.

  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgment in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.

  Mark Adler    madler@alumni.caltech.edu
*/

/* Adapted for TrueCrypt */
/* Adapted for VeraCrypt */


#define local static            /* for local function definitions */
#define NIL ((unsigned char *)0)        /* for no output option */

/*
 * Maximums for allocations and loops.  It is not useful to change these --
 * they are fixed by the deflate format.
 */
#define MAXBITS 15              /* maximum bits in a code */
#define MAXLCODES 286           /* maximum number of literal/length codes */
#define MAXDCODES 30            /* maximum number of distance codes */
#define MAXCODES (MAXLCODES+MAXDCODES)  /* maximum codes lengths to read */
#define FIXLCODES 288           /* number of fixed literal/length codes */

/* input and output state */
struct state {
    /* output state */
    unsigned char *out;         /* output buffer */
    unsigned int outlen;       /* available space at out */
    unsigned int outcnt;       /* bytes written to out so far */

    /* input state */
    unsigned char *in;          /* input buffer */
    unsigned int inlen;			 /* available input at in */
    unsigned int incnt;        /* bytes read so far */
    int bitbuf;                 /* bit buffer */
    int bitcnt;                 /* number of bits in bit buffer */
};


local int bits(struct state *s, int need)
{
    long val;           /* bit accumulator (can use up to 20 bits) */

    /* load at least need bits into val */
    val = s->bitbuf;
    while (s->bitcnt < need) {
        val |= (long)(s->in[s->incnt++]) << s->bitcnt;  /* load eight bits */
        s->bitcnt += 8;
    }

    /* drop need bits and update buffer, always zero to seven bits left */
    s->bitbuf = (int)(val >> need);
    s->bitcnt -= need;

    /* return need bits, zeroing the bits above that */
    return (int)(val & ((1L << need) - 1));
}


local int stored(struct state *s)
{
    unsigned len;       /* length of stored block */

    /* discard leftover bits from current byte (assumes s->bitcnt < 8) */
    s->bitbuf = 0;
    s->bitcnt = 0;

    if (s->incnt + 4 > s->inlen)
        return 2;                               /* not enough input */

    /* get length and check against its one's complement */
    len = s->in[s->incnt++];
    len |= s->in[s->incnt++] << 8;
    if (s->in[s->incnt++] != (~len & 0xff) ||
        s->in[s->incnt++] != ((~len >> 8) & 0xff))
        return -2;                              /* didn't match complement! */

    if (s->incnt + len > s->inlen)
        return 2;                               /* not enough input */

    /* copy len bytes from in to out */
    if (s->out != NIL) {
        if (s->outcnt + len > s->outlen)
            return 1;                           /* not enough output space */
        while (len--)
            s->out[s->outcnt++] = s->in[s->incnt++];
    }
    else {                                      /* just scanning */
        s->outcnt += len;
        s->incnt += len;
    }

    /* done with a valid stored block */
    return 0;
}


struct huffman {
    short *count;       /* number of symbols of each length */
    short *symbol;      /* canonically ordered symbols */
};

/* reduce code size by using slow version of the decompressor */
#define SLOW

#ifdef SLOW
local int decode(struct state *s, struct huffman *h)
{
    int len;            /* current number of bits in code */
    int code;           /* len bits being decoded */
    int first;          /* first code of length len */
    int count;          /* number of codes of length len */
    int index;          /* index of first code of length len in symbol table */

    code = first = index = 0;
    for (len = 1; len <= MAXBITS; len++) {
        code |= bits(s, 1);             /* get next bit */
        count = h->count[len];
        if (code < first + count)       /* if length len, return symbol */
            return h->symbol[index + (code - first)];
        index += count;                 /* else update for next length */
        first += count;
        first <<= 1;
        code <<= 1;
    }
    return -9;                          /* ran out of codes */
}

/*
 * A faster version of decode() for real applications of this code.   It's not
 * as readable, but it makes puff() twice as fast.  And it only makes the code
 * a few percent larger.
 */
#else /* !SLOW */
local int decode(struct state *s, struct huffman *h)
{
    int len;            /* current number of bits in code */
    int code;           /* len bits being decoded */
    int first;          /* first code of length len */
    int count;          /* number of codes of length len */
    int index;          /* index of first code of length len in symbol table */
    int bitbuf;         /* bits from stream */
    int left;           /* bits left in next or left to process */
    short *next;        /* next number of codes */

    bitbuf = s->bitbuf;
    left = s->bitcnt;
    code = first = index = 0;
    len = 1;
    next = h->count + 1;
    while (1) {
        while (left--) {
            code |= bitbuf & 1;
            bitbuf >>= 1;
            count = *next++;
            if (code < first + count) { /* if length len, return symbol */
                s->bitbuf = bitbuf;
                s->bitcnt = (s->bitcnt - len) & 7;
                return h->symbol[index + (code - first)];
            }
            index += count;             /* else update for next length */
            first += count;
            first <<= 1;
            code <<= 1;
            len++;
        }
        left = (MAXBITS+1) - len;
        if (left == 0) break;
        bitbuf = s->in[s->incnt++];
        if (left > 8) left = 8;
    }
    return -9;                          /* ran out of codes */
}
#endif /* SLOW */


local int construct(struct huffman *h, short *length, int n)
{
    int symbol;         /* current symbol when stepping through length[] */
    int len;            /* current length when stepping through h->count[] */
    int left;           /* number of possible codes left of current length */
    short offs[MAXBITS+1];      /* offsets in symbol table for each length */

    /* count number of codes of each length */
    for (len = 0; len <= MAXBITS; len++)
        h->count[len] = 0;
    for (symbol = 0; symbol < n; symbol++)
        (h->count[length[symbol]])++;   /* assumes lengths are within bounds */
    if (h->count[0] == n)               /* no codes! */
        return 0;                       /* complete, but decode() will fail */

    /* check for an over-subscribed or incomplete set of lengths */
    left = 1;                           /* one possible code of zero length */
    for (len = 1; len <= MAXBITS; len++) {
        left <<= 1;                     /* one more bit, double codes left */
        left -= h->count[len];          /* deduct count from possible codes */
        if (left < 0) return left;      /* over-subscribed--return negative */
    }                                   /* left > 0 means incomplete */

    /* generate offsets into symbol table for each length for sorting */
    offs[1] = 0;
    for (len = 1; len < MAXBITS; len++)
        offs[len + 1] = offs[len] + h->count[len];

    /*
     * put symbols in table sorted by length, by symbol order within each
     * length
     */
    for (symbol = 0; symbol < n; symbol++)
        if (length[symbol] != 0)
            h->symbol[offs[length[symbol]]++] = symbol;

    /* return zero for complete set, positive for incomplete set */
    return left;
}


local int codes(struct state *s,
                struct huffman *lencode,
                struct huffman *distcode)
{
    int symbol;         /* decoded symbol */
    int len;            /* length for copy */
    unsigned dist;      /* distance for copy */
    static const short lens[29] = { /* Size base for length codes 257..285 */
        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
    static const short lext[29] = { /* Extra bits for length codes 257..285 */
        0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
        3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
    static const short dists[30] = { /* Offset base for distance codes 0..29 */
        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
        8193, 12289, 16385, 24577};
    static const short dext[30] = { /* Extra bits for distance codes 0..29 */
        0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
        7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
        12, 12, 13, 13};

    /* decode literals and length/distance pairs */
    do {
        symbol = decode(s, lencode);
        if (symbol < 0) return symbol;  /* invalid symbol */
        if (symbol < 256) {             /* literal: symbol is the byte */
            /* write out the literal */
            if (s->out != NIL) {
                if (s->outcnt == s->outlen) return 1;
                s->out[s->outcnt] = symbol;
            }
            s->outcnt++;
        }
        else if (symbol > 256) {        /* length */
            /* get and compute length */
            symbol -= 257;
            if (symbol >= 29) return -9;        /* invalid fixed code */
            len = lens[symbol] + bits(s, lext[symbol]);

            /* get and check distance */
            symbol = decode(s, distcode);
            if (symbol < 0) return symbol;          /* invalid symbol */
            dist = dists[symbol] + bits(s, dext[symbol]);
            if (dist > s->outcnt)
                return -10;     /* distance too far back */

            /* copy length bytes from distance bytes back */
            if (s->out != NIL) {
                if (s->outcnt + len > s->outlen) return 1;
                while (len--) {
                    s->out[s->outcnt] = s->out[s->outcnt - dist];
                    s->outcnt++;
                }
            }
            else
                s->outcnt += len;
        }
    } while (symbol != 256);            /* end of block symbol */

    /* done with a valid fixed or dynamic block */
    return 0;
}


local int fixed(struct state *s)
{
    static int virgin = 1;
    static short lencnt[MAXBITS+1], lensym[FIXLCODES];
    static short distcnt[MAXBITS+1], distsym[MAXDCODES];
    static struct huffman lencode = {lencnt, lensym};
    static struct huffman distcode = {distcnt, distsym};

    /* build fixed huffman tables if first call (may not be thread safe) */
    if (virgin) {
        int symbol;
        short lengths[FIXLCODES];

        /* literal/length table */
        for (symbol = 0; symbol < 144; symbol++)
            lengths[symbol] = 8;
        for (; symbol < 256; symbol++)
            lengths[symbol] = 9;
        for (; symbol < 280; symbol++)
            lengths[symbol] = 7;
        for (; symbol < FIXLCODES; symbol++)
            lengths[symbol] = 8;
        construct(&lencode, lengths, FIXLCODES);

        /* distance table */
        for (symbol = 0; symbol < MAXDCODES; symbol++)
            lengths[symbol] = 5;
        construct(&distcode, lengths, MAXDCODES);

        /* do this just once */
        virgin = 0;
    }

    /* decode data until end-of-block code */
    return codes(s, &lencode, &distcode);
}


local int dynamic(struct state *s)
{
    int nlen, ndist, ncode;             /* number of lengths in descriptor */
    int index;                          /* index of lengths[] */
    int err;                            /* construct() return value */
    short lengths[MAXCODES];            /* descriptor code lengths */
    short lencnt[MAXBITS+1], lensym[MAXLCODES];         /* lencode memory */
    short distcnt[MAXBITS+1], distsym[MAXDCODES];       /* distcode memory */
    struct huffman lencode = {lencnt, lensym};          /* length code */
    struct huffman distcode = {distcnt, distsym};       /* distance code */
    static const short order[19] =      /* permutation of code length codes */
        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};

    /* get number of lengths in each table, check lengths */
    nlen = bits(s, 5) + 257;
    ndist = bits(s, 5) + 1;
    ncode = bits(s, 4) + 4;
    if (nlen > MAXLCODES || ndist > MAXDCODES)
        return -3;                      /* bad counts */

    /* read code length code lengths (really), missing lengths are zero */
    for (index = 0; index < ncode; index++)
        lengths[order[index]] = bits(s, 3);
    for (; index < 19; index++)
        lengths[order[index]] = 0;

    /* build huffman table for code lengths codes (use lencode temporarily) */
    err = construct(&lencode, lengths, 19);
    if (err != 0) return -4;            /* require complete code set here */

    /* read length/literal and distance code length tables */
    index = 0;
    while (index < nlen + ndist) {
        int symbol;             /* decoded value */
        int len;                /* last length to repeat */

        symbol = decode(s, &lencode);
        if (symbol < 0)
            return symbol;          /* invalid symbol */
        if (symbol < 16)                /* length in 0..15 */
            lengths[index++] = symbol;
        else {                          /* repeat instruction */
            len = 0;                    /* assume repeating zeros */
            switch(symbol)
            {
               case 16: {         /* repeat last length 3..6 times */
                  if (index == 0) return -5;      /* no last length! */
                  len = lengths[index - 1];       /* last length */
                  symbol = 3 + bits(s, 2);
                  break;
               }
               case  17:      /* repeat zero 3..10 times */
                  symbol = 3 + bits(s, 3);
                  break;
               default:                  /* == 18, repeat zero 11..138 times */
                   symbol = 11 + bits(s, 7);
                   break;
             }
            if ((index + symbol > nlen + ndist))
                return -6;              /* too many lengths! */
            while (symbol--)            /* repeat last or zero symbol times */
                lengths[index++] = len;
        }
    }

    /* check for end-of-block code -- there better be one! */
    if (lengths[256] == 0)
        return -9;

    /* build huffman table for literal/length codes */
    err = construct(&lencode, lengths, nlen);
    if (err < 0 || (err > 0 && nlen - lencode.count[0] != 1))
        return -7;      /* only allow incomplete codes if just one code */

    /* build huffman table for distance codes */
    err = construct(&distcode, lengths + nlen, ndist);
    if (err < 0 || (err > 0 && ndist - distcode.count[0] != 1))
        return -8;      /* only allow incomplete codes if just one code */

    /* decode data until end-of-block code */
    return codes(s, &lencode, &distcode);
}


void _acrtused () { }

// Decompress deflated data
int far main (
         unsigned char *dest,         /* pointer to destination pointer */
         unsigned int destlen,        /* amount of output space */
         unsigned char *source,       /* pointer to source data pointer */
         unsigned int sourcelen)
{
    struct state s;             /* input/output state */
    int last, type;             /* block information */
    int err;                    /* return value */

    /* initialize output state */
    s.out = dest;
    s.outlen = destlen;                /* ignored if dest is NIL */
    s.outcnt = 0;

    /* initialize input state */
    s.in = source;
    s.inlen = sourcelen;
    s.incnt = 0;
    s.bitbuf = 0;
    s.bitcnt = 0;

	/* process blocks until last block or error */
	do {
		last = bits(&s, 1);         /* one if last block */
		type = bits(&s, 2);         /* block type 0..3 */
		switch(type)
		{
		case 0:
			err = stored(&s);
			break;
		case 1:
			err = fixed(&s);
			break;
		case 2:
			err = dynamic(&s);
			break;
		default:
			err = -1; /* type == 3, invalid */
			break;
		}

		if (err != 0) break;        /* return with error */
	} while (!last);

	return err;
}