TestSocketFactory.java 30.5 KB
Newer Older
1
/*
2
 * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
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
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code 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 General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketOption;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMIServerSocketFactory;
import java.rmi.server.RMISocketFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;

51 52 53 54 55 56
/*
 * @test
 * @summary TestSocket Factory and tests of the basic trigger, match, and replace functions
 * @run testng TestSocketFactory
 * @bug 8186539
 */
57 58 59

/**
 * A RMISocketFactory utility factory to log RMI stream contents and to
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
 * trigger, and then match and replace output stream contents to simulate failures.
 * <p>
 * The trigger is a sequence of bytes that must be found before looking
 * for the bytes to match and replace.  If the trigger sequence is empty
 * matching is immediately enabled. While waiting for the trigger to be found
 * bytes written to the streams are written through to the output stream.
 * The when triggered and when a trigger is non-empty, matching looks for
 * the sequence of bytes supplied.  If the sequence is empty, no matching or
 * replacement is performed.
 * While waiting for a complete match, the partial matched bytes are not
 * written to the output stream.  When the match is incomplete, the partial
 * matched bytes are written to the output.  When a match is complete the
 * full replacement byte array is written to the output.
 * <p>
 * The trigger, match, and replacement bytes arrays can be changed at any
 * time and immediately reset and restart matching.  Changes are propagated
 * to all of the sockets created from the factories immediately.
77 78 79 80 81 82
 */
