summaryrefslogtreecommitdiff
path: root/indra/llmessage/llzerocode.h
blob: 7246c9d9466f19d7f0323aa4bfe881eda73e278e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/**
 * @file llzerocode.h
 * @brief Zero-code run-length compression used by the LLMessageSystem UDP protocol.
 *
 * $LicenseInfo:firstyear=2001&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#ifndef LL_LLZEROCODE_H
#define LL_LLZEROCODE_H

#include <cstring>

#include "stdtypes.h"

// Zero-coding compresses runs of zero bytes in a packet body, leaving the
// first header_size bytes of the buffer (the packet header - flags,
// sequence number, offset, etc.) untouched aside from the flag bit below.
//
//   Runs of zero bytes in the body are replaced by a two-byte token:
//     0x00 N        - represents N zero bytes, for N in 1..254
//     0x00 0x00 N   - represents (255 + N) zero bytes (wrap/overflow case,
//                     produced by decode()'s wire format but never emitted
//                     by encode(), which instead starts a fresh 0x00 token
//                     every 255 zero bytes)
namespace LLZeroCode
{
    // High bit of the first header byte: set by encode() and cleared by
    // decode() to indicate whether the body that follows is zero-coded.
    const U8 FLAG = 0x80;

    // Zero-codes src (src_size bytes, the first header_size of which are the
    // packet header and are copied verbatim) into dst.
    //
    // dst_capacity must be at least 2 * src_size: a pathological body of
    // isolated zero bytes can nearly double in size when encoded.
    //
    // Returns the encoded size (with FLAG set in dst[0]) if doing so made the
    // packet smaller. Returns -1 if compression would not help (or the
    // arguments are invalid), in which case dst is left untouched and the
    // caller should keep using the original, uncompressed buffer.
    inline S32 encode(const U8* src, U32 src_size, U8* dst, U32 dst_capacity, U32 header_size)
    {
        if (src_size < header_size || dst_capacity < 2 * src_size)
        {
            return -1;
        }

        S32 count = (S32)(src_size - header_size);
        S32 net_gain = 0;
        U8 num_zeroes = 0;

        const U8* inptr = src;
        U8* outptr = dst;

        // copy the header verbatim
        for (U32 ii = 0; ii < header_size; ++ii)
        {
            *outptr++ = *inptr++;
        }

        // sequential zero bytes are encoded as 0 [U8 count]; a run longer
        // than 254 bytes is split into consecutive 0 [U8 count] tokens.
        while (count--)
        {
            if (!(*inptr))   // in a zero count
            {
                if (num_zeroes)
                {
                    if (++num_zeroes > 254)
                    {
                        *outptr++ = num_zeroes;
                        num_zeroes = 0;
                    }
                    net_gain--;   // subsequent zeroes save one
                }
                else
                {
                    *outptr++ = 0;
                    net_gain++;  // starting a zero count adds one
                    num_zeroes = 1;
                }
                inptr++;
            }
            else
            {
                if (num_zeroes)
                {
                    *outptr++ = num_zeroes;
                    num_zeroes = 0;
                }
                *outptr++ = *inptr++;
            }
        }

        if (num_zeroes)
        {
            *outptr++ = num_zeroes;
        }

        if (net_gain >= 0)
        {
            // compression did not shrink the packet; caller should keep the original
            return -1;
        }

        dst[0] |= FLAG;
        return (S32)src_size + net_gain;
    }

    // Expands a zero-coded src (src_size bytes) into dst.
    //
    // If FLAG is not set in src[0], the body is not zero-coded: no work is
    // done and the function returns 0.
    //
    // On success, returns the number of bytes written to dst (always includes
    // the header_size header bytes, copied verbatim except for FLAG being
    // cleared from dst[0]).
    //
    // If expansion would write past dst_capacity - which only a malformed or
    // malicious packet should cause - decoding is aborted, *overflow is set
    // true, and the returned size reflects however much (if anything) was
    // salvaged; the caller should treat the packet as invalid.
    inline U32 decode(const U8* src, U32 src_size, U8* dst, U32 dst_capacity, U32 header_size, bool& overflow)
    {
        overflow = false;

        if (src_size < header_size || !(src[0] & FLAG))
        {
            return 0;
        }

        S32 count = (S32)(src_size - header_size);

        const U8* inptr = src;
        U8* outptr = dst;

        for (U32 ii = 0; ii < header_size; ++ii)
        {
            *outptr++ = *inptr++;
        }
        dst[0] &= ~FLAG;

        // reconstruct the body: a 0x00 byte starts a run; the byte(s) that
        // follow give its length (see the wire format described above).
        while (count--)
        {
            if (outptr > &dst[dst_capacity - 1])
            {
                overflow = true;
                outptr = dst;
                break;
            }

            if (!((*outptr++ = *inptr++)))
            {
                while ((count--) && (!(*inptr)))
                {
                    if (outptr > &dst[dst_capacity - 256])
                    {
                        overflow = true;
                        outptr = dst;
                        count = -1;
                        break;
                    }
                    *outptr++ = *inptr++;
                    memset(outptr, 0, 255);
                    outptr += 255;
                }

                if (count < 0)
                {
                    break;
                }
                else
                {
                    if (outptr > &dst[dst_capacity - (*inptr)])
                    {
                        overflow = true;
                        outptr = dst;
                    }
                    memset(outptr, 0, (*inptr) - 1);
                    outptr += ((*inptr) - 1);
                    inptr++;
                }
            }
        }

        return (U32)(outptr - dst);
    }
}

#endif // LL_LLZEROCODE_H