summaryrefslogtreecommitdiffstats
path: root/services/auth/source/ldap/util.go
blob: bd11e2d1193fd2de4edf787b150f04cc9ef077ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package ldap

// composeFullName composes a firstname surname or username
func composeFullName(firstname, surname, username string) string {
	switch {
	case len(firstname) == 0 && len(surname) == 0:
		return username
	case len(firstname) == 0:
		return surname
	case len(surname) == 0:
		return firstname
	default:
		return firstname + " " + surname
	}
}
m-junit-platform-launcher-1.13.1 Mirror of Apache POI: https://github.com/apache/poiwww-data
aboutsummaryrefslogtreecommitdiffstats
path: root/poi/src/test/java/org/apache/poi/hssf/dev/BiffViewer.java
blob: 21a8aff6d782318cb57e456f79c5ccb41f375d0a (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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
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
/* ====================================================================
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
==================================================================== */

package org.apache.poi.hssf.dev;

import static org.apache.logging.log4j.util.Unbox.box;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.output.CloseShieldOutputStream;
import org.apache.commons.io.output.NullOutputStream;
import org.apache.logging.log4j.Logger;
import org.apache.poi.logging.PoiLogManager;
import org.apache.poi.hssf.dev.BiffDumpingStream.IBiffRecordListener;
import org.apache.poi.hssf.record.ContinueRecord;
import org.apache.poi.hssf.record.HSSFRecordTypes;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.RecordInputStream;
import org.apache.poi.hssf.record.RecordInputStream.LeftoverDataException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.HexDump;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.RecordFormatException;
import org.apache.poi.util.StringUtil;

/**
 *  Utility for reading in BIFF8 records and displaying data from them.
 */
public final class BiffViewer {
    private static final char[] NEW_LINE_CHARS = System.getProperty("line.separator").toCharArray();
    private static final Logger LOG = PoiLogManager.getLogger(BiffViewer.class);
    private static final String ESCHER_SERIALIZE = "poi.deserialize.escher";
    private static final int DUMP_LINE_LEN = 16;
    private static final char[] COLUMN_SEPARATOR = " | ".toCharArray();

    private boolean biffHex;
    private boolean interpretRecords = true;
    private boolean rawHexOnly;
    private boolean noHeader = true;
    private boolean zeroAlignRecord = true;
    private final List<String> _headers = new ArrayList<>();


    /**
     * show hex dump of each BIFF record
     */
    public void setDumpBiffHex(boolean biffhex) {
        this.biffHex = biffhex;
    }

    /**
     * output interpretation of BIFF records
     */
    public void setInterpretRecords(boolean interpretRecords) {
        this.interpretRecords = interpretRecords;
    }

    /**
     * output raw hex dump of whole workbook stream
     */
    public void setOutputRawHexOnly(boolean rawhex) {
        this.rawHexOnly = rawhex;
    }

    /**
     * do not print record header - default is on
     */
    public void setSuppressHeader(boolean noHeader) {
        this.noHeader = noHeader;
    }

    /**
     * turn on deserialization of escher records (default is off)
     */
    public void setSerializeEscher(boolean serialize) {
        if (serialize) {
            System.setProperty(ESCHER_SERIALIZE, "true");
        } else {
            System.clearProperty(ESCHER_SERIALIZE);
        }
    }

    public void setZeroAlignRecord(boolean zeroAlignRecord) {
        this.zeroAlignRecord = zeroAlignRecord;
    }

    public void parse(File file) throws IOException {
        parse(file, System.out);
    }

    public void parse(File file, OutputStream os) throws IOException {
        try (POIFSFileSystem fs = new POIFSFileSystem(file, true);
             InputStream is = getPOIFSInputStream(fs);
             PrintWriter pw = wrap(os)
        ) {
            if (rawHexOnly) {
                byte[] data = IOUtils.toByteArray(is);
                HexDump.dump(data, 0, System.out, 0);
            } else {
                IBiffRecordListener recListener = (globalOffset, recordCounter, sid, dataSize, data) -> {
                    String header = formatRecordDetails(globalOffset, sid, dataSize, recordCounter);
                    if (!noHeader) {
                        _headers.add(header);
                    }
                    if (biffHex) {
                        pw.write(header);
                        pw.write(NEW_LINE_CHARS);
                        hexDumpAligned(pw, data, dataSize+4, globalOffset);
                        pw.flush();
                    }
                };

                try (InputStream is2 = new BiffDumpingStream(is, recListener)) {
                    createRecords(is2, pw);
                }
            }
        }
    }

    private static String formatRecordDetails(int globalOffset, int sid, int size, int recordCounter) {
        return "Offset=" + HexDump.intToHex(globalOffset) + "(" + globalOffset + ")" +
            " recno=" + recordCounter +
            " sid=" + HexDump.shortToHex(sid) +
            " size=" + HexDump.shortToHex(size) + "(" + size + ")";
    }

    /**
     *  Create an array of records from an input stream
     *
     * @param is the InputStream from which the records will be obtained
     * @param ps the PrintWriter to output the record data
     *
     * @throws  RecordFormatException  on error processing the InputStream
     */
    private void createRecords(InputStream is, PrintWriter ps) throws RecordFormatException {
        RecordInputStream recStream = new RecordInputStream(is);
        while (true) {
            _headers.clear();
            boolean hasNext;
            try {
                hasNext = recStream.hasNextRecord();
            } catch (LeftoverDataException e) {
                LOG.atError().withThrowable(e).log("Discarding {} bytes and continuing", box(recStream.remaining()));
                recStream.readRemainder();
                hasNext = recStream.hasNextRecord();
            }
            if (!hasNext) {
                break;
            }
            recStream.nextRecord();
            if (recStream.getSid() == 0) {
                continue;
            }
            Record record;
            if (interpretRecords) {
                record = HSSFRecordTypes.forSID(recStream.getSid()).getRecordConstructor().apply(recStream);
                if (record.getSid() == ContinueRecord.sid) {
                    continue;
                }

                _headers.forEach(ps::println);
                ps.print(record);
            } else {
                recStream.readRemainder();
            }
            ps.println();
        }
    }

    private static PrintWriter wrap(OutputStream os) {
        final OutputStream osOut;
        final Charset cs;

        if (os == null) {
            cs = Charset.defaultCharset();
            osOut = NullOutputStream.INSTANCE;
        } else if (os == System.out) {
            // Use the system default encoding when sending to System Out
            cs = Charset.defaultCharset();
            osOut = CloseShieldOutputStream.wrap(System.out);
        } else {
            cs = StringUtil.UTF8;
            osOut = os;
        }
        return new PrintWriter(new OutputStreamWriter(osOut, cs));
    }


    static InputStream getPOIFSInputStream(POIFSFileSystem fs) throws IOException {
        String workbookName = HSSFWorkbook.getWorkbookDirEntryName(fs.getRoot());
        return fs.createDocumentInputStream(workbookName);
    }


    /**
     * Hex-dumps a portion of a byte array in typical format, also preserving dump-line alignment
     * @param globalOffset (somewhat arbitrary) used to calculate the addresses printed at the
     * start of each line
     */
    private void hexDumpAligned(Writer w, byte[] data, int dumpLen, int globalOffset) {
        int baseDataOffset = 0;

        // perhaps this code should be moved to HexDump
        int globalStart = globalOffset + baseDataOffset;
        int globalEnd = globalOffset + baseDataOffset + dumpLen;
        int startDelta = globalStart % DUMP_LINE_LEN;
        int endDelta = globalEnd % DUMP_LINE_LEN;
        if (zeroAlignRecord) {
            endDelta -= startDelta;
            if (endDelta < 0) {
                endDelta += DUMP_LINE_LEN;
            }
            startDelta = 0;
        }
        int startLineAddr;
        int endLineAddr;
        if (zeroAlignRecord) {
            endLineAddr = globalEnd - endDelta - (globalStart - startDelta);
            startLineAddr = 0;
        } else {
            startLineAddr = globalStart - startDelta;
            endLineAddr = globalEnd - endDelta;
        }

        int lineDataOffset = baseDataOffset - startDelta;
        int lineAddr = startLineAddr;

        // output (possibly incomplete) first line
        if (startLineAddr == endLineAddr) {
            hexDumpLine(w, data, lineAddr, lineDataOffset, startDelta, endDelta);
            return;
        }
        hexDumpLine(w, data, lineAddr, lineDataOffset, startDelta, DUMP_LINE_LEN);

        // output all full lines in the middle
        while (true) {
            lineAddr += DUMP_LINE_LEN;
            lineDataOffset += DUMP_LINE_LEN;
            if (lineAddr >= endLineAddr) {
                break;
            }
            hexDumpLine(w, data, lineAddr, lineDataOffset, 0, DUMP_LINE_LEN);
        }


        // output (possibly incomplete) last line
        if (endDelta != 0) {
            hexDumpLine(w, data, lineAddr, lineDataOffset, 0, endDelta);
        }
    }

    private static void hexDumpLine(Writer w, byte[] data, int lineStartAddress, int lineDataOffset, int startDelta, int endDelta) {
        final char[] buf = new char[8+2*COLUMN_SEPARATOR.length+DUMP_LINE_LEN*3-1+DUMP_LINE_LEN+NEW_LINE_CHARS.length];

        if (startDelta >= endDelta) {
            throw new IllegalArgumentException("Bad start/end delta");
        }
        int idx=0;
        try {
            writeHex(buf, idx, lineStartAddress, 8);
            idx = arraycopy(COLUMN_SEPARATOR, buf, idx+8);
            // raw hex data
            for (int i=0; i< DUMP_LINE_LEN; i++) {
                if (i>0) {
                    buf[idx++] = ' ';
                }
                if (i >= startDelta && i < endDelta) {
                    writeHex(buf, idx, data[lineDataOffset+i], 2);
                } else {
                    buf[idx] = ' ';
                    buf[idx+1] = ' ';
                }
                idx += 2;
            }
            idx = arraycopy(COLUMN_SEPARATOR, buf, idx);

            // interpreted ascii
            for (int i=0; i< DUMP_LINE_LEN; i++) {
                char ch = ' ';
                if (i >= startDelta && i < endDelta) {
                    ch = getPrintableChar(data[lineDataOffset+i]);
                }
                buf[idx++] = ch;
            }

            idx = arraycopy(NEW_LINE_CHARS, buf, idx);

            w.write(buf, 0, idx);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    private static int arraycopy(char[] in, char[] out, int pos) {
        int idx = pos;
        for (char c : in) {
            out[idx++] = c;
        }
        return idx;
    }

    private static char getPrintableChar(byte b) {
        char ib = (char) (b & 0x00FF);
        if (ib < 32 || ib > 126) {
            return '.';
        }
        return ib;
    }

    private static void writeHex(char[] buf, int startInBuf, int value, int nDigits) {
        int acc = value;
        for(int i=nDigits-1; i>=0; i--) {
            int digit = acc & 0x0F;
            buf[startInBuf+i] = (char) (digit < 10 ? ('0' + digit) : ('A' + digit - 10));
            acc >>>= 4;
        }
    }
}