public class TestSocketFactory extends RMISocketFactory
        implements RMIClientSocketFactory, RMIServerSocketFactory, Serializable {

    private static final long serialVersionUID = 1L;

83 84
    private volatile transient byte[] triggerBytes;

85 86 87 88 89 90 91 92
    private volatile transient byte[] matchBytes;

    private volatile transient byte[] replaceBytes;

    private transient final List<InterposeSocket> sockets = new ArrayList<>();

    private transient final List<InterposeServerSocket> serverSockets = new ArrayList<>();

93 94
    static final byte[] EMPTY_BYTE_ARRAY = new byte[0];

95 96
    // True to enable logging of matches and replacements.
    private static volatile boolean debugLogging = false;
97 98 99 100 101 102 103

    /**
     * Debugging output can be synchronized with logging of RMI actions.
     *
     * @param format a printf format
     * @param args   any args
     */
104 105
    public static void DEBUG(String format, Object... args) {
        if (debugLogging) {
106 107 108 109 110
            System.err.printf(format, args);
        }
    }

    /**
111 112
     * Create a socket factory that creates InputStreams
     * and OutputStreams that log.
113 114
     */
    public TestSocketFactory() {
115 116 117
        this.triggerBytes = EMPTY_BYTE_ARRAY;
        this.matchBytes = EMPTY_BYTE_ARRAY;
        this.replaceBytes = EMPTY_BYTE_ARRAY;
118 119
    }

120 121 122 123 124 125 126 127 128 129 130
    /**
     * Set debug to true to generate logging output of matches and substitutions.
     * @param debug {@code true} to generate logging output
     * @return the previous value
     */
    public static boolean setDebug(boolean debug) {
        boolean oldDebug = debugLogging;
        debugLogging = debug;
        return oldDebug;
    }

131 132 133 134 135 136 137
    /**
     * Set the match and replacement bytes, with an empty trigger.
     * The match and replacements are propagated to all existing sockets.
     *
     * @param matchBytes bytes to match
     * @param replaceBytes bytes to replace the matched bytes
     */
138
    public void setMatchReplaceBytes(byte[] matchBytes, byte[] replaceBytes) {
139 140 141 142 143 144 145 146 147 148 149 150 151 152
        setMatchReplaceBytes(EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
    }

    /**
     * Set the trigger, match, and replacement bytes.
     * The trigger, match, and replacements are propagated to all existing sockets.
     *
     * @param triggerBytes array of bytes to use as a trigger, may be zero length
     * @param matchBytes bytes to match after the trigger has been seen
     * @param replaceBytes bytes to replace the matched bytes
     */
    public void setMatchReplaceBytes(byte[] triggerBytes, byte[] matchBytes,
                                     byte[] replaceBytes) {
        this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
153 154
        this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
        this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
155 156 157 158
        sockets.forEach( s -> s.setMatchReplaceBytes(triggerBytes, matchBytes,
                replaceBytes));
        serverSockets.forEach( s -> s.setMatchReplaceBytes(triggerBytes, matchBytes,
                replaceBytes));
159 160 161 162 163 164
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException {
        Socket socket = RMISocketFactory.getDefaultSocketFactory()
                .createSocket(host, port);
165 166
        InterposeSocket s = new InterposeSocket(socket,
                triggerBytes, matchBytes, replaceBytes);
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
        sockets.add(s);
        return s;
    }

    /**
     * Return the current list of sockets.
     * @return Return a snapshot of the current list of sockets
     */
    public List<InterposeSocket> getSockets() {
        List<InterposeSocket> snap = new ArrayList<>(sockets);
        return snap;
    }

    @Override
    public ServerSocket createServerSocket(int port) throws IOException {

        ServerSocket serverSocket = RMISocketFactory.getDefaultSocketFactory()
                .createServerSocket(port);
185 186
        InterposeServerSocket ss = new InterposeServerSocket(serverSocket,
                triggerBytes, matchBytes, replaceBytes);
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
        serverSockets.add(ss);
        return ss;
    }

    /**
     * Return the current list of server sockets.
     * @return Return a snapshot of the current list of server sockets
     */
    public List<InterposeServerSocket> getServerSockets() {
        List<InterposeServerSocket> snap = new ArrayList<>(serverSockets);
        return snap;
    }

    /**
     * An InterposeSocket wraps a socket that produces InputStreams
     * and OutputStreams that log the traffic.
203 204
     * The OutputStreams it produces watch for a trigger and then
     * match an array of bytes and replace them.
205 206 207 208 209 210
     * Useful for injecting protocol and content errors.
     */
    public static class InterposeSocket extends Socket {
        private final Socket socket;
        private InputStream in;
        private MatchReplaceOutputStream out;
211
        private volatile byte[] triggerBytes;
212 213 214 215 216 217 218
        private volatile byte[] matchBytes;
        private volatile byte[] replaceBytes;
        private final ByteArrayOutputStream inLogStream;
        private final ByteArrayOutputStream outLogStream;
        private final String name;
        private static volatile int num = 0;    // index for created InterposeSockets

219 220 221 222 223 224 225
        /**
         * Construct a socket that interposes on a socket to match and replace.
         * The trigger is empty.
         * @param socket the underlying socket
         * @param matchBytes the bytes that must match
         * @param replaceBytes the replacement bytes
         */
226
        public InterposeSocket(Socket socket, byte[] matchBytes, byte[] replaceBytes) {
227 228 229 230 231 232 233 234 235 236 237 238
            this(socket, EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
        }

        /**
         * Construct a socket that interposes on a socket to match and replace.
         * @param socket the underlying socket
         * @param triggerBytes array of bytes to enable matching
         * @param matchBytes the bytes that must match
         * @param replaceBytes the replacement bytes
         */
        public InterposeSocket(Socket socket, byte[]
                triggerBytes, byte[] matchBytes, byte[] replaceBytes) {
239
            this.socket = socket;
240
            this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
241 242 243 244 245 246 247 248 249
            this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
            this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
            this.inLogStream = new ByteArrayOutputStream();
            this.outLogStream = new ByteArrayOutputStream();
            this.name = "IS" + ++num + "::"
                    + Thread.currentThread().getName() + ": "
                    + socket.getLocalPort() + " <  " + socket.getPort();
        }

250 251 252 253 254 255 256
        /**
         * Set the match and replacement bytes, with an empty trigger.
         * The match and replacements are propagated to all existing sockets.
         *
         * @param matchBytes bytes to match
         * @param replaceBytes bytes to replace the matched bytes
         */
257
        public void setMatchReplaceBytes(byte[] matchBytes, byte[] replaceBytes) {
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
            this.setMatchReplaceBytes(EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
        }

        /**
         * Set the trigger, match, and replacement bytes.
         * The trigger, match, and replacements are propagated to the
         * MatchReplaceOutputStream.
         *
         * @param triggerBytes array of bytes to use as a trigger, may be zero length
         * @param matchBytes bytes to match after the trigger has been seen
         * @param replaceBytes bytes to replace the matched bytes
         */
        public void setMatchReplaceBytes(byte[] triggerBytes, byte[] matchBytes,
                                         byte[] replaceBytes) {
            this.triggerBytes = triggerBytes;
273 274
            this.matchBytes = matchBytes;
            this.replaceBytes = replaceBytes;
275
            out.setMatchReplaceBytes(triggerBytes, matchBytes, replaceBytes);
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
        }

        @Override
        public void connect(SocketAddress endpoint) throws IOException {
            socket.connect(endpoint);
        }

        @Override
        public void connect(SocketAddress endpoint, int timeout) throws IOException {
            socket.connect(endpoint, timeout);
        }

        @Override
        public void bind(SocketAddress bindpoint) throws IOException {
            socket.bind(bindpoint);
        }

        @Override
        public InetAddress getInetAddress() {
            return socket.getInetAddress();
        }

        @Override
        public InetAddress getLocalAddress() {
            return socket.getLocalAddress();
        }

        @Override
        public int getPort() {
            return socket.getPort();
        }

        @Override
        public int getLocalPort() {
            return socket.getLocalPort();
        }

        @Override
        public SocketAddress getRemoteSocketAddress() {
            return socket.getRemoteSocketAddress();
        }

        @Override
        public SocketAddress getLocalSocketAddress() {
            return socket.getLocalSocketAddress();
        }

        @Override
        public SocketChannel getChannel() {
            return socket.getChannel();
        }

        @Override
        public synchronized void close() throws IOException {
            socket.close();
        }

        @Override
        public String toString() {
            return "InterposeSocket " + name + ": " + socket.toString();
        }

        @Override
        public boolean isConnected() {
            return socket.isConnected();
        }

        @Override
        public boolean isBound() {
            return socket.isBound();
        }

        @Override
        public boolean isClosed() {
            return socket.isClosed();
        }

        @Override
        public synchronized InputStream getInputStream() throws IOException {
            if (in == null) {
                in = socket.getInputStream();
                String name = Thread.currentThread().getName() + ": "
                        + socket.getLocalPort() + " <  " + socket.getPort();
                in = new LoggingInputStream(in, name, inLogStream);
                DEBUG("Created new InterposeInputStream: %s%n", name);
            }
            return in;
        }

        @Override
        public synchronized OutputStream getOutputStream() throws IOException {
            if (out == null) {
                OutputStream o = socket.getOutputStream();
                String name = Thread.currentThread().getName() + ": "
                        + socket.getLocalPort() + "  > " + socket.getPort();
371 372
                out = new MatchReplaceOutputStream(o, name, outLogStream,
                        triggerBytes, matchBytes, replaceBytes);
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
                DEBUG("Created new MatchReplaceOutputStream: %s%n", name);
            }
            return out;
        }

        /**
         * Return the bytes logged from the input stream.
         * @return Return the bytes logged from the input stream.
         */
        public byte[] getInLogBytes() {
            return inLogStream.toByteArray();
        }

        /**
         * Return the bytes logged from the output stream.
         * @return Return the bytes logged from the output stream.
         */
        public byte[] getOutLogBytes() {
            return outLogStream.toByteArray();
        }

    }

    /**
     * InterposeServerSocket is a ServerSocket that wraps each Socket it accepts
     * with an InterposeSocket so that its input and output streams can be monitored.
     */
    public static class InterposeServerSocket extends ServerSocket {
        private final ServerSocket socket;
402
        private volatile byte[] triggerBytes;
403 404 405 406
        private volatile byte[] matchBytes;
        private volatile byte[] replaceBytes;
        private final List<InterposeSocket> sockets = new ArrayList<>();

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
        /**
         * Construct a server socket that interposes on a socket to match and replace.
         * The trigger is empty.
         * @param socket the underlying socket
         * @param matchBytes the bytes that must match
         * @param replaceBytes the replacement bytes
         */
        public InterposeServerSocket(ServerSocket socket, byte[] matchBytes,
                                     byte[] replaceBytes) throws IOException {
            this(socket, EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
        }

        /**
         * Construct a server socket that interposes on a socket to match and replace.
         * @param socket the underlying socket
         * @param triggerBytes array of bytes to enable matching
         * @param matchBytes the bytes that must match
         * @param replaceBytes the replacement bytes
         */
        public InterposeServerSocket(ServerSocket socket, byte[] triggerBytes,
                                     byte[] matchBytes, byte[] replaceBytes) throws IOException {
428
            this.socket = socket;
429
            this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
430 431 432 433
            this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
            this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
        }

434 435 436 437 438 439 440
        /**
         * Set the match and replacement bytes, with an empty trigger.
         * The match and replacements are propagated to all existing sockets.
         *
         * @param matchBytes bytes to match
         * @param replaceBytes bytes to replace the matched bytes
         */
441
        public void setMatchReplaceBytes(byte[] matchBytes, byte[] replaceBytes) {
442 443 444 445 446 447 448 449 450 451 452 453 454 455
            setMatchReplaceBytes(EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
        }

        /**
         * Set the trigger, match, and replacement bytes.
         * The trigger, match, and replacements are propagated to all existing sockets.
         *
         * @param triggerBytes array of bytes to use as a trigger, may be zero length
         * @param matchBytes bytes to match after the trigger has been seen
         * @param replaceBytes bytes to replace the matched bytes
         */
        public void setMatchReplaceBytes(byte[] triggerBytes, byte[] matchBytes,
                                         byte[] replaceBytes) {
            this.triggerBytes = triggerBytes;
456 457
            this.matchBytes = matchBytes;
            this.replaceBytes = replaceBytes;
458
            sockets.forEach(s -> s.setMatchReplaceBytes(triggerBytes, matchBytes, replaceBytes));
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
        }
        /**
         * Return a snapshot of the current list of sockets created from this server socket.
         * @return Return a snapshot of the current list of sockets
         */
        public List<InterposeSocket> getSockets() {
            List<InterposeSocket> snap = new ArrayList<>(sockets);
            return snap;
        }

        @Override
        public void bind(SocketAddress endpoint) throws IOException {
            socket.bind(endpoint);
        }

        @Override
        public void bind(SocketAddress endpoint, int backlog) throws IOException {
            socket.bind(endpoint, backlog);
        }

        @Override
        public InetAddress getInetAddress() {
            return socket.getInetAddress();
        }

        @Override
        public int getLocalPort() {
            return socket.getLocalPort();
        }

        @Override
        public SocketAddress getLocalSocketAddress() {
            return socket.getLocalSocketAddress();
        }

        @Override
        public Socket accept() throws IOException {
            Socket s = socket.accept();
            InterposeSocket socket = new InterposeSocket(s, matchBytes, replaceBytes);
            sockets.add(socket);
            return socket;
        }

        @Override
        public void close() throws IOException {
            socket.close();
        }

        @Override
        public ServerSocketChannel getChannel() {
            return socket.getChannel();
        }

        @Override
        public boolean isClosed() {
            return socket.isClosed();
        }

        @Override
        public String toString() {
            return socket.toString();
        }

        @Override
        public synchronized void setSoTimeout(int timeout) throws SocketException {
            socket.setSoTimeout(timeout);
        }

        @Override
        public synchronized int getSoTimeout() throws IOException {
            return socket.getSoTimeout();
        }
    }

    /**
     * LoggingInputStream is a stream and logs all bytes read to it.
     * For identification it is given a name.
     */
    public static class LoggingInputStream extends FilterInputStream {
        private int bytesIn = 0;
        private final String name;
        private final OutputStream log;

        public LoggingInputStream(InputStream in, String name, OutputStream log) {
            super(in);
            this.name = name;
            this.log = log;
        }

        @Override
        public int read() throws IOException {
            int b = super.read();
            if (b >= 0) {
                log.write(b);
                bytesIn++;
            }
            return b;
        }

        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            int bytes = super.read(b, off, len);
            if (bytes > 0) {
                log.write(b, off, bytes);
                bytesIn += bytes;
            }
            return bytes;
        }

        @Override
        public int read(byte[] b) throws IOException {
            return read(b, 0, b.length);
        }

        @Override
        public void close() throws IOException {
            super.close();
        }

        @Override
        public String toString() {
            return String.format("%s: In: (%d)", name, bytesIn);
        }
    }

    /**
585 586
     * An OutputStream that looks for a trigger to enable matching and
     * replaces one string of bytes with another.
587 588 589 590 591
     * If any range matches, the match starts after the partial match.
     */
    static class MatchReplaceOutputStream extends OutputStream {
        private final OutputStream out;
        private final String name;
592
        private volatile byte[] triggerBytes;
593 594
        private volatile byte[] matchBytes;
        private volatile byte[] replaceBytes;
595
        int triggerIndex;
596 597 598 599 600 601
        int matchIndex;
        private int bytesOut = 0;
        private final OutputStream log;

        MatchReplaceOutputStream(OutputStream out, String name, OutputStream log,
                                 byte[] matchBytes, byte[] replaceBytes) {
602 603 604 605 606 607
            this(out, name, log, EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
        }

        MatchReplaceOutputStream(OutputStream out, String name, OutputStream log,
                                 byte[] triggerBytes, byte[] matchBytes,
                                 byte[] replaceBytes) {
608 609
            this.out = out;
            this.name = name;
610 611
            this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
            triggerIndex = 0;
612 613 614 615 616 617 618
            this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
            this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
            matchIndex = 0;
            this.log = log;
        }

        public void setMatchReplaceBytes(byte[] matchBytes, byte[] replaceBytes) {
619 620 621 622 623 624 625 626 627
            setMatchReplaceBytes(EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
        }

        public void setMatchReplaceBytes(byte[] triggerBytes, byte[] matchBytes,
                                         byte[] replaceBytes) {
            this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
            triggerIndex = 0;
            this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
            this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
628 629 630 631 632 633 634
            matchIndex = 0;
        }


        public void write(int b) throws IOException {
            b = b & 0xff;
            if (matchBytes.length == 0) {
635
                // fast path, no match
636 637 638 639 640
                out.write(b);
                log.write(b);
                bytesOut++;
                return;
            }
641 642 643 644 645 646 647 648 649
            // if trigger not satisfied, keep looking
            if (triggerBytes.length != 0 && triggerIndex < triggerBytes.length) {
                out.write(b);
                log.write(b);
                bytesOut++;

                triggerIndex = (b == (triggerBytes[triggerIndex] & 0xff))
                        ? ++triggerIndex    // matching advance
                        : 0;
650
            } else {
651
                // trigger not used or has been satisfied
652
                if (b == (matchBytes[matchIndex] & 0xff)) {
653 654 655 656 657 658 659 660 661 662
                    if (++matchIndex >= matchBytes.length) {
                        matchIndex = 0;
                        triggerIndex = 0;       // match/replace ok, reset trigger
                        DEBUG("TestSocketFactory MatchReplace %s replaced %d bytes " +
                                "at offset: %d (x%04x)%n",
                                name, replaceBytes.length, bytesOut, bytesOut);
                        out.write(replaceBytes);
                        log.write(replaceBytes);
                        bytesOut += replaceBytes.length;
                    }
663
                } else {
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
                    if (matchIndex > 0) {
                        // mismatch, write out any that matched already
                        DEBUG("Partial match %s matched %d bytes at offset: %d (0x%04x), expected: x%02x, actual: x%02x%n",
                            name, matchIndex, bytesOut, bytesOut, matchBytes[matchIndex], b);
                        out.write(matchBytes, 0, matchIndex);
                        log.write(matchBytes, 0, matchIndex);
                        bytesOut += matchIndex;
                        matchIndex = 0;
                    }
                    if (b == (matchBytes[matchIndex] & 0xff)) {
                        matchIndex++;
                    } else {
                        out.write(b);
                        log.write(b);
                        bytesOut++;
                    }
680 681 682 683
                }
            }
        }

684 685 686 687 688 689 690 691 692 693 694 695 696
        public void flush() throws IOException {
            if (matchIndex > 0) {
                // write out any that matched already to avoid consumer hang.
                // Match/replace across a flush is not supported.
                DEBUG( "Flush partial match %s matched %d bytes at offset: %d (0x%04x)%n",
                        name, matchIndex, bytesOut, bytesOut);
                out.write(matchBytes, 0, matchIndex);
                log.write(matchBytes, 0, matchIndex);
                bytesOut += matchIndex;
                matchIndex = 0;
            }
        }

697 698 699 700 701 702
        @Override
        public String toString() {
            return String.format("%s: Out: (%d)", name, bytesOut);
        }
    }

703 704
    private static byte[] obj1Data = new byte[] {
            0x7e, 0x7e, 0x7e,
705
            (byte) 0x80, 0x05,
706 707 708 709 710
            0x7f, 0x7f, 0x7f,
            0x73, 0x72, 0x00, 0x10, // TC_OBJECT, TC_CLASSDESC, length = 16
            (byte)'j', (byte)'a', (byte)'v', (byte)'a', (byte)'.',
            (byte)'l', (byte)'a', (byte)'n', (byte)'g', (byte)'.',
            (byte)'n', (byte)'u', (byte)'m', (byte)'b', (byte)'e', (byte)'r'
711
    };
712 713
    private static byte[] obj1Result = new byte[] {
            0x7e, 0x7e, 0x7e,
714
            (byte) 0x80, 0x05,
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
            0x7f, 0x7f, 0x7f,
            0x73, 0x72, 0x00, 0x11, // TC_OBJECT, TC_CLASSDESC, length = 17
            (byte)'j', (byte)'a', (byte)'v', (byte)'a', (byte)'.',
            (byte)'l', (byte)'a', (byte)'n', (byte)'g', (byte)'.',
            (byte)'I', (byte)'n', (byte)'t', (byte)'e', (byte)'g', (byte)'e', (byte)'r'
    };
    private static byte[] obj1Trigger = new byte[] {
            (byte) 0x80, 0x05
    };
    private static byte[] obj1Trigger2 = new byte[] {
            0x7D, 0x7D, 0x7D, 0x7D,
    };
    private static byte[] obj1Trigger3 = new byte[] {
            0x7F,
    };
    private static byte[] obj1Match = new byte[] {
            0x73, 0x72, 0x00, 0x10, // TC_OBJECT, TC_CLASSDESC, length = 16
            (byte)'j', (byte)'a', (byte)'v', (byte)'a', (byte)'.',
            (byte)'l', (byte)'a', (byte)'n', (byte)'g', (byte)'.',
            (byte)'n', (byte)'u', (byte)'m', (byte)'b', (byte)'e', (byte)'r'
    };
    private static byte[] obj1Repl = new byte[] {
            0x73, 0x72, 0x00, 0x11, // TC_OBJECT, TC_CLASSDESC, length = 17
            (byte)'j', (byte)'a', (byte)'v', (byte)'a', (byte)'.',
            (byte)'l', (byte)'a', (byte)'n', (byte)'g', (byte)'.',
            (byte)'I', (byte)'n', (byte)'t', (byte)'e', (byte)'g', (byte)'e', (byte)'r'
741 742 743 744 745 746 747 748 749 750 751 752 753 754
    };

    @DataProvider(name = "MatchReplaceData")
    static Object[][] matchReplaceData() {
        byte[] empty = new byte[0];
        byte[] byte1 = new byte[]{1, 2, 3, 4, 5, 6};
        byte[] bytes2 = new byte[]{1, 2, 4, 3, 5, 6};
        byte[] bytes3 = new byte[]{6, 5, 4, 3, 2, 1};
        byte[] bytes4 = new byte[]{1, 2, 0x10, 0x20, 0x30, 0x40, 5, 6};
        byte[] bytes4a = new byte[]{1, 2, 0x10, 0x20, 0x30, 0x40, 5, 7};  // mostly matches bytes4
        byte[] bytes5 = new byte[]{0x30, 0x40, 5, 6};
        byte[] bytes6 = new byte[]{1, 2, 0x10, 0x20, 0x30};

        return new Object[][]{
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
                {EMPTY_BYTE_ARRAY, new byte[]{}, new byte[]{},
                        empty, empty},
                {EMPTY_BYTE_ARRAY, new byte[]{}, new byte[]{},
                        byte1, byte1},
                {EMPTY_BYTE_ARRAY, new byte[]{3, 4}, new byte[]{4, 3},
                        byte1, bytes2}, //swap bytes
                {EMPTY_BYTE_ARRAY, new byte[]{3, 4}, new byte[]{0x10, 0x20, 0x30, 0x40},
                        byte1, bytes4}, // insert
                {EMPTY_BYTE_ARRAY, new byte[]{1, 2, 0x10, 0x20}, new byte[]{},
                        bytes4, bytes5}, // delete head
                {EMPTY_BYTE_ARRAY, new byte[]{0x40, 5, 6}, new byte[]{},
                        bytes4, bytes6},   // delete tail
                {EMPTY_BYTE_ARRAY, new byte[]{0x40, 0x50}, new byte[]{0x60, 0x50},
                        bytes4, bytes4}, // partial match, replace nothing
                {EMPTY_BYTE_ARRAY, bytes4a, bytes3,
                        bytes4, bytes4}, // long partial match, not replaced
                {EMPTY_BYTE_ARRAY, obj1Match, obj1Repl,
                        obj1Match, obj1Repl},
                {obj1Trigger, obj1Match, obj1Repl,
                        obj1Data, obj1Result},
                {obj1Trigger3, obj1Match, obj1Repl,
                        obj1Data, obj1Result}, // different trigger, replace
                {obj1Trigger2, obj1Match, obj1Repl,
                        obj1Data, obj1Data},  // no trigger, no replace
779 780 781
        };
    }

782 783
    @Test(dataProvider = "MatchReplaceData")
    public static void test1(byte[] trigger, byte[] match, byte[] replace,
784
                      byte[] input, byte[] expected) {
785 786
        System.out.printf("trigger: %s, match: %s, replace: %s%n", Arrays.toString(trigger),
                Arrays.toString(match), Arrays.toString(replace));
787 788 789
        try (ByteArrayOutputStream output = new ByteArrayOutputStream();
        ByteArrayOutputStream log = new ByteArrayOutputStream();
             OutputStream out = new MatchReplaceOutputStream(output, "test3",
790
                     log, trigger, match, replace)) {
791 792 793 794 795 796 797 798 799 800 801 802 803
            out.write(input);
            byte[] actual = output.toByteArray();

            if (!Arrays.equals(actual, expected)) {
                System.out.printf("actual: %s%n", Arrays.toString(actual));
                System.out.printf("expected: %s%n", Arrays.toString(expected));
            }
            Assert.assertEquals(actual, expected, "match/replace fail");
        } catch (IOException ioe) {
            Assert.fail("unexpected exception", ioe);
        }
    }
}