input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code public boolean connect(SharingPeer peer) { Socket socket = new Socket(); InetSocketAddress address = new InetSocketAddress(peer.getIp(), peer.getPort()); logger.info("Connecting to " + peer + "..."); try { socket.connect(address, 3*1000); } catch (IOException ioe) { // Could not connect to peer, abort logger.warn("Could not connect to " + peer + ": " + ioe.getMessage()); return false; } try { this.sendHandshake(socket); Handshake hs = this.validateHandshake(socket, (peer.hasPeerId() ? peer.getPeerId().array() : null)); this.fireNewPeerConnection(socket, hs.getPeerId()); return true; } catch (ParseException pe) { logger.info("Invalid handshake from " + this.socketRepr(socket) + ": " + pe.getMessage()); try { socket.close(); } catch (IOException e) { } } catch (IOException ioe) { logger.info("An error occured while reading an incoming " + "handshake: " + ioe.getMessage()); try { if (!socket.isClosed()) { socket.close(); } } catch (IOException e) { // Ignore } } return false; } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code public boolean connect(SharingPeer peer) { Socket socket = new Socket(); InetSocketAddress address = new InetSocketAddress(peer.getIp(), peer.getPort()); logger.info("Connecting to {}...", peer); try { socket.connect(address, 3*1000); } catch (IOException ioe) { // Could not connect to peer, abort logger.warn("Could not connect to {}: {}", peer, ioe.getMessage()); return false; } try { this.sendHandshake(socket); Handshake hs = this.validateHandshake(socket, (peer.hasPeerId() ? peer.getPeerId().array() : null)); this.fireNewPeerConnection(socket, hs.getPeerId()); return true; } catch (ParseException pe) { logger.info("Invalid handshake from {}: {}", this.socketRepr(socket), pe.getMessage()); try { socket.close(); } catch (IOException e) { } } catch (IOException ioe) { logger.info("An error occured while reading an incoming " + "handshake: {}", ioe.getMessage()); try { if (!socket.isClosed()) { socket.close(); } } catch (IOException e) { // Ignore } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static String hashPieces(File source) throws NoSuchAlgorithmException, IOException { MessageDigest md = MessageDigest.getInstance("SHA-1"); FileInputStream fis = new FileInputStream(source); StringBuffer pieces = new StringBuffer(); byte[] data = new byte[Torrent.PIECE_LENGTH]; int read; while ((read = fis.read(data)) > 0) { md.reset(); md.update(data, 0, read); pieces.append(new String(md.digest(), Torrent.BYTE_ENCODING)); } fis.close(); int n_pieces = new Double(Math.ceil((double)source.length() / Torrent.PIECE_LENGTH)).intValue(); logger.debug("Hashed {} ({} bytes) in {} pieces.", new Object[] { source.getName(), source.length(), n_pieces }); return pieces.toString(); } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code private static String hashPieces(File source) throws NoSuchAlgorithmException, IOException { long start = System.nanoTime(); long hashTime = 0L; MessageDigest md = MessageDigest.getInstance("SHA-1"); InputStream is = new BufferedInputStream(new FileInputStream(source)); StringBuffer pieces = new StringBuffer(); byte[] data = new byte[Torrent.PIECE_LENGTH]; int read; while ((read = is.read(data)) > 0) { md.reset(); md.update(data, 0, read); long hashStart = System.nanoTime(); pieces.append(new String(md.digest(), Torrent.BYTE_ENCODING)); hashTime += (System.nanoTime() - hashStart); } is.close(); int n_pieces = new Double(Math.ceil((double)source.length() / Torrent.PIECE_LENGTH)).intValue(); logger.info("Hashed {} ({} bytes) in {} pieces (total: {}ms, " + "{}ms hashing).", new Object[] { source.getName(), source.length(), n_pieces, String.format("%.1f", (System.nanoTime() - start) / 1024), String.format("%.1f", hashTime / 1024), }); return pieces.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public MetadataBuilder addDataSource(@NotNull InputStream dataSource, String path, boolean closeAfterBuild) { sources.add(new Source(dataSource, path, closeAfterBuild)); return this; } #location 2 #vulnerability type RESOURCE_LEAK
#fixed code public MetadataBuilder addDataSource(@NotNull InputStream dataSource, String path, boolean closeAfterBuild) { checkHashingResultIsNotSet(); filesPaths.add(path); dataSources.add(new StreamBasedHolderImpl(dataSource, closeAfterBuild)); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { // First, analyze the torrent's local data. try { this.torrent.init(); } catch (ClosedByInterruptException cbie) { logger.warn("Client was interrupted during initialization. " + "Aborting right away."); this.setState(ClientState.ERROR); return; } catch (IOException ioe) { logger.error("Could not initialize torrent file data!", ioe); this.setState(ClientState.ERROR); return; } // Initial completion test if (this.torrent.isComplete()) { this.seed(); } else { this.setState(ClientState.SHARING); } this.announce.start(); this.service.start(); int optimisticIterations = 0; int rateComputationIterations = 0; while (!this.stop) { optimisticIterations = (optimisticIterations == 0 ? Client.OPTIMISTIC_UNCHOKE_ITERATIONS : optimisticIterations - 1); rateComputationIterations = (rateComputationIterations == 0 ? Client.RATE_COMPUTATION_ITERATIONS : rateComputationIterations - 1); try { this.unchokePeers(optimisticIterations == 0); this.info(); if (rateComputationIterations == 0) { this.resetPeerRates(); } } catch (Exception e) { logger.error("An exception occurred during the BitTorrent " + "client main loop execution!", e); } try { Thread.sleep(Client.UNCHOKING_FREQUENCY*1000); } catch (InterruptedException ie) { logger.trace("BitTorrent main loop interrupted."); } } logger.debug("Stopping BitTorrent client connection service " + "and announce threads..."); this.service.stop(); this.announce.stop(); // Close all peer connections logger.debug("Closing all remaining peer connections..."); for (SharingPeer peer : this.connected.values()) { peer.unbind(true); } // Determine final state if (this.torrent.isComplete()) { this.setState(ClientState.DONE); } else { this.setState(ClientState.ERROR); } logger.info("BitTorrent client signing off."); } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void run() { // First, analyze the torrent's local data. try { this.torrent.init(); } catch (ClosedByInterruptException cbie) { logger.warn("Client was interrupted during initialization. " + "Aborting right away."); this.setState(ClientState.ERROR); return; } catch (IOException ioe) { logger.error("Could not initialize torrent file data!", ioe); this.setState(ClientState.ERROR); return; } // Initial completion test if (this.torrent.isComplete()) { this.seed(); } else { this.setState(ClientState.SHARING); } this.announce.start(); this.service.start(); int optimisticIterations = 0; int rateComputationIterations = 0; while (!this.stop) { optimisticIterations = (optimisticIterations == 0 ? Client.OPTIMISTIC_UNCHOKE_ITERATIONS : optimisticIterations - 1); rateComputationIterations = (rateComputationIterations == 0 ? Client.RATE_COMPUTATION_ITERATIONS : rateComputationIterations - 1); try { this.unchokePeers(optimisticIterations == 0); this.info(); if (rateComputationIterations == 0) { this.resetPeerRates(); } } catch (Exception e) { logger.error("An exception occurred during the BitTorrent " + "client main loop execution!", e); } try { Thread.sleep(Client.UNCHOKING_FREQUENCY*1000); } catch (InterruptedException ie) { logger.trace("BitTorrent main loop interrupted."); } } logger.debug("Stopping BitTorrent client connection service " + "and announce threads..."); this.service.stop(); this.announce.stop(); // Close all peer connections logger.debug("Closing all remaining peer connections..."); for (SharingPeer peer : this.connected.values()) { peer.unbind(true); } this.torrent.close(); // Determine final state if (this.torrent.isComplete()) { this.setState(ClientState.DONE); } else { this.setState(ClientState.ERROR); } logger.info("BitTorrent client signing off."); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void announce(AnnounceRequestMessage.RequestEvent event, boolean inhibitEvents) throws AnnounceException { logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...", new Object[] { this.formatAnnounceEvent(event), this.torrent.getUploaded(), this.torrent.getDownloaded(), this.torrent.getLeft() }); try { ByteBuffer data = null; UDPTrackerMessage.UDPTrackerResponseMessage message = UDPTrackerMessage.UDPTrackerResponseMessage.parse(data); this.handleTrackerResponse(message, inhibitEvents); } catch (MessageValidationException mve) { logger.error("Tracker message violates expected protocol: {}!", mve.getMessage(), mve); } } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void announce(AnnounceRequestMessage.RequestEvent event, boolean inhibitEvents) throws AnnounceException { logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...", new Object[] { this.formatAnnounceEvent(event), this.torrent.getUploaded(), this.torrent.getDownloaded(), this.torrent.getLeft() }); try { State state = State.CONNECT_REQUEST; int tries = 0; while (tries <= UDP_MAX_TRIES) { if (this.lastConnectionTime != null && new Date().before(this.lastConnectionTime)) { state = State.ANNOUNCE_REQUEST; } tries++; } ByteBuffer data = null; UDPTrackerMessage.UDPTrackerResponseMessage message = UDPTrackerMessage.UDPTrackerResponseMessage.parse(data); this.handleTrackerResponse(message, inhibitEvents); } catch (MessageValidationException mve) { logger.error("Tracker message violates expected protocol: {}!", mve.getMessage(), mve); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> future = executorService.submit(myConnectionManager); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); int serverPort = ConnectionManager.PORT_RANGE_START; Socket socket = new Socket(); while (serverPort < ConnectionManager.PORT_RANGE_END) { try { socket.connect(new InetSocketAddress("127.0.0.1", serverPort)); if (socket.isConnected()) break; } catch (ConnectException ignored) {} serverPort++; } if (!socket.isConnected()) { fail("can not connect to server channel of connection manager"); } tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); executorService.shutdownNow(); boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS); assertTrue(executorShutdownCorrectly); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); } #location 18 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> future = executorService.submit(myConnectionManager); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); int serverPort = ConnectionManager.PORT_RANGE_START; Socket socket = null; while (serverPort < ConnectionManager.PORT_RANGE_END) { try { socket = new Socket("127.0.0.1", serverPort); if (socket.isConnected()) break; } catch (ConnectException ignored) {} serverPort++; } if (socket == null || !socket.isConnected()) { fail("can not connect to server channel of connection manager"); } tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); executorService.shutdownNow(); boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS); assertTrue(executorShutdownCorrectly); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void downloadUninterruptibly(final String dotTorrentPath, final String downloadDirPath, final long idleTimeoutSec, final int minSeedersCount, final AtomicBoolean isInterrupted, final long maxTimeForConnectMs, DownloadProgressListener listener) throws IOException, InterruptedException, NoSuchAlgorithmException { String hash = addTorrent(dotTorrentPath, downloadDirPath, false, true); final AnnounceableFileTorrent announceableTorrent = torrentsStorage.getAnnounceableTorrent(hash); if (announceableTorrent == null) throw new IOException("Unable to download torrent completely - announceable torrent is not found"); final SharedTorrent torrent = SharedTorrent.fromFile(new File(dotTorrentPath), new File(downloadDirPath), false, false, true, announceableTorrent); torrentsStorage.putIfAbsentActiveTorrent(torrent.getHexInfoHash(), torrent); long maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000; torrent.addDownloadProgressListener(listener); final long startDownloadAt = System.currentTimeMillis(); long currentLeft = torrent.getLeft(); while (torrent.getClientState() != ClientState.SEEDING && torrent.getClientState() != ClientState.ERROR && (torrent.getSeedersCount() >= minSeedersCount || torrent.getLastAnnounceTime() < 0) && (System.currentTimeMillis() <= maxIdleTime)) { if (Thread.currentThread().isInterrupted() || isInterrupted.get()) throw new InterruptedException("Download of " + torrent.getDirectoryName() + " was interrupted"); if (currentLeft > torrent.getLeft()) { currentLeft = torrent.getLeft(); maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000; } if (System.currentTimeMillis() - startDownloadAt > maxTimeForConnectMs) { if (getPeersForTorrent(torrent.getHexInfoHash()).size() < minSeedersCount) { break; } } Thread.sleep(100); } if (!(torrent.isFinished() && torrent.getClientState() == ClientState.SEEDING)) { removeAndDeleteTorrent(hash, torrent); final List<SharingPeer> peersForTorrent = getPeersForTorrent(hash); int connectedPeersForTorrent = peersForTorrent.size(); for (SharingPeer peer : peersForTorrent) { peer.unbind(true); } final String errorMsg; if (System.currentTimeMillis() > maxIdleTime) { int completedPieces = torrent.getCompletedPieces().cardinality(); int totalPieces = torrent.getPieceCount(); errorMsg = String.format("No pieces has been downloaded in %d seconds. Downloaded pieces %d/%d, connected peers %d" , idleTimeoutSec, completedPieces, totalPieces, connectedPeersForTorrent); } else if (connectedPeersForTorrent < minSeedersCount) { errorMsg = String.format("Not enough seeders. Required %d, found %d", minSeedersCount, connectedPeersForTorrent); } else if (torrent.getClientState() == ClientState.ERROR) { errorMsg = "Torrent state is ERROR"; } else { errorMsg = "Unknown error"; } throw new IOException("Unable to download torrent completely - " + errorMsg); } } #location 60 #vulnerability type RESOURCE_LEAK
#fixed code public void downloadUninterruptibly(final String dotTorrentPath, final String downloadDirPath, final long idleTimeoutSec, final int minSeedersCount, final AtomicBoolean isInterrupted, final long maxTimeForConnectMs, DownloadProgressListener listener) throws IOException, InterruptedException, NoSuchAlgorithmException { String hash = addTorrent(dotTorrentPath, downloadDirPath, false, true); final AnnounceableFileTorrent announceableTorrent = torrentsStorage.getAnnounceableTorrent(hash); if (announceableTorrent == null) throw new IOException("Unable to download torrent completely - announceable torrent is not found"); SharedTorrent torrent = new TorrentLoaderImpl(torrentsStorage).loadTorrent(announceableTorrent); long maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000; torrent.addDownloadProgressListener(listener); final long startDownloadAt = System.currentTimeMillis(); long currentLeft = torrent.getLeft(); while (torrent.getClientState() != ClientState.SEEDING && torrent.getClientState() != ClientState.ERROR && (torrent.getSeedersCount() >= minSeedersCount || torrent.getLastAnnounceTime() < 0) && (System.currentTimeMillis() <= maxIdleTime)) { if (Thread.currentThread().isInterrupted() || isInterrupted.get()) throw new InterruptedException("Download of " + torrent.getDirectoryName() + " was interrupted"); if (currentLeft > torrent.getLeft()) { currentLeft = torrent.getLeft(); maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000; } if (System.currentTimeMillis() - startDownloadAt > maxTimeForConnectMs) { if (getPeersForTorrent(torrent.getHexInfoHash()).size() < minSeedersCount) { break; } } Thread.sleep(100); } if (!(torrent.isFinished() && torrent.getClientState() == ClientState.SEEDING)) { removeAndDeleteTorrent(hash, torrent); final List<SharingPeer> peersForTorrent = getPeersForTorrent(hash); int connectedPeersForTorrent = peersForTorrent.size(); for (SharingPeer peer : peersForTorrent) { peer.unbind(true); } final String errorMsg; if (System.currentTimeMillis() > maxIdleTime) { int completedPieces = torrent.getCompletedPieces().cardinality(); int totalPieces = torrent.getPieceCount(); errorMsg = String.format("No pieces has been downloaded in %d seconds. Downloaded pieces %d/%d, connected peers %d" , idleTimeoutSec, completedPieces, totalPieces, connectedPeersForTorrent); } else if (connectedPeersForTorrent < minSeedersCount) { errorMsg = String.format("Not enough seeders. Required %d, found %d", minSeedersCount, connectedPeersForTorrent); } else if (torrent.getClientState() == ClientState.ERROR) { errorMsg = "Torrent state is ERROR"; } else { errorMsg = "Unknown error"; } throw new IOException("Unable to download torrent completely - " + errorMsg); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> future = executorService.submit(myConnectionManager); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); int serverPort = ConnectionManager.PORT_RANGE_START; Socket socket = new Socket(); while (serverPort < ConnectionManager.PORT_RANGE_END) { try { socket.connect(new InetSocketAddress("127.0.0.1", serverPort)); if (socket.isConnected()) break; } catch (ConnectException ignored) {} serverPort++; } if (!socket.isConnected()) { fail("can not connect to server channel of connection manager"); } tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); executorService.shutdownNow(); boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS); assertTrue(executorShutdownCorrectly); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); } #location 103 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> future = executorService.submit(myConnectionManager); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); int serverPort = ConnectionManager.PORT_RANGE_START; Socket socket = null; while (serverPort < ConnectionManager.PORT_RANGE_END) { try { socket = new Socket("127.0.0.1", serverPort); if (socket.isConnected()) break; } catch (ConnectException ignored) {} serverPort++; } if (socket == null || !socket.isConnected()) { fail("can not connect to server channel of connection manager"); } tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); executorService.shutdownNow(); boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS); assertTrue(executorShutdownCorrectly); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public long getUploaded() { return this.uploaded; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public long getUploaded() { return myTorrentStatistic.getUploadedBytes(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException { HttpURLConnection conn = null; InputStream in = null; try { conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); in = conn.getInputStream(); } catch (IOException ioe) { if (conn != null) { in = conn.getErrorStream(); } } // At this point if the input stream is null it means we have neither a // response body nor an error stream from the server. No point in going // any further. if (in == null) { throw new AnnounceException("No response or unreachable tracker!"); } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int len; while ((len=in.read(buf)) > 0){ baos.write(buf, 0, len); } // Parse and handle the response return HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray())); } catch (IOException ioe) { throw new AnnounceException("Error reading tracker response!", ioe); } catch (MessageValidationException mve) { throw new AnnounceException("Tracker message violates expected " + "protocol (" + mve.getMessage() + ")", mve); } finally { // Make sure we close everything down at the end to avoid resource // leaks. try { in.close(); } catch (IOException ioe) { logger.info("Problem ensuring error stream closed!"); logger.debug("Problem ensuring error stream closed!", ioe); } // This means trying to close the error stream as well. InputStream err = conn.getErrorStream(); if (err != null) { try { err.close(); } catch (IOException ioe) { logger.info("Problem ensuring error stream closed!"); logger.debug("Problem ensuring error stream closed!", ioe); } } } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException { HttpURLConnection conn = null; InputStream in = null; try { conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); in = conn.getInputStream(); } catch (IOException ioe) { if (conn != null) { in = conn.getErrorStream(); } } // At this point if the input stream is null it means we have neither a // response body nor an error stream from the server. No point in going // any further. if (in == null) { throw new AnnounceException("No response or unreachable tracker!"); } try { // Parse and handle the response return HTTPTrackerMessage.parse(in); } catch (IOException ioe) { throw new AnnounceException("Error reading tracker response!", ioe); } catch (MessageValidationException mve) { throw new AnnounceException("Tracker message violates expected " + "protocol (" + mve.getMessage() + ")", mve); } finally { // Make sure we close everything down at the end to avoid resource // leaks. try { in.close(); } catch (IOException ioe) { logger.info("Problem ensuring error stream closed!"); logger.debug("Problem ensuring error stream closed!", ioe); } // This means trying to close the error stream as well. InputStream err = conn.getErrorStream(); if (err != null) { try { err.close(); } catch (IOException ioe) { logger.info("Problem ensuring error stream closed!"); logger.debug("Problem ensuring error stream closed!", ioe); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static SharedTorrent fromFile(File source, File parent, boolean multiThreadHash, boolean seeder, boolean leecher, TorrentStatisticProvider torrentStatisticProvider) throws IOException, NoSuchAlgorithmException { FileInputStream fis = new FileInputStream(source); byte[] data = new byte[(int) source.length()]; fis.read(data); fis.close(); return new SharedTorrent(data, parent, multiThreadHash, seeder, leecher, DEFAULT_REQUEST_STRATEGY, torrentStatisticProvider); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code public static SharedTorrent fromFile(File source, File parent, boolean multiThreadHash, boolean seeder, boolean leecher, TorrentStatisticProvider torrentStatisticProvider) throws IOException, NoSuchAlgorithmException { byte[] data = FileUtils.readFileToByteArray(source); return new SharedTorrent(data, parent, multiThreadHash, seeder, leecher, DEFAULT_REQUEST_STRATEGY, torrentStatisticProvider); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean connect(SharingPeer peer) { Socket socket = new Socket(); InetSocketAddress address = new InetSocketAddress(peer.getIp(), peer.getPort()); logger.info("Connecting to " + peer + "..."); try { socket.connect(address, 3*1000); } catch (IOException ioe) { // Could not connect to peer, abort logger.warn("Could not connect to " + peer + ": " + ioe.getMessage()); return false; } try { this.sendHandshake(socket); Handshake hs = this.validateHandshake(socket, (peer.hasPeerId() ? peer.getPeerId().array() : null)); this.fireNewPeerConnection(socket, hs.getPeerId()); return true; } catch (ParseException pe) { logger.info("Invalid handshake from " + this.socketRepr(socket) + ": " + pe.getMessage()); try { socket.close(); } catch (IOException e) { } } catch (IOException ioe) { logger.info("An error occured while reading an incoming " + "handshake: " + ioe.getMessage()); try { if (!socket.isClosed()) { socket.close(); } } catch (IOException e) { // Ignore } } return false; } #location 30 #vulnerability type RESOURCE_LEAK
#fixed code public boolean connect(SharingPeer peer) { Socket socket = new Socket(); InetSocketAddress address = new InetSocketAddress(peer.getIp(), peer.getPort()); logger.info("Connecting to {}...", peer); try { socket.connect(address, 3*1000); } catch (IOException ioe) { // Could not connect to peer, abort logger.warn("Could not connect to {}: {}", peer, ioe.getMessage()); return false; } try { this.sendHandshake(socket); Handshake hs = this.validateHandshake(socket, (peer.hasPeerId() ? peer.getPeerId().array() : null)); this.fireNewPeerConnection(socket, hs.getPeerId()); return true; } catch (ParseException pe) { logger.info("Invalid handshake from {}: {}", this.socketRepr(socket), pe.getMessage()); try { socket.close(); } catch (IOException e) { } } catch (IOException ioe) { logger.info("An error occured while reading an incoming " + "handshake: {}", ioe.getMessage()); try { if (!socket.isClosed()) { socket.close(); } } catch (IOException e) { // Ignore } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public long getLeft() { return this.left; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public long getLeft() { return myTorrentStatistic.getLeftBytes(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Torrent load(File torrent, File parent, boolean seeder) throws IOException { FileInputStream fis = new FileInputStream(torrent); byte[] data = new byte[(int)torrent.length()]; fis.read(data); fis.close(); return new Torrent(data, parent, seeder); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public static Torrent load(File torrent, File parent, boolean seeder) throws IOException, NoSuchAlgorithmException { FileInputStream fis = null; try { fis = new FileInputStream(torrent); byte[] data = new byte[(int)torrent.length()]; fis.read(data); return new Torrent(data, parent, seeder); } finally { if (fis != null) { fis.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void open() throws IOException { this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void open() throws IOException { try { myLock.writeLock().lock(); this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } finally { myLock.writeLock().unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> future = executorService.submit(myConnectionManager); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); int serverPort = ConnectionManager.PORT_RANGE_START; Socket socket = null; while (serverPort < ConnectionManager.PORT_RANGE_END) { try { socket = new Socket("127.0.0.1", serverPort); if (socket.isConnected()) break; } catch (ConnectException ignored) {} serverPort++; } if (socket == null || !socket.isConnected()) { fail("can not connect to server channel of connection manager"); } tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); executorService.shutdownNow(); boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS); assertTrue(executorShutdownCorrectly); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); } #location 44 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; myConnectionManager.initAndRunWorker(); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); int serverPort = myConnectionManager.getBindAddress().getPort(); Socket socket = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); this.myConnectionManager.close(true); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void handleIOException(SharingPeer peer, IOException ioe) { logger.error("I/O error while exchanging data with {}, " + "closing connection with it!", peer, ioe.getMessage()); this.stop(); this.setState(ClientState.ERROR); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void handleIOException(SharingPeer peer, IOException ioe) { logger.warn("I/O error while exchanging data with {}, " + "closing connection with it!", peer, ioe.getMessage()); peer.unbind(true); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException { HttpURLConnection conn = null; InputStream in = null; try { conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); in = conn.getInputStream(); } catch (IOException ioe) { if (conn != null) { in = conn.getErrorStream(); } } // At this point if the input stream is null it means we have neither a // response body nor an error stream from the server. No point in going // any further. if (in == null) { throw new AnnounceException("No response or unreachable tracker!"); } try { // Parse and handle the response return HTTPTrackerMessage.parse(in); } catch (IOException ioe) { throw new AnnounceException("Error reading tracker response!", ioe); } catch (MessageValidationException mve) { throw new AnnounceException("Tracker message violates expected " + "protocol (" + mve.getMessage() + ")", mve); } finally { // Make sure we close everything down at the end to avoid resource // leaks. try { in.close(); } catch (IOException ioe) { logger.info("Problem ensuring error stream closed!"); logger.debug("Problem ensuring error stream closed!", ioe); } // This means trying to close the error stream as well. InputStream err = conn.getErrorStream(); if (err != null) { try { err.close(); } catch (IOException ioe) { logger.info("Problem ensuring error stream closed!"); logger.debug("Problem ensuring error stream closed!", ioe); } } } } #location 41 #vulnerability type RESOURCE_LEAK
#fixed code private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException { HttpURLConnection conn = null; InputStream in = null; try { conn = (HttpURLConnection)openConnectionCheckRedirects(url); in = conn.getInputStream(); } catch (IOException ioe) { if (conn != null) { in = conn.getErrorStream(); } } // At this point if the input stream is null it means we have neither a // response body nor an error stream from the server. No point in going // any further. if (in == null) { throw new AnnounceException("No response or unreachable tracker!"); } try { // Parse and handle the response return HTTPTrackerMessage.parse(in); } catch (IOException ioe) { throw new AnnounceException("Error reading tracker response!", ioe); } catch (MessageValidationException mve) { throw new AnnounceException("Tracker message violates expected " + "protocol (" + mve.getMessage() + ")", mve); } finally { // Make sure we close everything down at the end to avoid resource // leaks. try { in.close(); } catch (IOException ioe) { logger.info("Problem ensuring error stream closed!"); logger.debug("Problem ensuring error stream closed!", ioe); } // This means trying to close the error stream as well. InputStream err = conn.getErrorStream(); if (err != null) { try { err.close(); } catch (IOException ioe) { logger.info("Problem ensuring error stream closed!"); logger.debug("Problem ensuring error stream closed!", ioe); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public synchronized void handleMessage(PeerMessage msg) { // logger.trace("Received msg {} from {}", msg.getType(), this); switch (msg.getType()) { case KEEP_ALIVE: // Nothing to do, we're keeping the connection open anyways. break; case CHOKE: this.choked = true; this.firePeerChoked(); this.cancelPendingRequests(); break; case UNCHOKE: this.choked = false; logger.trace("Peer {} is now accepting requests.", this); this.firePeerReady(); break; case INTERESTED: this.interested = true; break; case NOT_INTERESTED: this.interested = false; break; case HAVE: // Record this peer has the given piece PeerMessage.HaveMessage have = (PeerMessage.HaveMessage) msg; Piece havePiece = this.torrent.getPiece(have.getPieceIndex()); synchronized (this.availablePiecesLock) { this.availablePieces.set(havePiece.getIndex()); logger.trace("Peer {} now has {} [{}/{}].", new Object[]{ this, havePiece, this.availablePieces.cardinality(), this.torrent.getPieceCount() }); } this.firePieceAvailabity(havePiece); break; case BITFIELD: // Augment the hasPiece bit field from this BITFIELD message PeerMessage.BitfieldMessage bitfield = (PeerMessage.BitfieldMessage) msg; synchronized (this.availablePiecesLock) { this.availablePieces.or(bitfield.getBitfield()); logger.trace("Recorded bitfield from {} with {} " + "pieces(s) [{}/{}].", new Object[]{ this, bitfield.getBitfield().cardinality(), this.availablePieces.cardinality(), this.torrent.getPieceCount() }); } this.fireBitfieldAvailabity(); break; case REQUEST: PeerMessage.RequestMessage request = (PeerMessage.RequestMessage) msg; logger.trace("Got request message for {} ({} {}@{}) from {}", new Object[]{ Arrays.toString(torrent.getFilenames().toArray()), request.getPiece(), request.getLength(), request.getOffset(), this }); Piece rp = this.torrent.getPiece(request.getPiece()); // If we are choking from this peer and it still sends us // requests, it is a violation of the BitTorrent protocol. // Similarly, if the peer requests a piece we don't have, it // is a violation of the BitTorrent protocol. In these // situation, terminate the connection. if (this.isChoking() || !rp.isValid()) { logger.warn("Peer {} violated protocol, terminating exchange.", this); this.unbind(true); break; } if (request.getLength() > PeerMessage.RequestMessage.MAX_REQUEST_SIZE) { logger.warn("Peer {} requested a block too big, " + "terminating exchange.", this); this.unbind(true); break; } // At this point we agree to send the requested piece block to // the remote peer, so let's queue a message with that block try { ByteBuffer block = rp.read(request.getOffset(), request.getLength()); this.send(PeerMessage.PieceMessage.craft(request.getPiece(), request.getOffset(), block)); this.upload.add(block.capacity()); if (request.getOffset() + request.getLength() == rp.size()) { this.firePieceSent(rp); } } catch (IOException ioe) { logger.error("error", ioe); this.fireIOException(new IOException( "Error while sending piece block request!", ioe)); } break; case PIECE: // Record the incoming piece block. // Should we keep track of the requested pieces and act when we // get a piece we didn't ask for, or should we just stay // greedy? PeerMessage.PieceMessage piece = (PeerMessage.PieceMessage) msg; Piece p = this.torrent.getPiece(piece.getPiece()); logger.trace("Got piece for {} ({} {}@{}) from {}", new Object[]{ Arrays.toString(torrent.getFilenames().toArray()), p.getIndex(), p.size(), piece.getOffset(), this }); // Remove the corresponding request from the request queue to // make room for next block requests. this.removeBlockRequest(piece); this.download.add(piece.getBlock().capacity()); try { synchronized (p) { if (p.isValid()) { this.requestedPiece = null; this.cancelPendingRequests(); this.firePeerReady(); logger.debug("Discarding block for already completed " + p); break; } //TODO add proper catch for IOException p.record(piece.getBlock(), piece.getOffset()); // If the block offset equals the piece size and the block // length is 0, it means the piece has been entirely // downloaded. In this case, we have nothing to save, but // we should validate the piece. if (requests==null || requests.size() == 0) { p.finish(); p.validate(torrent, p); this.firePieceCompleted(p); this.requestedPiece = null; this.firePeerReady(); } else { if (piece.getOffset() + piece.getBlock().capacity() == p.size()) { // final request reached for (PeerMessage.RequestMessage requestMessage : requests) { send(requestMessage); } } else { this.requestNextBlocks(); } } } } catch (IOException ioe) { logger.error(ioe.getMessage(), ioe); this.fireIOException(new IOException( "Error while storing received piece block!", ioe)); break; } break; case CANCEL: // No need to support break; } } #location 163 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public synchronized void handleMessage(PeerMessage msg) { // logger.trace("Received msg {} from {}", msg.getType(), this); switch (msg.getType()) { case KEEP_ALIVE: // Nothing to do, we're keeping the connection open anyways. break; case CHOKE: this.choked = true; this.firePeerChoked(); this.cancelPendingRequests(); break; case UNCHOKE: this.choked = false; logger.trace("Peer {} is now accepting requests.", this); this.firePeerReady(); break; case INTERESTED: this.interested = true; break; case NOT_INTERESTED: this.interested = false; break; case HAVE: // Record this peer has the given piece PeerMessage.HaveMessage have = (PeerMessage.HaveMessage) msg; Piece havePiece = this.torrent.getPiece(have.getPieceIndex()); synchronized (this.availablePiecesLock) { this.availablePieces.set(havePiece.getIndex()); logger.trace("Peer {} now has {} [{}/{}].", new Object[]{ this, havePiece, this.availablePieces.cardinality(), this.torrent.getPieceCount() }); } this.firePieceAvailabity(havePiece); break; case BITFIELD: // Augment the hasPiece bit field from this BITFIELD message PeerMessage.BitfieldMessage bitfield = (PeerMessage.BitfieldMessage) msg; synchronized (this.availablePiecesLock) { this.availablePieces.or(bitfield.getBitfield()); logger.trace("Recorded bitfield from {} with {} " + "pieces(s) [{}/{}].", new Object[]{ this, bitfield.getBitfield().cardinality(), this.availablePieces.cardinality(), this.torrent.getPieceCount() }); } this.fireBitfieldAvailabity(); break; case REQUEST: PeerMessage.RequestMessage request = (PeerMessage.RequestMessage) msg; logger.trace("Got request message for {} ({} {}@{}) from {}", new Object[]{ Arrays.toString(torrent.getFilenames().toArray()), request.getPiece(), request.getLength(), request.getOffset(), this }); Piece rp = this.torrent.getPiece(request.getPiece()); // If we are choking from this peer and it still sends us // requests, it is a violation of the BitTorrent protocol. // Similarly, if the peer requests a piece we don't have, it // is a violation of the BitTorrent protocol. In these // situation, terminate the connection. if (this.isChoking() || !rp.isValid()) { logger.warn("Peer {} violated protocol, terminating exchange.", this); this.unbind(true); break; } if (request.getLength() > PeerMessage.RequestMessage.MAX_REQUEST_SIZE) { logger.warn("Peer {} requested a block too big, " + "terminating exchange.", this); this.unbind(true); break; } // At this point we agree to send the requested piece block to // the remote peer, so let's queue a message with that block try { ByteBuffer block = rp.read(request.getOffset(), request.getLength()); this.send(PeerMessage.PieceMessage.craft(request.getPiece(), request.getOffset(), block)); this.upload.add(block.capacity()); if (request.getOffset() + request.getLength() == rp.size()) { this.firePieceSent(rp); } } catch (IOException ioe) { logger.error("error", ioe); this.fireIOException(new IOException( "Error while sending piece block request!", ioe)); } break; case PIECE: // Record the incoming piece block. // Should we keep track of the requested pieces and act when we // get a piece we didn't ask for, or should we just stay // greedy? PeerMessage.PieceMessage piece = (PeerMessage.PieceMessage) msg; Piece p = this.torrent.getPiece(piece.getPiece()); logger.trace("Got piece for {} ({} {}@{}) from {}", new Object[]{ Arrays.toString(torrent.getFilenames().toArray()), p.getIndex(), p.size(), piece.getOffset(), this }); // Remove the corresponding request from the request queue to // make room for next block requests. this.removeBlockRequest(piece.getPiece(), piece.getOffset()); this.download.add(piece.getBlock().capacity()); try { synchronized (p) { if (p.isValid()) { this.cancelPendingRequests(p); this.firePeerReady(); logger.debug("Discarding block for already completed " + p); break; } //TODO add proper catch for IOException p.record(piece.getBlock(), piece.getOffset()); // If the block offset equals the piece size and the block // length is 0, it means the piece has been entirely // downloaded. In this case, we have nothing to save, but // we should validate the piece. if (getRemainingRequestedPieces(p).size() == 0) { p.finish(); p.validate(torrent, p); this.firePieceCompleted(p); myRequestedPieces.remove(p); this.firePeerReady(); } else { if (piece.getOffset() + piece.getBlock().capacity() == p.size()) { // final request reached for (PeerMessage.RequestMessage requestMessage : getRemainingRequestedPieces(p)) { send(requestMessage); } } else { this.requestNextBlocksForPiece(p); } } } } catch (IOException ioe) { logger.error(ioe.getMessage(), ioe); this.fireIOException(new IOException( "Error while storing received piece block!", ioe)); break; } break; case CANCEL: // No need to support break; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized boolean validate(SharedTorrent torrent, Piece piece) throws IOException { if (this.seeder) { logger.trace("Skipping validation of {} (seeder mode).", this); this.valid = true; return true; } logger.trace("Validating {}...", this); this.valid = false; try { // TODO: remove cast to int when large ByteBuffer support is // implemented in Java. ByteBuffer buffer = this._read(0, this.length); byte[] data = new byte[(int)this.length]; buffer.get(data); final byte[] calculatedHash = Torrent.hash(data); this.valid = Arrays.equals(calculatedHash, this.hash); if (torrent != null && piece != null){ final File file; if (torrent.getParentFile().isDirectory()) { file = new File(torrent.getParentFile(), String.format("%d.txt", piece.getIndex())); } else { file = new File(torrent.getParentFile().getCanonicalFile().getParentFile(), String.format("%s.%d.txt", torrent.getName(), piece.getIndex())); } if (!valid) { logger.debug("Piece {} invalid. Expected hash {} when actual is {}", new Object[]{ piece.getIndex(), HexBin.encode(hash), HexBin.encode(calculatedHash)}); //saving data: FileOutputStream fOut = new FileOutputStream(file); fOut.write(data); fOut.close(); } else { if (file.exists()){ File correctFile; if (torrent.getParentFile().isDirectory()) { correctFile = new File(torrent.getParentFile(), String.format("%d.correct.txt", piece.getIndex())); } else { correctFile = new File(torrent.getParentFile().getCanonicalFile().getParentFile(), String.format("%s.%d.correct.txt", torrent.getName(), piece.getIndex())); } FileOutputStream fOut = new FileOutputStream(correctFile); fOut.write(data); fOut.close(); } } } } catch (NoSuchAlgorithmException nsae) { logger.error("{}", nsae); } /* if (valid){ System.out.println("Valid"); } else { System.out.println("Invalid"); } */ logger.trace("Validation of {} {}", this, this.isValid() ? "succeeded" : "failed"); return this.isValid(); } #location 48 #vulnerability type RESOURCE_LEAK
#fixed code public synchronized boolean validate(SharedTorrent torrent, Piece piece) throws IOException { if (this.seeder) { logger.trace("Skipping validation of {} (seeder mode).", this); this.valid = true; return true; } logger.trace("Validating {}...", this); this.valid = false; try { // TODO: remove cast to int when large ByteBuffer support is // implemented in Java. ByteBuffer buffer = this._read(0, this.length); byte[] data = new byte[(int)this.length]; buffer.get(data); final byte[] calculatedHash = Torrent.hash(data); this.valid = Arrays.equals(calculatedHash, this.hash); } catch (NoSuchAlgorithmException nsae) { logger.error("{}", nsae); } return this.isValid(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void start(final InetAddress... bindAddresses) throws IOException { start(bindAddresses, Constants.DEFAULT_ANNOUNCE_INTERVAL_SEC, null); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public void start(final InetAddress... bindAddresses) throws IOException { start(bindAddresses, Constants.DEFAULT_ANNOUNCE_INTERVAL_SEC, null, new SelectorFactoryImpl()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders + 7; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(baseFile, md5); final Client firstClient = clientsList.get(0); new WaitFor(10 * 1000) { @Override protected boolean condition() { return firstClient.getTorrentsStorage().activeTorrents().size() >= 1; } }; final SharedTorrent torrent = firstClient.getTorrents().iterator().next(); final File file = new File(torrent.getParentFile(), torrent.getFilenames().get(0)); final int oldByte; { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(0); oldByte = raf.read(); raf.seek(0); // replacing the byte if (oldByte != 35) { raf.write(35); } else { raf.write(45); } raf.close(); } final WaitFor waitFor = new WaitFor(60 * 1000) { @Override protected boolean condition() { for (Client client : clientsList) { final SharedTorrent next = client.getTorrents().iterator().next(); if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) { return false; } } return true; } }; if (!waitFor.isMyResult()) { fail("All seeders didn't get their files"); } Thread.sleep(10 * 1000); { byte[] piece = new byte[pieceSize]; FileInputStream fin = new FileInputStream(baseFile); fin.read(piece); fin.close(); RandomAccessFile raf; try { raf = new RandomAccessFile(file, "rw"); raf.seek(0); raf.write(oldByte); raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } } #location 71 #vulnerability type RESOURCE_LEAK
#fixed code public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders + 7; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(baseFile, md5); final Client firstClient = clientsList.get(0); new WaitFor(10 * 1000) { @Override protected boolean condition() { return firstClient.getTorrentsStorage().activeTorrents().size() >= 1; } }; final SharedTorrent torrent = firstClient.getTorrents().iterator().next(); final File file = new File(torrent.getParentFile(), TorrentUtils.getTorrentFileNames(torrent).get(0)); final int oldByte; { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(0); oldByte = raf.read(); raf.seek(0); // replacing the byte if (oldByte != 35) { raf.write(35); } else { raf.write(45); } raf.close(); } final WaitFor waitFor = new WaitFor(60 * 1000) { @Override protected boolean condition() { for (Client client : clientsList) { final SharedTorrent next = client.getTorrents().iterator().next(); if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) { return false; } } return true; } }; if (!waitFor.isMyResult()) { fail("All seeders didn't get their files"); } Thread.sleep(10 * 1000); { byte[] piece = new byte[pieceSize]; FileInputStream fin = new FileInputStream(baseFile); fin.read(piece); fin.close(); RandomAccessFile raf; try { raf = new RandomAccessFile(file, "rw"); raf.seek(0); raf.write(oldByte); raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void open() throws IOException { this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void open() throws IOException { try { myLock.writeLock().lock(); this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } finally { myLock.writeLock().unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public BitSet getCompletedPieces() { synchronized (this.completedPieces) { return (BitSet)this.completedPieces.clone(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public BitSet getCompletedPieces() { if (!this.isInitialized()) { throw new IllegalStateException("Torrent not yet initialized!"); } synchronized (this.completedPieces) { return (BitSet)this.completedPieces.clone(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { try { init(); Peer self = client.peersStorage.getSelf(); logger.info("BitTorrent client [{}] started and " + "listening at {}:{}...", new Object[]{ self.getShortHexPeerId(), self.getIp(), self.getPort() }); } catch (IOException e) { LoggerUtils.warnAndDebugDetails(logger, "error in initialization server channel", e); return; } while (!Thread.interrupted()) { int selected = -1; try { selected = selector.select();// TODO: 11/13/17 timeout } catch (IOException e) { LoggerUtils.warnAndDebugDetails(logger, "unable to select channel keys", e); } logger.trace("select keys from selector. Keys count is " + selected); if (selected < 0) { logger.info("selected count less that zero"); } if (selected == 0) { continue; } processSelectedKeys(); } try { close(); } catch (IOException e) { LoggerUtils.warnAndDebugDetails(logger, "unable to close connection receiver", e); } } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void run() { try { init(); Peer self = peersStorageFactory.getPeersStorage().getSelf(); logger.info("BitTorrent client [{}] started and " + "listening at {}:{}...", new Object[]{ self.getShortHexPeerId(), self.getIp(), self.getPort() }); } catch (IOException e) { LoggerUtils.warnAndDebugDetails(logger, "error in initialization server channel", e); return; } while (!Thread.interrupted()) { int selected = -1; try { selected = selector.select();// TODO: 11/13/17 timeout } catch (IOException e) { LoggerUtils.warnAndDebugDetails(logger, "unable to select channel keys", e); } logger.trace("select keys from selector. Keys count is " + selected); if (selected < 0) { logger.info("selected count less that zero"); } if (selected == 0) { continue; } processSelectedKeys(); } try { close(); } catch (IOException e) { LoggerUtils.warnAndDebugDetails(logger, "unable to close connection receiver", e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void validatePieceAsync(final SharedTorrent torrent, final Piece piece, String torrentHash, SharingPeer peer) { try { synchronized (piece) { if (piece.isValid()) return; piece.validate(torrent, piece); if (piece.isValid()) { piece.finish(); // Send a HAVE message to all connected peers, which don't have the piece PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex()); for (SharingPeer remote : getConnectedPeers()) { if (remote.getTorrent().getHexInfoHash().equals(torrentHash) && !remote.getAvailablePieces().get(piece.getIndex())) remote.send(have); } final boolean isTorrentComplete; synchronized (torrent) { torrent.removeValidationFuture(piece); torrent.notifyPieceDownloaded(piece, peer); boolean isCurrentPeerSeeder = peer.getAvailablePieces().cardinality() == torrent.getPieceCount(); //if it's seeder we will send not interested message when we download full file if (!isCurrentPeerSeeder) { if (torrent.isAllPiecesOfPeerCompletedAndValidated(peer)) { peer.notInteresting(); } } isTorrentComplete = torrent.isComplete(); if (isTorrentComplete) { logger.debug("Download of {} complete.", torrent.getDirectoryName()); torrent.finish(); } } if (isTorrentComplete) { LoadedTorrent announceableTorrent = torrentsStorage.getLoadedTorrent(torrentHash); if (announceableTorrent == null) return; AnnounceableInformation announceableInformation = announceableTorrent.createAnnounceableInformation(); try { announce.getCurrentTrackerClient(announceableInformation) .announceAllInterfaces(COMPLETED, true, announceableInformation); } catch (AnnounceException e) { logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce()); } for (SharingPeer remote : getPeersForTorrent(torrentHash)) { remote.notInteresting(); } } } else { torrent.markUncompleted(piece); logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer); peer.getPoorlyAvailablePieces().set(piece.getIndex()); } } } catch (Throwable e) { torrent.markUncompleted(piece); logger.warn("unhandled exception in piece {} validation task", e); } } #location 51 #vulnerability type NULL_DEREFERENCE
#fixed code private void validatePieceAsync(final SharedTorrent torrent, final Piece piece, String torrentHash, SharingPeer peer) { try { synchronized (piece) { if (piece.isValid()) return; piece.validate(torrent, piece); if (piece.isValid()) { piece.finish(); // Send a HAVE message to all connected peers, which don't have the piece PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex()); for (SharingPeer remote : getConnectedPeers()) { if (remote.getTorrent().getHexInfoHash().equals(torrentHash) && !remote.getAvailablePieces().get(piece.getIndex())) remote.send(have); } final boolean isTorrentComplete; synchronized (torrent) { torrent.removeValidationFuture(piece); torrent.notifyPieceDownloaded(piece, peer); boolean isCurrentPeerSeeder = peer.getAvailablePieces().cardinality() == torrent.getPieceCount(); //if it's seeder we will send not interested message when we download full file if (!isCurrentPeerSeeder) { if (torrent.isAllPiecesOfPeerCompletedAndValidated(peer)) { peer.notInteresting(); } } isTorrentComplete = torrent.isComplete(); if (isTorrentComplete) { logger.debug("Download of {} complete.", torrent.getDirectoryName()); torrent.finish(); } } if (isTorrentComplete) { LoadedTorrent announceableTorrent = torrentsStorage.getLoadedTorrent(torrentHash); if (announceableTorrent == null) return; AnnounceableInformation announceableInformation = announceableTorrent.createAnnounceableInformation(); try { announce.getCurrentTrackerClient(announceableInformation) .announceAllInterfaces(COMPLETED, true, announceableInformation); } catch (AnnounceException e) { logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce()); } for (SharingPeer remote : getPeersForTorrent(torrentHash)) { remote.notInteresting(); } } } else { torrent.markUncompleted(piece); logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer); peer.getPoorlyAvailablePieces().set(piece.getIndex()); } } } catch (Throwable e) { torrent.markUncompleted(piece); logger.warn("unhandled exception in piece {} validation task", e); } torrent.handlePeerReady(peer); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { logger.info("Starting announce loop..."); while (!this.stop && !Thread.currentThread().isInterrupted()) { logger.debug("Starting announce for {} torrents", torrents.size()); for (SharedTorrent torrent : this.torrents) { if (this.stop || Thread.currentThread().isInterrupted()){ break; } try { TrackerClient trackerClient = this.getCurrentTrackerClient(torrent); if (trackerClient != null) { trackerClient.announceAllInterfaces(AnnounceRequestMessage.RequestEvent.NONE, torrent.isFinished(), torrent); } else { logger.warn("Tracker client for {} is null. Torrent is not announced on tracker", torrent.getName()); } } catch (Exception e) { logger.info(e.getMessage()); logger.debug(e.getMessage(), e); } } try { Thread.sleep(this.myAnnounceInterval * 1000); } catch (InterruptedException ie) { break; } } logger.info("Exited announce loop."); if (!this.forceStop) { // Send the final 'stopped' event to the tracker after a little // while. try { Thread.sleep(500); } catch (InterruptedException ie) { // Ignore return; } try { for (SharedTorrent torrent : this.torrents) { this.getCurrentTrackerClient(torrent).announceAllInterfaces(AnnounceRequestMessage.RequestEvent.STOPPED, true, torrent); } } catch (AnnounceException e) { logger.info("Can't announce stop: " + e.getMessage()); logger.debug("Can't announce stop", e); // don't try to announce all. Stop after first error, assuming tracker is already unavailable } } } #location 46 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void run() { logger.info("Starting announce loop..."); while (!this.stop && !Thread.currentThread().isInterrupted()) { logger.debug("Starting announce for {} torrents", torrents.size()); for (SharedTorrent torrent : this.torrents) { if (this.stop || Thread.currentThread().isInterrupted()){ break; } try { TrackerClient trackerClient = this.getCurrentTrackerClient(torrent); if (trackerClient != null) { trackerClient.announceAllInterfaces(AnnounceRequestMessage.RequestEvent.NONE, torrent.isFinished(), torrent); } else { logger.warn("Tracker client for {} is null. Torrent is not announced on tracker", torrent.getName()); } } catch (Exception e) { logger.info(e.getMessage()); logger.debug(e.getMessage(), e); } } try { Thread.sleep(this.myAnnounceInterval * 1000); } catch (InterruptedException ie) { break; } } logger.info("Exited announce loop."); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void announce(AnnounceRequestMessage.RequestEvent event, boolean inhibitEvents, TorrentInfo torrentInfo) throws AnnounceException { logAnnounceRequest(event, torrentInfo); URL target = null; try { HTTPAnnounceRequestMessage request = this.buildAnnounceRequest(event, torrentInfo); target = request.buildAnnounceURL(this.tracker.toURL()); } catch (MalformedURLException mue) { throw new AnnounceException("Invalid announce URL (" + mue.getMessage() + ")", mue); } catch (MessageValidationException mve) { throw new AnnounceException("Announce request creation violated " + "expected protocol (" + mve.getMessage() + ")", mve); } catch (IOException ioe) { throw new AnnounceException("Error building announce request (" + ioe.getMessage() + ")", ioe); } HttpURLConnection conn = null; InputStream in = null; try { conn = (HttpURLConnection)target.openConnection(); in = conn.getInputStream(); } catch (IOException ioe) { if (conn != null) { in = conn.getErrorStream(); } } // At this point if the input stream is null it means we have neither a // response body nor an error stream from the server. No point in going // any further. if (in == null) { throw new AnnounceException("No response or unreachable tracker!"); } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(in); // Parse and handle the response HTTPTrackerMessage message = HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray())); this.handleTrackerAnnounceResponse(message, inhibitEvents, torrentInfo.getHexInfoHash()); } catch (IOException ioe) { throw new AnnounceException("Error reading tracker response!", ioe); } catch (MessageValidationException mve) { throw new AnnounceException("Tracker message violates expected " + "protocol (" + mve.getMessage() + ")", mve); } finally { // Make sure we close everything down at the end to avoid resource // leaks. try { in.close(); } catch (IOException ioe) { logger.warn("Problem ensuring error stream closed!", ioe); } // This means trying to close the error stream as well. InputStream err = conn.getErrorStream(); if (err != null) { try { err.close(); } catch (IOException ioe) { logger.warn("Problem ensuring error stream closed!", ioe); } } } } #location 61 #vulnerability type RESOURCE_LEAK
#fixed code public void announce(AnnounceRequestMessage.RequestEvent event, boolean inhibitEvents, TorrentInfo torrentInfo) throws AnnounceException { logAnnounceRequest(event, torrentInfo); URL target = null; try { HTTPAnnounceRequestMessage request = this.buildAnnounceRequest(event, torrentInfo); target = request.buildAnnounceURL(this.tracker.toURL()); } catch (MalformedURLException mue) { throw new AnnounceException("Invalid announce URL (" + mue.getMessage() + ")", mue); } catch (MessageValidationException mve) { throw new AnnounceException("Announce request creation violated " + "expected protocol (" + mve.getMessage() + ")", mve); } catch (IOException ioe) { throw new AnnounceException("Error building announce request (" + ioe.getMessage() + ")", ioe); } HttpURLConnection conn = null; InputStream in = null; try { conn = (HttpURLConnection)target.openConnection(); in = conn.getInputStream(); } catch (IOException ioe) { if (conn != null) { in = conn.getErrorStream(); } } // At this point if the input stream is null it means we have neither a // response body nor an error stream from the server. No point in going // any further. if (in == null) { throw new AnnounceException("No response or unreachable tracker!"); } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int len; while ((len=in.read(buf)) > 0){ baos.write(buf, 0, len); } // Parse and handle the response HTTPTrackerMessage message = HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray())); this.handleTrackerAnnounceResponse(message, inhibitEvents, torrentInfo.getHexInfoHash()); } catch (IOException ioe) { throw new AnnounceException("Error reading tracker response!", ioe); } catch (MessageValidationException mve) { throw new AnnounceException("Tracker message violates expected " + "protocol (" + mve.getMessage() + ")", mve); } finally { // Make sure we close everything down at the end to avoid resource // leaks. try { in.close(); } catch (IOException ioe) { logger.warn("Problem ensuring error stream closed!", ioe); } // This means trying to close the error stream as well. InputStream err = conn.getErrorStream(); if (err != null) { try { err.close(); } catch (IOException ioe) { logger.warn("Problem ensuring error stream closed!", ioe); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders + 7; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(baseFile, md5); final Client firstClient = clientsList.get(0); new WaitFor(10 * 1000) { @Override protected boolean condition() { return firstClient.getTorrentsStorage().activeTorrents().size() >= 1; } }; final SharedTorrent torrent = firstClient.getTorrents().iterator().next(); final File file = new File(torrent.getParentFile(), torrent.getFilenames().get(0)); final int oldByte; { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(0); oldByte = raf.read(); raf.seek(0); // replacing the byte if (oldByte != 35) { raf.write(35); } else { raf.write(45); } raf.close(); } final WaitFor waitFor = new WaitFor(60 * 1000) { @Override protected boolean condition() { for (Client client : clientsList) { final SharedTorrent next = client.getTorrents().iterator().next(); if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) { return false; } } return true; } }; if (!waitFor.isMyResult()) { fail("All seeders didn't get their files"); } Thread.sleep(10 * 1000); { byte[] piece = new byte[pieceSize]; FileInputStream fin = new FileInputStream(baseFile); fin.read(piece); fin.close(); RandomAccessFile raf; try { raf = new RandomAccessFile(file, "rw"); raf.seek(0); raf.write(oldByte); raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } } #location 46 #vulnerability type RESOURCE_LEAK
#fixed code public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders + 7; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(baseFile, md5); final Client firstClient = clientsList.get(0); new WaitFor(10 * 1000) { @Override protected boolean condition() { return firstClient.getTorrentsStorage().activeTorrents().size() >= 1; } }; final SharedTorrent torrent = firstClient.getTorrents().iterator().next(); final File file = new File(torrent.getParentFile(), TorrentUtils.getTorrentFileNames(torrent).get(0)); final int oldByte; { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(0); oldByte = raf.read(); raf.seek(0); // replacing the byte if (oldByte != 35) { raf.write(35); } else { raf.write(45); } raf.close(); } final WaitFor waitFor = new WaitFor(60 * 1000) { @Override protected boolean condition() { for (Client client : clientsList) { final SharedTorrent next = client.getTorrents().iterator().next(); if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) { return false; } } return true; } }; if (!waitFor.isMyResult()) { fail("All seeders didn't get their files"); } Thread.sleep(10 * 1000); { byte[] piece = new byte[pieceSize]; FileInputStream fin = new FileInputStream(baseFile); fin.read(piece); fin.close(); RandomAccessFile raf; try { raf = new RandomAccessFile(file, "rw"); raf.seek(0); raf.write(oldByte); raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public MetadataBuilder addFile(@NotNull File source) { sources.add(new Source(source)); return this; } #location 2 #vulnerability type RESOURCE_LEAK
#fixed code public MetadataBuilder addFile(@NotNull File source) { return addFile(source, source.getName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void open() throws IOException { this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } #location 16 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void open() throws IOException { try { myLock.writeLock().lock(); this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } finally { myLock.writeLock().unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> future = executorService.submit(myConnectionManager); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); Socket socket = new Socket("127.0.0.1", ConnectionManager.PORT_RANGE_START); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", ConnectionManager.PORT_RANGE_START); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); executorService.shutdownNow(); boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS); assertTrue(executorShutdownCorrectly); } #location 66 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> future = executorService.submit(myConnectionManager); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); int serverPort = ConnectionManager.PORT_RANGE_START; Socket socket = new Socket(); while (serverPort < ConnectionManager.PORT_RANGE_END) { try { socket.connect(new InetSocketAddress("127.0.0.1", serverPort)); } catch (ConnectException ignored) {} serverPort++; } if (!socket.isConnected()) { fail("can not connect to server channel of connection manager"); } tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); executorService.shutdownNow(); boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS); assertTrue(executorShutdownCorrectly); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void handlePieceCompleted(final SharingPeer peer, Piece piece) throws IOException { final SharedTorrent torrent = peer.getTorrent(); synchronized (torrent) { if (piece.isValid()) { // Make sure the piece is marked as completed in the torrent // Note: this is required because the order the // PeerActivityListeners are called is not defined, and we // might be called before the torrent's piece completion // handler is. torrent.markCompleted(piece); logger.debug("Completed download of {} from {}, now has {}/{} pieces.", new Object[]{ piece, peer, torrent.getCompletedPieces().cardinality(), torrent.getPieceCount() }); // Send a HAVE message to all connected peers PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex()); final String torrentHash = torrent.getHexInfoHash(); for (SharingPeer remote : getConnectedPeers()) { if (remote.getTorrent().getHexInfoHash().equals(torrentHash)) remote.send(have); } BitSet completed = new BitSet(); completed.or(torrent.getCompletedPieces()); completed.and(peer.getAvailablePieces()); if (completed.equals(peer.getAvailablePieces())) { // send not interested when have no interested pieces; peer.send(PeerMessage.NotInterestedMessage.craft()); } } else { logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer); peer.getPoorlyAvailablePieces().set(piece.getIndex()); } if (torrent.isComplete()) { //close connection with all peers for this torrent logger.info("Download of {} complete.", torrent.getName()); torrent.finish(); try { this.announce.getCurrentTrackerClient(torrent) .announceAllInterfaces(TrackerMessage.AnnounceRequestMessage.RequestEvent.COMPLETED, true, torrent); } catch (AnnounceException e) { logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce()); } } } } #location 50 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void handlePieceCompleted(final SharingPeer peer, Piece piece) throws IOException { final SharedTorrent torrent = peer.getTorrent(); final String torrentHash; synchronized (torrent) { torrentHash = torrent.getHexInfoHash(); if (piece.isValid()) { // Make sure the piece is marked as completed in the torrent // Note: this is required because the order the // PeerActivityListeners are called is not defined, and we // might be called before the torrent's piece completion // handler is. torrent.markCompleted(piece); logger.debug("Completed download of {} from {}, now has {}/{} pieces.", new Object[]{ piece, peer, torrent.getCompletedPieces().cardinality(), torrent.getPieceCount() }); BitSet completed = new BitSet(); completed.or(torrent.getCompletedPieces()); completed.and(peer.getAvailablePieces()); if (completed.equals(peer.getAvailablePieces())) { // send not interested when have no interested pieces; peer.send(PeerMessage.NotInterestedMessage.craft()); } } else { logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer); peer.getPoorlyAvailablePieces().set(piece.getIndex()); } if (torrent.isComplete()) { //close connection with all peers for this torrent logger.info("Download of {} complete.", torrent.getName()); torrent.finish(); try { this.announce.getCurrentTrackerClient(torrent) .announceAllInterfaces(TrackerMessage.AnnounceRequestMessage.RequestEvent.COMPLETED, true, torrent); } catch (AnnounceException e) { logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce()); } } } // Send a HAVE message to all connected peers PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex()); for (SharingPeer remote : getConnectedPeers()) { if (remote.getTorrent().getHexInfoHash().equals(torrentHash)) remote.send(have); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void handlePieceCompleted(final SharingPeer peer, Piece piece) throws IOException { final SharedTorrent torrent = peer.getTorrent(); final String torrentHash = torrent.getHexInfoHash(); if (piece.isValid()) { // Send a HAVE message to all connected peers PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex()); for (SharingPeer remote : getConnectedPeers()) { if (remote.getTorrent().getHexInfoHash().equals(torrentHash)) remote.send(have); } } synchronized (torrent) { if (piece.isValid()) { // Make sure the piece is marked as completed in the torrent // Note: this is required because the order the // PeerActivityListeners are called is not defined, and we // might be called before the torrent's piece completion // handler is. torrent.markCompleted(piece); logger.debug("Completed download of {} from {}, now has {}/{} pieces.", new Object[]{ piece, peer, torrent.getCompletedPieces().cardinality(), torrent.getPieceCount() }); BitSet completed = new BitSet(); completed.or(torrent.getCompletedPieces()); completed.and(peer.getAvailablePieces()); if (completed.equals(peer.getAvailablePieces())) { // send not interested when have no interested pieces; peer.send(PeerMessage.NotInterestedMessage.craft()); } } else { logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer); peer.getPoorlyAvailablePieces().set(piece.getIndex()); } if (torrent.isComplete()) { //close connection with all peers for this torrent logger.debug("Download of {} complete.", torrent.getName()); torrent.finish(); try { this.announce.getCurrentTrackerClient(torrent) .announceAllInterfaces(COMPLETED, true, torrent); } catch (AnnounceException e) { logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce()); } } } } #location 51 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void handlePieceCompleted(final SharingPeer peer, Piece piece) throws IOException { final SharedTorrent torrent = peer.getTorrent(); final String torrentHash = torrent.getHexInfoHash(); if (piece.isValid()) { // Send a HAVE message to all connected peers PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex()); for (SharingPeer remote : getConnectedPeers()) { if (remote.getTorrent().getHexInfoHash().equals(torrentHash)) remote.send(have); } } synchronized (torrent) { if (piece.isValid()) { // Make sure the piece is marked as completed in the torrent // Note: this is required because the order the // PeerActivityListeners are called is not defined, and we // might be called before the torrent's piece completion // handler is. torrent.markCompleted(piece); logger.debug("Completed download of {} from {}, now has {}/{} pieces.", new Object[]{ piece, peer, torrent.getCompletedPieces().cardinality(), torrent.getPieceCount() }); BitSet completed = new BitSet(); completed.or(torrent.getCompletedPieces()); completed.and(peer.getAvailablePieces()); if (completed.equals(peer.getAvailablePieces())) { // send not interested when have no interested pieces; peer.send(PeerMessage.NotInterestedMessage.craft()); } } else { logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer); peer.getPoorlyAvailablePieces().set(piece.getIndex()); } if (torrent.isComplete()) { //close connection with all peers for this torrent logger.debug("Download of {} complete.", torrent.getDirectoryName()); torrent.finish(); AnnounceableTorrent announceableTorrent = torrentsStorage.getAnnounceableTorrent(torrentHash); if (announceableTorrent == null) return; try { this.announce.getCurrentTrackerClient(announceableTorrent) .announceAllInterfaces(COMPLETED, true, announceableTorrent); } catch (AnnounceException e) { logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce()); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<TorrentFile> parseFiles(Map<String, BEValue> infoTable, boolean torrentContainsManyFiles, String name) throws InvalidBEncodingException { if (!torrentContainsManyFiles) { final BEValue md5Sum = infoTable.get(MD5_SUM); return Collections.singletonList(new TorrentFile( Collections.singletonList(name), getRequiredValueOrThrowException(infoTable, FILE_LENGTH).getLong(), md5Sum == null ? null : md5Sum.getString() )); } List<TorrentFile> result = new ArrayList<TorrentFile>(); for (BEValue file : infoTable.get(FILES).getList()) { Map<String, BEValue> fileInfo = file.getMap(); List<String> path = new ArrayList<String>(); for (BEValue pathElement : fileInfo.get(FILE_PATH).getList()) { path.add(pathElement.getString()); } final BEValue md5Sum = infoTable.get(MD5_SUM); result.add(new TorrentFile( path, fileInfo.get(FILE_LENGTH).getLong(), md5Sum == null ? null : md5Sum.getString())); } return result; } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code private List<TorrentFile> parseFiles(Map<String, BEValue> infoTable, boolean torrentContainsManyFiles, String name) throws InvalidBEncodingException { if (!torrentContainsManyFiles) { final BEValue md5Sum = infoTable.get(MD5_SUM); return Collections.singletonList(new TorrentFile( Collections.singletonList(name), getRequiredValueOrThrowException(infoTable, FILE_LENGTH).getLong(), md5Sum == null ? null : md5Sum.getString() )); } List<TorrentFile> result = new ArrayList<TorrentFile>(); for (BEValue file : infoTable.get(FILES).getList()) { Map<String, BEValue> fileInfo = file.getMap(); List<String> path = new ArrayList<String>(); BEValue filePathList = fileInfo.get(FILE_PATH_UTF8); if (filePathList == null) { filePathList = fileInfo.get(FILE_PATH); } for (BEValue pathElement : filePathList.getList()) { path.add(pathElement.getString()); } final BEValue md5Sum = infoTable.get(MD5_SUM); result.add(new TorrentFile( path, fileInfo.get(FILE_LENGTH).getLong(), md5Sum == null ? null : md5Sum.getString())); } return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void open() throws IOException { this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } #location 25 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void open() throws IOException { try { myLock.writeLock().lock(); this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } finally { myLock.writeLock().unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void save(File output) throws IOException { FileOutputStream fos = new FileOutputStream(output); fos.write(this.getEncoded()); fos.close(); logger.info("Wrote torrent file {}.", output.getAbsolutePath()); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code public void save(File output) throws IOException { FileOutputStream fos = null; try { fos = new FileOutputStream(output); fos.write(this.getEncoded()); logger.info("Wrote torrent file {}.", output.getAbsolutePath()); } finally { if (fos != null) { fos.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> future = executorService.submit(myConnectionManager); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); int serverPort = ConnectionManager.PORT_RANGE_START; Socket socket = new Socket(); while (serverPort < ConnectionManager.PORT_RANGE_END) { try { socket.connect(new InetSocketAddress("127.0.0.1", serverPort)); if (socket.isConnected()) break; } catch (ConnectException ignored) {} serverPort++; } if (!socket.isConnected()) { fail("can not connect to server channel of connection manager"); } tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); executorService.shutdownNow(); boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS); assertTrue(executorShutdownCorrectly); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); } #location 103 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final AtomicInteger lastReadBytesCount = new AtomicInteger(); final ByteBuffer byteBuffer = ByteBuffer.allocate(10); final Semaphore semaphore = new Semaphore(0); this.channelListener = new ChannelListener() { @Override public void onNewDataAvailable(SocketChannel socketChannel) throws IOException { readCount.incrementAndGet(); lastReadBytesCount.set(socketChannel.read(byteBuffer)); if (lastReadBytesCount.get() == -1) { socketChannel.close(); } semaphore.release(); } @Override public void onConnectionAccept(SocketChannel socketChannel) throws IOException { acceptCount.incrementAndGet(); semaphore.release(); } @Override public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) { connectCount.incrementAndGet(); semaphore.release(); } }; ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> future = executorService.submit(myConnectionManager); assertEquals(acceptCount.get(), 0); assertEquals(readCount.get(), 0); int serverPort = ConnectionManager.PORT_RANGE_START; Socket socket = null; while (serverPort < ConnectionManager.PORT_RANGE_END) { try { socket = new Socket("127.0.0.1", serverPort); if (socket.isConnected()) break; } catch (ConnectException ignored) {} serverPort++; } if (socket == null || !socket.isConnected()) { fail("can not connect to server channel of connection manager"); } tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socket.isConnected()); assertEquals(acceptCount.get(), 1); assertEquals(readCount.get(), 0); Socket socketSecond = new Socket("127.0.0.1", serverPort); tryAcquireOrFail(semaphore);//wait until connection is accepted assertTrue(socketSecond.isConnected()); assertEquals(acceptCount.get(), 2); assertEquals(readCount.get(), 0); socketSecond.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 1); assertEquals(acceptCount.get(), 2); assertEquals(lastReadBytesCount.get(), -1); byteBuffer.rewind(); assertEquals(byteBuffer.get(), 0); byteBuffer.rewind(); String writeStr = "abc"; OutputStream outputStream = socket.getOutputStream(); outputStream.write(writeStr.getBytes()); tryAcquireOrFail(semaphore);//wait until read bytes assertEquals(readCount.get(), 2); assertEquals(lastReadBytesCount.get(), 3); byte[] expected = new byte[byteBuffer.capacity()]; System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length()); assertEquals(byteBuffer.array(), expected); outputStream.close(); socket.close(); tryAcquireOrFail(semaphore);//wait read that connection is closed assertEquals(readCount.get(), 3); int otherPeerPort = 7575; ServerSocket ss = new ServerSocket(otherPeerPort); assertEquals(connectCount.get(), 0); myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() { @Override public byte[] getInfoHash() { return new byte[0]; } @Override public String getHexInfoHash() { return null; } }), 1, TimeUnit.SECONDS); ss.accept(); tryAcquireOrFail(semaphore); assertEquals(connectCount.get(), 1); executorService.shutdownNow(); boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS); assertTrue(executorShutdownCorrectly); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders + 7; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(baseFile, md5); final Client firstClient = clientsList.get(0); new WaitFor(10 * 1000) { @Override protected boolean condition() { return firstClient.getTorrentsStorage().activeTorrents().size() >= 1; } }; final SharedTorrent torrent = firstClient.getTorrents().iterator().next(); final File file = new File(torrent.getParentFile(), torrent.getFilenames().get(0)); final int oldByte; { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(0); oldByte = raf.read(); raf.seek(0); // replacing the byte if (oldByte != 35) { raf.write(35); } else { raf.write(45); } raf.close(); } final WaitFor waitFor = new WaitFor(60 * 1000) { @Override protected boolean condition() { for (Client client : clientsList) { final SharedTorrent next = client.getTorrents().iterator().next(); if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) { return false; } } return true; } }; if (!waitFor.isMyResult()) { fail("All seeders didn't get their files"); } Thread.sleep(10 * 1000); { byte[] piece = new byte[pieceSize]; FileInputStream fin = new FileInputStream(baseFile); fin.read(piece); fin.close(); RandomAccessFile raf; try { raf = new RandomAccessFile(file, "rw"); raf.seek(0); raf.write(oldByte); raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } } #location 46 #vulnerability type RESOURCE_LEAK
#fixed code public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders + 7; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(baseFile, md5); final Client firstClient = clientsList.get(0); new WaitFor(10 * 1000) { @Override protected boolean condition() { return firstClient.getTorrentsStorage().activeTorrents().size() >= 1; } }; final SharedTorrent torrent = firstClient.getTorrents().iterator().next(); final File file = new File(torrent.getParentFile(), TorrentUtils.getTorrentFileNames(torrent).get(0)); final int oldByte; { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(0); oldByte = raf.read(); raf.seek(0); // replacing the byte if (oldByte != 35) { raf.write(35); } else { raf.write(45); } raf.close(); } final WaitFor waitFor = new WaitFor(60 * 1000) { @Override protected boolean condition() { for (Client client : clientsList) { final SharedTorrent next = client.getTorrents().iterator().next(); if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) { return false; } } return true; } }; if (!waitFor.isMyResult()) { fail("All seeders didn't get their files"); } Thread.sleep(10 * 1000); { byte[] piece = new byte[pieceSize]; FileInputStream fin = new FileInputStream(baseFile); fin.read(piece); fin.close(); RandomAccessFile raf; try { raf = new RandomAccessFile(file, "rw"); raf.seek(0); raf.write(oldByte); raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void cleanUp() { for (PeerMessage.RequestMessage request : myRequests) { if (System.currentTimeMillis() - request.getSendTime() > MAX_REQUEST_TIMEOUT){ send(request); request.renew(); } } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void cleanUp() { // temporary ignore until I figure out how to handle this in more robust way. /* for (PeerMessage.RequestMessage request : myRequests) { if (System.currentTimeMillis() - request.getSendTime() > MAX_REQUEST_TIMEOUT){ send(request); request.renew(); } } */ }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException { HttpURLConnection conn = null; InputStream in = null; try { conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); in = conn.getInputStream(); } catch (IOException ioe) { if (conn != null) { in = conn.getErrorStream(); } } // At this point if the input stream is null it means we have neither a // response body nor an error stream from the server. No point in going // any further. if (in == null) { throw new AnnounceException("No response or unreachable tracker!"); } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int len; while ((len=in.read(buf)) > 0){ baos.write(buf, 0, len); } // Parse and handle the response return HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray())); } catch (IOException ioe) { throw new AnnounceException("Error reading tracker response!", ioe); } catch (MessageValidationException mve) { throw new AnnounceException("Tracker message violates expected " + "protocol (" + mve.getMessage() + ")", mve); } finally { // Make sure we close everything down at the end to avoid resource // leaks. try { in.close(); } catch (IOException ioe) { logger.info("Problem ensuring error stream closed!"); logger.debug("Problem ensuring error stream closed!", ioe); } // This means trying to close the error stream as well. InputStream err = conn.getErrorStream(); if (err != null) { try { err.close(); } catch (IOException ioe) { logger.info("Problem ensuring error stream closed!"); logger.debug("Problem ensuring error stream closed!", ioe); } } } } #location 32 #vulnerability type RESOURCE_LEAK
#fixed code private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException { HttpURLConnection conn = null; InputStream in = null; try { conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); in = conn.getInputStream(); } catch (IOException ioe) { if (conn != null) { in = conn.getErrorStream(); } } // At this point if the input stream is null it means we have neither a // response body nor an error stream from the server. No point in going // any further. if (in == null) { throw new AnnounceException("No response or unreachable tracker!"); } try { // Parse and handle the response return HTTPTrackerMessage.parse(in); } catch (IOException ioe) { throw new AnnounceException("Error reading tracker response!", ioe); } catch (MessageValidationException mve) { throw new AnnounceException("Tracker message violates expected " + "protocol (" + mve.getMessage() + ")", mve); } finally { // Make sure we close everything down at the end to avoid resource // leaks. try { in.close(); } catch (IOException ioe) { logger.info("Problem ensuring error stream closed!"); logger.debug("Problem ensuring error stream closed!", ioe); } // This means trying to close the error stream as well. InputStream err = conn.getErrorStream(); if (err != null) { try { err.close(); } catch (IOException ioe) { logger.info("Problem ensuring error stream closed!"); logger.debug("Problem ensuring error stream closed!", ioe); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public BitSet getAvailablePieces() { BitSet availablePieces = new BitSet(this.pieces.length); synchronized (this.pieces) { for (Piece piece : this.pieces) { if (piece.available()) { availablePieces.set(piece.getIndex()); } } } return availablePieces; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public BitSet getAvailablePieces() { if (!this.isInitialized()) { throw new IllegalStateException("Torrent not yet initialized!"); } BitSet availablePieces = new BitSet(this.pieces.length); synchronized (this.pieces) { for (Piece piece : this.pieces) { if (piece.available()) { availablePieces.set(piece.getIndex()); } } } return availablePieces; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public int write(ByteBuffer buffer, long offset) throws IOException { int requested = buffer.remaining(); if (offset + requested > this.size) { throw new IllegalArgumentException("Invalid storage write request!"); } return this.channel.write(buffer, offset); } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public int write(ByteBuffer buffer, long offset) throws IOException { try { myLock.writeLock().lock(); int requested = buffer.remaining(); if (offset + requested > this.size) { throw new IllegalArgumentException("Invalid storage write request!"); } return this.channel.write(buffer, offset); } finally { myLock.writeLock().unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void open() throws IOException { this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void open() throws IOException { try { myLock.writeLock().lock(); this.partial = new File(this.target.getAbsolutePath() + TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX); if (this.partial.exists()) { logger.debug("Partial download found at {}. Continuing...", this.partial.getAbsolutePath()); this.current = this.partial; } else if (!this.target.exists()) { logger.debug("Downloading new file to {}...", this.partial.getAbsolutePath()); this.current = this.partial; } else { logger.debug("Using existing file {}.", this.target.getAbsolutePath()); this.current = this.target; } this.raf = new RandomAccessFile(this.current, "rw"); // Set the file length to the appropriate size, eventually truncating // or extending the file if it already exists with a different size. this.raf.setLength(this.size); this.channel = raf.getChannel(); logger.debug("Opened byte storage file at {} " + "({}+{} byte(s)).", new Object[] { this.current.getAbsolutePath(), this.offset, this.size, }); } finally { myLock.writeLock().unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static String hashPieces(File source) throws NoSuchAlgorithmException, IOException { long start = System.nanoTime(); long hashTime = 0L; MessageDigest md = MessageDigest.getInstance("SHA-1"); InputStream is = new BufferedInputStream(new FileInputStream(source)); StringBuffer pieces = new StringBuffer(); byte[] data = new byte[Torrent.PIECE_LENGTH]; int read; while ((read = is.read(data)) > 0) { md.reset(); md.update(data, 0, read); long hashStart = System.nanoTime(); pieces.append(new String(md.digest(), Torrent.BYTE_ENCODING)); hashTime += (System.nanoTime() - hashStart); } is.close(); int n_pieces = new Double(Math.ceil((double)source.length() / Torrent.PIECE_LENGTH)).intValue(); logger.info("Hashed {} ({} bytes) in {} pieces (total: {}ms, " + "{}ms hashing).", new Object[] { source.getName(), source.length(), n_pieces, String.format("%.1f", (System.nanoTime() - start) / 1024), String.format("%.1f", hashTime / 1024), }); return pieces.toString(); } #location 34 #vulnerability type RESOURCE_LEAK
#fixed code private static String hashPieces(File source) throws NoSuchAlgorithmException, InterruptedException, IOException { ExecutorService executor = Executors.newFixedThreadPool( getHashingThreadsCount()); List<Future<String>> results = new LinkedList<Future<String>>(); byte[] data = new byte[Torrent.PIECE_LENGTH]; int pieces = 0; int read; logger.info("Analyzing local data for {} with {} threads...", source.getName(), getHashingThreadsCount()); long start = System.nanoTime(); InputStream is = new BufferedInputStream(new FileInputStream(source)); while ((read = is.read(data)) > 0) { results.add(executor.submit(new CallableChunkHasher(data, read))); pieces++; } is.close(); // Request orderly executor shutdown and wait for hashing tasks to // complete. executor.shutdown(); while (!executor.isTerminated()) { Thread.sleep(10); } long elapsed = System.nanoTime() - start; StringBuffer hashes = new StringBuffer(); try { for (Future<String> chunk : results) { hashes.append(chunk.get()); } } catch (ExecutionException ee) { throw new IOException("Error while hashing the torrent data!", ee); } int expectedPieces = new Double(Math.ceil((double)source.length() / Torrent.PIECE_LENGTH)).intValue(); logger.info("Hashed {} ({} bytes) in {} pieces ({} expected) in {}ms.", new Object[] { source.getName(), source.length(), pieces, expectedPieces, String.format("%.1f", elapsed/1024.0/1024.0), }); return hashes.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void load_torrent_created_by_utorrent() throws IOException, NoSuchAlgorithmException, URISyntaxException { Torrent t = Torrent.load(new File("src/test/resources/torrents/file1.jar.torrent")); assertEquals(new URI("http://localhost:6969/announce"), t.getAnnounceList().get(0).get(0)); assertEquals("B92D38046C76D73948E14C42DF992CAF25489D08", t.getHexInfoHash()); assertEquals("uTorrent/3130", t.getCreatedBy()); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public void load_torrent_created_by_utorrent() throws IOException, NoSuchAlgorithmException, URISyntaxException { Torrent t = Torrent.load(new File("src/test/resources/torrents/file1.jar.torrent")); assertEquals("http://localhost:6969/announce", t.getAnnounceList().get(0).get(0)); assertEquals("B92D38046C76D73948E14C42DF992CAF25489D08", t.getHexInfoHash()); assertEquals("uTorrent/3130", t.getCreatedBy()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException { int numFiles = 50; this.tracker.setAcceptForeignTorrents(true); final File srcDir = tempFiles.createTempDir(); final File downloadDir = tempFiles.createTempDir(); Client seeder = createClient("seeder"); seeder.start(InetAddress.getLocalHost()); Client leech = null; try { URL announce = new URL("http://127.0.0.1:6969/announce"); URI announceURI = announce.toURI(); final Set<String> names = new HashSet<String>(); List<File> filesToShare = new ArrayList<File>(); for (int i = 0; i < numFiles; i++) { File tempFile = tempFiles.createTempFile(513 * 1024); File srcFile = new File(srcDir, tempFile.getName()); assertTrue(tempFile.renameTo(srcFile)); Torrent torrent = TorrentCreator.create(srcFile, announceURI, "Test"); File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent"); saveTorrent(torrent, torrentFile); filesToShare.add(srcFile); names.add(srcFile.getName()); } for (File f : filesToShare) { File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent"); seeder.addTorrent(torrentFile.getAbsolutePath(), f.getParent()); } leech = createClient("leecher"); leech.start(new InetAddress[]{InetAddress.getLocalHost()}, 5, null); for (File f : filesToShare) { File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent"); leech.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath()); } new WaitFor(60 * 1000) { @Override protected boolean condition() { final Set<String> strings = listFileNames(downloadDir); int count = 0; final List<String> partItems = new ArrayList<String>(); for (String s : strings) { if (s.endsWith(".part")) { count++; partItems.add(s); } } if (count < 5) { System.err.printf("Count: %d. Items: %s%n", count, Arrays.toString(partItems.toArray())); } return strings.containsAll(names); } }; assertEquals(listFileNames(downloadDir), names); } finally { leech.stop(); seeder.stop(); } } #location 35 #vulnerability type NULL_DEREFERENCE
#fixed code public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException { int numFiles = 50; this.tracker.setAcceptForeignTorrents(true); final File srcDir = tempFiles.createTempDir(); final File downloadDir = tempFiles.createTempDir(); Client seeder = createClient("seeder"); seeder.start(InetAddress.getLocalHost()); Client leech = null; try { URL announce = new URL("http://127.0.0.1:6969/announce"); URI announceURI = announce.toURI(); final Set<String> names = new HashSet<String>(); List<File> filesToShare = new ArrayList<File>(); for (int i = 0; i < numFiles; i++) { File tempFile = tempFiles.createTempFile(513 * 1024); File srcFile = new File(srcDir, tempFile.getName()); assertTrue(tempFile.renameTo(srcFile)); Torrent torrent = TorrentCreator.create(srcFile, announceURI, "Test"); File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent"); saveTorrent(torrent, torrentFile); filesToShare.add(srcFile); names.add(srcFile.getName()); } for (File f : filesToShare) { File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent"); seeder.addTorrent(torrentFile.getAbsolutePath(), f.getParent()); } leech = createClient("leecher"); leech.start(new InetAddress[]{InetAddress.getLocalHost()}, 5, null, new SelectorFactoryImpl()); for (File f : filesToShare) { File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent"); leech.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath()); } new WaitFor(60 * 1000) { @Override protected boolean condition() { final Set<String> strings = listFileNames(downloadDir); int count = 0; final List<String> partItems = new ArrayList<String>(); for (String s : strings) { if (s.endsWith(".part")) { count++; partItems.add(s); } } if (count < 5) { System.err.printf("Count: %d. Items: %s%n", count, Arrays.toString(partItems.toArray())); } return strings.containsAll(names); } }; assertEquals(listFileNames(downloadDir), names); } finally { leech.stop(); seeder.stop(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void process(final String uri, final String hostAddress, RequestHandler requestHandler) throws IOException { // Prepare the response headers. /** * Parse the query parameters into an announce request message. * * We need to rely on our own query parsing function because * SimpleHTTP's Query map will contain UTF-8 decoded parameters, which * doesn't work well for the byte-encoded strings we expect. */ HTTPAnnounceRequestMessage announceRequest = null; try { announceRequest = this.parseQuery(uri, hostAddress); } catch (MessageValidationException mve) { LoggerUtils.warnAndDebugDetails(logger, "Unable to parse request message. Request url is {}", uri, mve); serveError(Status.BAD_REQUEST, mve.getMessage(), requestHandler); return; } // The requested torrent must be announced by the tracker if and only if myAcceptForeignTorrents is false final ConcurrentMap<String, TrackedTorrent> torrentsMap = requestHandler.getTorrentsMap(); TrackedTorrent torrent = torrentsMap.get(announceRequest.getHexInfoHash()); if (!this.myAcceptForeignTorrents && torrent == null) { logger.warn("Requested torrent hash was: {}", announceRequest.getHexInfoHash()); serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.UNKNOWN_TORRENT, requestHandler); return; } if (torrent == null) { torrent = new TrackedTorrent(announceRequest.getInfoHash()); TrackedTorrent oldTorrent = requestHandler.getTorrentsMap().putIfAbsent(torrent.getHexInfoHash(), torrent); if (oldTorrent != null) { torrent = oldTorrent; } } AnnounceRequestMessage.RequestEvent event = announceRequest.getEvent(); PeerUID peerUID = new PeerUID(new InetSocketAddress(announceRequest.getIp(), announceRequest.getPort()), announceRequest.getHexInfoHash()); // When no event is specified, it's a periodic update while the client // is operating. If we don't have a peer for this announce, it means // the tracker restarted while the client was running. Consider this // announce request as a 'started' event. if ((event == null || AnnounceRequestMessage.RequestEvent.NONE.equals(event)) && torrent.getPeer(peerUID) == null) { event = AnnounceRequestMessage.RequestEvent.STARTED; } if (myAddressChecker.isBadAddress(announceRequest.getIp())) { writeAnnounceResponse(torrent, null, requestHandler); return; } if (event != null && torrent.getPeer(peerUID) == null && AnnounceRequestMessage.RequestEvent.STOPPED.equals(event)) { writeAnnounceResponse(torrent, null, requestHandler); return; } // If an event other than 'started' is specified and we also haven't // seen the peer on this torrent before, something went wrong. A // previous 'started' announce request should have been made by the // client that would have had us register that peer on the torrent this // request refers to. if (event != null && torrent.getPeer(peerUID) == null && !(AnnounceRequestMessage.RequestEvent.STARTED.equals(event) || AnnounceRequestMessage.RequestEvent.COMPLETED.equals(event))) { serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT, requestHandler); return; } // Update the torrent according to the announce event TrackedPeer peer = null; try { peer = torrent.update(event, ByteBuffer.wrap(announceRequest.getPeerId()), announceRequest.getHexPeerId(), announceRequest.getIp(), announceRequest.getPort(), announceRequest.getUploaded(), announceRequest.getDownloaded(), announceRequest.getLeft()); } catch (IllegalArgumentException iae) { LoggerUtils.warnAndDebugDetails(logger, "Unable to update peer torrent. Request url is {}", uri, iae); serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT, requestHandler); return; } // Craft and output the answer writeAnnounceResponse(torrent, peer, requestHandler); } #location 77 #vulnerability type NULL_DEREFERENCE
#fixed code public void process(final String uri, final String hostAddress, RequestHandler requestHandler) throws IOException { // Prepare the response headers. /** * Parse the query parameters into an announce request message. * * We need to rely on our own query parsing function because * SimpleHTTP's Query map will contain UTF-8 decoded parameters, which * doesn't work well for the byte-encoded strings we expect. */ HTTPAnnounceRequestMessage announceRequest = null; try { announceRequest = this.parseQuery(uri, hostAddress); } catch (MessageValidationException mve) { LoggerUtils.warnAndDebugDetails(logger, "Unable to parse request message. Request url is {}", uri, mve); serveError(Status.BAD_REQUEST, mve.getMessage(), requestHandler); return; } AnnounceRequestMessage.RequestEvent event = announceRequest.getEvent(); if (event == null) { event = AnnounceRequestMessage.RequestEvent.NONE; } TrackedTorrent torrent = myTorrentsRepository.getTorrent(announceRequest.getHexInfoHash()); // The requested torrent must be announced by the tracker if and only if myAcceptForeignTorrents is false if (!this.myAcceptForeignTorrents && torrent == null) { logger.warn("Requested torrent hash was: {}", announceRequest.getHexInfoHash()); serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.UNKNOWN_TORRENT, requestHandler); return; } final boolean isSeeder = (event == AnnounceRequestMessage.RequestEvent.COMPLETED) || (announceRequest.getLeft() == 0); if (myAddressChecker.isBadAddress(announceRequest.getIp())) { if (torrent == null) { writeEmptyResponse(announceRequest, requestHandler); } else { writeAnnounceResponse(torrent, null, isSeeder, requestHandler); } return; } final Peer peer = new Peer(announceRequest.getIp(), announceRequest.getPort()); try { torrent = myTorrentsRepository.putIfAbsentAndUpdate(announceRequest.getHexInfoHash(), new TrackedTorrent(announceRequest.getInfoHash()),event, ByteBuffer.wrap(announceRequest.getPeerId()), announceRequest.getHexPeerId(), announceRequest.getIp(), announceRequest.getPort(), announceRequest.getUploaded(), announceRequest.getDownloaded(), announceRequest.getLeft()); } catch (IllegalArgumentException iae) { LoggerUtils.warnAndDebugDetails(logger, "Unable to update peer torrent. Request url is {}", uri, iae); serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT, requestHandler); return; } // Craft and output the answer writeAnnounceResponse(torrent, peer, isSeeder, requestHandler); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void downloadUninterruptibly(final String dotTorrentPath, final String downloadDirPath, final long idleTimeoutSec, final int minSeedersCount, final AtomicBoolean isInterrupted, final long maxTimeForConnectMs, DownloadProgressListener listener) throws IOException, InterruptedException, NoSuchAlgorithmException { String hash = addTorrent(dotTorrentPath, downloadDirPath, false, true); final AnnounceableFileTorrent announceableTorrent = torrentsStorage.getAnnounceableTorrent(hash); if (announceableTorrent == null) throw new IOException("Unable to download torrent completely - announceable torrent is not found"); final SharedTorrent torrent = SharedTorrent.fromFile(new File(dotTorrentPath), new File(downloadDirPath), false, false, true, announceableTorrent); torrentsStorage.putIfAbsentActiveTorrent(torrent.getHexInfoHash(), torrent); long maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000; torrent.addDownloadProgressListener(listener); final long startDownloadAt = System.currentTimeMillis(); long currentLeft = torrent.getLeft(); while (torrent.getClientState() != ClientState.SEEDING && torrent.getClientState() != ClientState.ERROR && (torrent.getSeedersCount() >= minSeedersCount || torrent.getLastAnnounceTime() < 0) && (System.currentTimeMillis() <= maxIdleTime)) { if (Thread.currentThread().isInterrupted() || isInterrupted.get()) throw new InterruptedException("Download of " + torrent.getDirectoryName() + " was interrupted"); if (currentLeft > torrent.getLeft()) { currentLeft = torrent.getLeft(); maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000; } if (System.currentTimeMillis() - startDownloadAt > maxTimeForConnectMs) { if (getPeersForTorrent(torrent.getHexInfoHash()).size() < minSeedersCount) { break; } } Thread.sleep(100); } if (!(torrent.isFinished() && torrent.getClientState() == ClientState.SEEDING)) { removeAndDeleteTorrent(hash, torrent); final List<SharingPeer> peersForTorrent = getPeersForTorrent(hash); int connectedPeersForTorrent = peersForTorrent.size(); for (SharingPeer peer : peersForTorrent) { peer.unbind(true); } final String errorMsg; if (System.currentTimeMillis() > maxIdleTime) { int completedPieces = torrent.getCompletedPieces().cardinality(); int totalPieces = torrent.getPieceCount(); errorMsg = String.format("No pieces has been downloaded in %d seconds. Downloaded pieces %d/%d, connected peers %d" , idleTimeoutSec, completedPieces, totalPieces, connectedPeersForTorrent); } else if (connectedPeersForTorrent < minSeedersCount) { errorMsg = String.format("Not enough seeders. Required %d, found %d", minSeedersCount, connectedPeersForTorrent); } else if (torrent.getClientState() == ClientState.ERROR) { errorMsg = "Torrent state is ERROR"; } else { errorMsg = "Unknown error"; } throw new IOException("Unable to download torrent completely - " + errorMsg); } } #location 59 #vulnerability type RESOURCE_LEAK
#fixed code public void downloadUninterruptibly(final String dotTorrentPath, final String downloadDirPath, final long idleTimeoutSec, final int minSeedersCount, final AtomicBoolean isInterrupted, final long maxTimeForConnectMs, DownloadProgressListener listener) throws IOException, InterruptedException, NoSuchAlgorithmException { String hash = addTorrent(dotTorrentPath, downloadDirPath, false, true); final AnnounceableFileTorrent announceableTorrent = torrentsStorage.getAnnounceableTorrent(hash); if (announceableTorrent == null) throw new IOException("Unable to download torrent completely - announceable torrent is not found"); SharedTorrent torrent = new TorrentLoaderImpl(torrentsStorage).loadTorrent(announceableTorrent); long maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000; torrent.addDownloadProgressListener(listener); final long startDownloadAt = System.currentTimeMillis(); long currentLeft = torrent.getLeft(); while (torrent.getClientState() != ClientState.SEEDING && torrent.getClientState() != ClientState.ERROR && (torrent.getSeedersCount() >= minSeedersCount || torrent.getLastAnnounceTime() < 0) && (System.currentTimeMillis() <= maxIdleTime)) { if (Thread.currentThread().isInterrupted() || isInterrupted.get()) throw new InterruptedException("Download of " + torrent.getDirectoryName() + " was interrupted"); if (currentLeft > torrent.getLeft()) { currentLeft = torrent.getLeft(); maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000; } if (System.currentTimeMillis() - startDownloadAt > maxTimeForConnectMs) { if (getPeersForTorrent(torrent.getHexInfoHash()).size() < minSeedersCount) { break; } } Thread.sleep(100); } if (!(torrent.isFinished() && torrent.getClientState() == ClientState.SEEDING)) { removeAndDeleteTorrent(hash, torrent); final List<SharingPeer> peersForTorrent = getPeersForTorrent(hash); int connectedPeersForTorrent = peersForTorrent.size(); for (SharingPeer peer : peersForTorrent) { peer.unbind(true); } final String errorMsg; if (System.currentTimeMillis() > maxIdleTime) { int completedPieces = torrent.getCompletedPieces().cardinality(); int totalPieces = torrent.getPieceCount(); errorMsg = String.format("No pieces has been downloaded in %d seconds. Downloaded pieces %d/%d, connected peers %d" , idleTimeoutSec, completedPieces, totalPieces, connectedPeersForTorrent); } else if (connectedPeersForTorrent < minSeedersCount) { errorMsg = String.format("Not enough seeders. Required %d, found %d", minSeedersCount, connectedPeersForTorrent); } else if (torrent.getClientState() == ClientState.ERROR) { errorMsg = "Torrent state is ERROR"; } else { errorMsg = "Unknown error"; } throw new IOException("Unable to download torrent completely - " + errorMsg); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void removeTorrent(TorrentHash torrentHash) { logger.info("Stopping seeding " + torrentHash.getHexInfoHash()); final TorrentsPair torrentsPair = torrentsStorage.removeActiveAndAnnounceableTorrent(torrentHash.getHexInfoHash()); SharedTorrent torrent = torrentsPair.getSharedTorrent(); if (torrent != null) { torrent.setClientState(ClientState.DONE); torrent.close(); } else { logger.warn(String.format("Torrent %s already removed from myTorrents", torrentHash.getHexInfoHash())); } final AnnounceableFileTorrent announceableFileTorrent = torrentsPair.getAnnounceableFileTorrent(); if (announceableFileTorrent == null) { logger.info("Announceable torrent {} not found in storage on removing torrent", torrentHash.getHexInfoHash()); } try { this.announce.forceAnnounce(announceableFileTorrent, this, STOPPED); } catch (IOException e) { LoggerUtils.warnAndDebugDetails(logger, "can not send force stop announce event on delete torrent {}", torrentHash.getHexInfoHash(), e); } } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code public void removeTorrent(TorrentHash torrentHash) { logger.info("Stopping seeding " + torrentHash.getHexInfoHash()); final TorrentsPair torrentsPair = torrentsStorage.removeActiveAndAnnounceableTorrent(torrentHash.getHexInfoHash()); SharedTorrent torrent = torrentsPair.getSharedTorrent(); if (torrent != null) { torrent.setClientState(ClientState.DONE); torrent.close(); } else { logger.warn(String.format("Torrent %s already removed from myTorrents", torrentHash.getHexInfoHash())); } sendStopEvent(torrentsPair.getAnnounceableFileTorrent(), torrentHash.getHexInfoHash()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void initAndRunWorker() throws IOException { myServerSocketChannel = selector.provider().openServerSocketChannel(); myServerSocketChannel.configureBlocking(false); for (int port = PORT_RANGE_START; port < PORT_RANGE_END; port++) { try { InetSocketAddress tryAddress = new InetSocketAddress(inetAddress, port); myServerSocketChannel.socket().bind(tryAddress); myServerSocketChannel.register(selector, SelectionKey.OP_ACCEPT); this.myBindAddress = tryAddress; break; } catch (IOException e) { //try next port logger.debug("Could not bind to port {}, trying next port...", port); } } if (this.myBindAddress == null) { throw new IOException("No available port for the BitTorrent client!"); } final String id = Client.BITTORRENT_ID_PREFIX + UUID.randomUUID().toString().split("-")[4]; byte[] idBytes = id.getBytes(Torrent.BYTE_ENCODING); Peer self = new Peer(this.myBindAddress, ByteBuffer.wrap(idBytes)); peersStorageProvider.getPeersStorage().setSelf(self); myWorkerFuture = myExecutorService.submit(this);// TODO: 11/22/17 move runnable part to separate class e.g. ConnectionWorker logger.info("BitTorrent client [{}] started and " + "listening at {}:{}...", new Object[]{ self.getShortHexPeerId(), self.getIp(), self.getPort() }); } #location 28 #vulnerability type NULL_DEREFERENCE
#fixed code public void initAndRunWorker() throws IOException { myServerSocketChannel = selector.provider().openServerSocketChannel(); myServerSocketChannel.configureBlocking(false); for (int port = PORT_RANGE_START; port < PORT_RANGE_END; port++) { try { InetSocketAddress tryAddress = new InetSocketAddress(inetAddress, port); myServerSocketChannel.socket().bind(tryAddress); myServerSocketChannel.register(selector, SelectionKey.OP_ACCEPT); this.myBindAddress = tryAddress; break; } catch (IOException e) { //try next port logger.debug("Could not bind to port {}, trying next port...", port); } } if (this.myBindAddress == null) { throw new IOException("No available port for the BitTorrent client!"); } myWorkerFuture = myExecutorService.submit(this);// TODO: 11/22/17 move runnable part to separate class e.g. ConnectionWorker }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void handlePeerDisconnected(SharingPeer peer) { final SharedTorrent peerTorrent = peer.getTorrent(); Peer p = new Peer(peer.getIp(), peer.getPort()); p.setPeerId(peer.getPeerId()); p.setTorrentHash(peer.getHexInfoHash()); PeerUID peerUID = new PeerUID(p.getStringPeerId(), p.getHexInfoHash()); SharingPeer sharingPeer = this.peersStorage.removeSharingPeer(peerUID); logger.debug("Peer {} disconnected, [{}/{}].", new Object[]{ peer, getConnectedPeers().size(), this.peersStorage.getSharingPeers().size() }); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void handlePeerDisconnected(SharingPeer peer) { final SharedTorrent peerTorrent = peer.getTorrent(); Peer p = new Peer(peer.getIp(), peer.getPort()); p.setPeerId(peer.getPeerId()); p.setTorrentHash(peer.getHexInfoHash()); PeerUID peerUID = new PeerUID(p.getAddress(), p.getHexInfoHash()); SharingPeer sharingPeer = this.peersStorage.removeSharingPeer(peerUID); logger.debug("Peer {} disconnected, [{}/{}].", new Object[]{ peer, getConnectedPeers().size(), this.peersStorage.getSharingPeers().size() }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public MetadataBuilder addFile(@NotNull File source, @NotNull String path) { if (!source.isFile()) { throw new IllegalArgumentException(source + " is not exist"); } sources.add(new Source(source, path)); return this; } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public MetadataBuilder addFile(@NotNull File source, @NotNull String path) { if (!source.isFile()) { throw new IllegalArgumentException(source + " is not exist"); } checkHashingResultIsNotSet(); filesPaths.add(path); dataSources.add(new FileSourceHolder(source)); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public int read(ByteBuffer buffer, long offset) throws IOException { int requested = buffer.remaining(); if (offset + requested > this.size) { throw new IllegalArgumentException("Invalid storage read request!"); } int bytes = this.channel.read(buffer, offset); if (bytes < requested) { throw new IOException("Storage underrun!"); } return bytes; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public int read(ByteBuffer buffer, long offset) throws IOException { try { myLock.readLock().lock(); int requested = buffer.remaining(); if (offset + requested > this.size) { throw new IllegalArgumentException("Invalid storage read request!"); } int bytes = this.channel.read(buffer, offset); if (bytes < requested) { throw new IOException("Storage underrun!"); } return bytes; } finally { myLock.readLock().unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void unbind(boolean force) { if (!force) { // Cancel all outgoing requests, and send a NOT_INTERESTED message to // the peer. this.cancelPendingRequests(); this.send(PeerMessage.NotInterestedMessage.craft()); } PeerExchange exchangeCopy; synchronized (this.exchangeLock) { exchangeCopy = exchange; } if (exchangeCopy != null) { exchangeCopy.close(); } synchronized (this.exchangeLock) { this.exchange = null; } this.firePeerDisconnected(); this.requestedPiece = null; } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void unbind(boolean force) { if (!force) { // Cancel all outgoing requests, and send a NOT_INTERESTED message to // the peer. this.cancelPendingRequests(); this.send(PeerMessage.NotInterestedMessage.craft()); } PeerExchange exchangeCopy; synchronized (this.exchangeLock) { exchangeCopy = exchange; } if (exchangeCopy != null) { exchangeCopy.close(); } synchronized (this.exchangeLock) { this.exchange = null; } this.firePeerDisconnected(); myRequestedPieces.clear(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void accept() throws IOException, SocketTimeoutException { Socket socket = this.socket.accept(); try { logger.debug("New incoming connection ..."); Handshake hs = this.validateHandshake(socket, null); this.sendHandshake(socket); this.fireNewPeerConnection(socket, hs.getPeerId()); } catch (ParseException pe) { logger.info("Invalid handshake from " + this.socketRepr(socket) + ": " + pe.getMessage()); try { socket.close(); } catch (IOException e) { } } catch (IOException ioe) { logger.info("An error occured while reading an incoming " + "handshake: " + ioe.getMessage()); try { if (!socket.isClosed()) { socket.close(); } } catch (IOException e) { // Ignore } } } #location 17 #vulnerability type RESOURCE_LEAK
#fixed code private void accept() throws IOException, SocketTimeoutException { Socket socket = this.socket.accept(); try { logger.debug("New incoming connection ..."); Handshake hs = this.validateHandshake(socket, null); this.sendHandshake(socket); this.fireNewPeerConnection(socket, hs.getPeerId()); } catch (ParseException pe) { logger.info("Invalid handshake from {}: {}", this.socketRepr(socket), pe.getMessage()); try { socket.close(); } catch (IOException e) { } } catch (IOException ioe) { logger.info("An error occured while reading an incoming " + "handshake: {}", ioe.getMessage()); try { if (!socket.isClosed()) { socket.close(); } } catch (IOException e) { // Ignore } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public DataProcessor processAndGetNext(ByteChannel socketChannel) throws IOException { if (pstrLength == -1) { ByteBuffer len = ByteBuffer.allocate(1); int readBytes = -1; try { readBytes = socketChannel.read(len); } catch (IOException ignored) { } if (readBytes == -1) { return new ShutdownProcessor(uid, peersStorageFactory); } if (readBytes == 0) { return this; } len.rewind(); byte pstrLen = len.get(); this.pstrLength = pstrLen; messageBytes = ByteBuffer.allocate(this.pstrLength + Handshake.BASE_HANDSHAKE_LENGTH); messageBytes.put(pstrLen); } int readBytes = -1; try { readBytes = socketChannel.read(messageBytes); } catch (IOException e) { e.printStackTrace(); } if (readBytes == -1) { return new ShutdownProcessor(uid, peersStorageFactory); } if (messageBytes.remaining() != 0) { return this; } Handshake hs; try { messageBytes.rewind(); hs = Handshake.parse(messageBytes, pstrLength); } catch (ParseException e) { logger.debug("incorrect handshake message from " + socketChannel.toString(), e); return new ShutdownProcessor(uid, peersStorageFactory); } if (!torrentsStorageFactory.getTorrentsStorage().hasTorrent(hs.getHexInfoHash())) { logger.debug("peer {} try download torrent with hash {}, but it's unknown torrent for self", Arrays.toString(hs.getPeerId()), hs.getHexInfoHash()); return new ShutdownProcessor(uid, peersStorageFactory); } Peer peer = peersStorageFactory.getPeersStorage().getPeer(uid); logger.trace("set peer id to peer " + peer); peer.setPeerId(ByteBuffer.wrap(hs.getPeerId())); peer.setTorrentHash(hs.getHexInfoHash()); ConnectionUtils.sendHandshake(socketChannel, hs.getInfoHash(), peersStorageFactory.getPeersStorage().getSelf().getPeerIdArray()); SharedTorrent torrent = torrentsStorageFactory.getTorrentsStorage().getTorrent(hs.getHexInfoHash()); SharingPeer sharingPeer = new SharingPeer(peer.getIp(), peer.getPort(), peer.getPeerId(), torrent); sharingPeer.register(torrent); sharingPeer.bind(socketChannel, true); peersStorageFactory.getPeersStorage().addSharingPeer(peer, sharingPeer); return new WorkingReceiver(this.uid, peersStorageFactory, torrentsStorageFactory); } #location 57 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public DataProcessor processAndGetNext(ByteChannel socketChannel) throws IOException { if (pstrLength == -1) { ByteBuffer len = ByteBuffer.allocate(1); int readBytes = -1; try { readBytes = socketChannel.read(len); } catch (IOException ignored) { } if (readBytes == -1) { return new ShutdownProcessor(uid, peersStorageFactory); } if (readBytes == 0) { return this; } len.rewind(); byte pstrLen = len.get(); this.pstrLength = pstrLen; messageBytes = ByteBuffer.allocate(this.pstrLength + Handshake.BASE_HANDSHAKE_LENGTH); messageBytes.put(pstrLen); } int readBytes = -1; try { readBytes = socketChannel.read(messageBytes); } catch (IOException e) { e.printStackTrace(); } if (readBytes == -1) { return new ShutdownProcessor(uid, peersStorageFactory); } if (messageBytes.remaining() != 0) { return this; } Handshake hs; try { messageBytes.rewind(); hs = Handshake.parse(messageBytes, pstrLength); } catch (ParseException e) { logger.debug("incorrect handshake message from " + socketChannel.toString(), e); return new ShutdownProcessor(uid, peersStorageFactory); } if (!torrentsStorageFactory.getTorrentsStorage().hasTorrent(hs.getHexInfoHash())) { logger.debug("peer {} try download torrent with hash {}, but it's unknown torrent for self", Arrays.toString(hs.getPeerId()), hs.getHexInfoHash()); return new ShutdownProcessor(uid, peersStorageFactory); } logger.debug("get handshake {} from {}", Arrays.toString(messageBytes.array()), socketChannel); Peer peer = peersStorageFactory.getPeersStorage().getPeer(uid); ByteBuffer wrap = ByteBuffer.wrap(hs.getPeerId()); wrap.rewind(); peer.setPeerId(wrap); peer.setTorrentHash(hs.getHexInfoHash()); logger.trace("set peer id to peer " + peer); ConnectionUtils.sendHandshake(socketChannel, hs.getInfoHash(), peersStorageFactory.getPeersStorage().getSelf().getPeerIdArray()); SharedTorrent torrent = torrentsStorageFactory.getTorrentsStorage().getTorrent(hs.getHexInfoHash()); SharingPeer sharingPeer = new SharingPeer(peer.getIp(), peer.getPort(), peer.getPeerId(), torrent); sharingPeer.register(torrent); sharingPeer.register(myPeerActivityListener); sharingPeer.bind(socketChannel, true); SharingPeer old = peersStorageFactory.getPeersStorage().tryAddSharingPeer(peer, sharingPeer); if (old != null) { logger.debug("$$$ already connected to " + peer); return new ShutdownProcessor(uid, peersStorageFactory); } return new WorkingReceiver(this.uid, peersStorageFactory, torrentsStorageFactory); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void send(PeerMessage message) throws IllegalStateException { logger.trace("Sending msg {} to {}", message.getType(), this); if (this.isConnected()) { ByteBuffer data = message.getData(); data.rewind(); boolean writeTaskAdded = connectionManager.offerWrite(new WriteTask(socketChannel, data, new WriteListener() { @Override public void onWriteFailed(String message, Throwable e) { logger.debug(message, e); unbind(true); } @Override public void onWriteDone() { } }), 1, TimeUnit.SECONDS); if (!writeTaskAdded) { unbind(true); } } else { logger.info("Attempting to send a message to non-connected peer {}!", this); unbind(true); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void send(PeerMessage message) throws IllegalStateException { logger.trace("Sending msg {} to {}", message.getType(), this); if (this.isConnected()) { ByteBuffer data = message.getData(); data.rewind(); connectionManager.offerWrite(new WriteTask(socketChannel, data, new WriteListener() { @Override public void onWriteFailed(String message, Throwable e) { logger.debug(message, e); unbind(true); } @Override public void onWriteDone() { } }), 1, TimeUnit.SECONDS); } else { logger.info("Attempting to send a message to non-connected peer {}!", this); unbind(true); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void init(String fileName) throws IOException { cellList.clear(); BufferedReader reader = FileReadUtil.createLineRead(fileName); String line = reader.readLine(); String[] temps; while (line != null) { temps = StringUtils.split(line, "|"); cellList.add(new WxImgCreateTemplateCell(temps[0], temps[1])); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code private void init(String fileName) throws IOException { List<WxImgCreateTemplateCell> list = new CopyOnWriteArrayList<>(); BufferedReader reader = FileReadUtil.createLineRead(fileName); String line = reader.readLine(); String[] temps; while (line != null) { temps = StringUtils.split(line, "|"); list.add(new WxImgCreateTemplateCell(temps[0], temps[1])); line = reader.readLine(); } cellList = list; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); return; } packet.writeLength += n; } clearTimeout(); handler.onSended(this, packet.buffers[1], packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { // key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); timeoutClose(); return; } packet.writeLength += n; } clearTimeout(); handler.onSended(this, packet.buffers[1], packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); return; } packet.writeLength += n; } ByteBufferStream.free(packet.buffers[1]); clearTimeout(); handler.onSended(this, packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); return; } packet.writeLength += n; } clearTimeout(); handler.onSended(this, packet.buffers[1], packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); return; } packet.writeLength += n; } clearTimeout(); handler.onSended(this, packet.buffers[1], packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public final void send() { if (packet == null) { packet = outqueue.poll(); if (packet == null) { return; } } try { for (;;) { while (packet.writeLength < packet.totalLength) { setTimeout(handler.getWriteTimeout(), TimeoutType.WRITE_TIMEOUT); long n = channel.write(packet.buffers); if (n < 0) { close(); return; } if (n == 0) { // key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); timeoutClose(); return; } packet.writeLength += n; } clearTimeout(); handler.onSended(this, packet.buffers[1], packet.id); synchronized (outqueue) { packet = outqueue.poll(); if (packet == null) { key.interestOps(SelectionKey.OP_READ); return; } } } } catch (Exception e) { close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Map<String, String> filterInfo(Map<String, String> info) { HashMap<String, String> newInfo = Maps.newHashMap(info); String limit = newInfo.get(PUSH_PROPERTIES_LIMIT); if (Strings.isNullOrEmpty(limit)) { newInfo.remove(PUSH_PROPERTIES_LIMIT); return ImmutableMap.copyOf(newInfo); } List<String> limitList = PUSH_LIMIT_SPLITTER.splitToList(limit); if (limitList.size() == 0) { newInfo.remove(PUSH_PROPERTIES_LIMIT); return ImmutableMap.copyOf(newInfo); } ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); for (String key : limitList) { builder.put(key, newInfo.get(key)); } return builder.build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
#fixed code private Map<String, String> filterInfo(Map<String, String> info) { Map<String, String> newInfo = Maps.newHashMap(info); String limitLine = newInfo.remove(PUSH_PROPERTIES_LIMIT); Set<String> limitKeys = getLimitKeys(limitLine); if (limitKeys.isEmpty()) { return newInfo; } ImmutableMap.Builder<String, String> result = ImmutableMap.builder(); for (String key : limitKeys) { result.put(key, newInfo.get(key)); } return result.build(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public T blpopObject(int timeout, String key, Class clazz) { this.setSchema(clazz); Jedis jedis = null; try { List<byte[]> bytes = jedis.blpop(timeout, key.getBytes()); if (bytes == null || bytes.size() == 0) { return null; } return getBytes(bytes.get(1)); } finally { jedis.close(); } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public T blpopObject(int timeout, String key, Class clazz) { this.setSchema(clazz); Jedis jedis = null; try { jedis = jedisPool.getResource(); List<byte[]> bytes = jedis.blpop(timeout, key.getBytes()); if (bytes == null || bytes.size() == 0) { return null; } return getBytes(bytes.get(1)); } finally { jedis.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPostMultipleFiles() throws JSONException, URISyntaxException { HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").field("param3", "wot").field("file1", new File(getClass().getResource("/test").toURI())).field("file2", new File(getClass().getResource("/test").toURI())).asJson(); JSONObject names = response.getBody().getObject().getJSONObject("files"); assertEquals(2, names.length()); assertEquals("This is a test file", names.getString("file1")); assertEquals("This is a test file", names.getString("file2")); assertEquals("wot", response.getBody().getObject().getJSONObject("form").getString("param3")); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testPostMultipleFiles() throws JSONException, URISyntaxException { HttpResponse<JsonNode> response = Unirest.post(MockServer.POST) .field("param3", "wot") .field("file1", new File(getClass().getResource("/test").toURI())) .field("file2", new File(getClass().getResource("/test").toURI())) .asJson(); parse(response) .assertParam("param3", "wot") .assertFileContent("file1", "This is a test file") .assertFileContent("file2", "This is a test file"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCustomUserAgent() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get?name=mark").header("user-agent", "hello-world").asJson(); assertEquals("hello-world", response.getBody().getObject().getJSONObject("headers").getString("User-Agent")); GetRequest getRequest = Unirest.get("http"); for (Object current : Arrays.asList(0, 1, 2)) { getRequest.queryString("name", current); } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testCustomUserAgent() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON) .header("user-agent", "hello-world") .asJson(); RequestCapture json = parse(response); json.assertHeader("User-Agent", "hello-world"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAsync() throws JSONException, InterruptedException, ExecutionException { Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .field("param1", "value1") .field("param2","bye") .asJsonAsync(); assertNotNull(future); HttpResponse<JsonNode> jsonResponse = future.get(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getCode()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testAsync() throws JSONException, InterruptedException, ExecutionException { // Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post") // .header("accept", "application/json") // .field("param1", "value1") // .field("param2","bye") // .asJsonAsync(); // // assertNotNull(future); // HttpResponse<JsonNode> jsonResponse = future.get(); // // assertTrue(jsonResponse.getHeaders().size() > 0); // assertTrue(jsonResponse.getBody().toString().length() > 0); // assertFalse(jsonResponse.getRawBody() == null); // assertEquals(200, jsonResponse.getCode()); // // JsonNode json = jsonResponse.getBody(); // assertFalse(json.isArray()); // assertNotNull(json.getObject()); // assertNotNull(json.getArray()); // assertEquals(1, json.getArray().length()); // assertNotNull(json.getArray().get(0)); Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .field("param1", "value1") .field("param2", "value2") .asJsonAsync(new Callback<JsonNode>() { public void failed(Exception e) { System.out.println("The request has failed"); } public void completed(HttpResponse<JsonNode> response) { int code = response.getCode(); Map<String, String> headers = response.getHeaders(); JsonNode body = response.getBody(); InputStream rawBody = response.getRawBody(); } public void cancelled() { System.out.println("The request has been cancelled"); } }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDelete() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.delete("http://httpbin.org/delete").asJson(); assertEquals(200, response.getCode()); response = Unirest.delete("http://httpbin.org/delete").field("name", "mark").asJson(); assertEquals("name=mark", response.getBody().getObject().getString("data")); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDelete() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.delete("http://httpbin.org/delete").asJson(); assertEquals(200, response.getCode()); //TODO: Uncomment when https://github.com/Mashape/unirest-java/issues/36 has been fixed // response = Unirest.delete("http://httpbin.org/delete").field("name", "mark").asJson(); // assertEquals("name=mark", response.getBody().getObject().getString("data")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static <T> MashapeResponse<T> doRequest (Class<T> clazz, HttpMethod httpMethod, String url, Map<String, Object> parameters, ContentType contentType, ResponseType responseType, List<Authentication> authenticationHandlers) { if (authenticationHandlers == null) authenticationHandlers = new ArrayList<Authentication>(); if (parameters == null) parameters = new HashMap<String, Object>(); List<Header> headers = new LinkedList<Header>(); // Handle authentications for (Authentication authentication : authenticationHandlers) { if (authentication instanceof HeaderAuthentication) { headers.addAll(authentication.getHeaders()); } else { Map<String, String> queryParameters = authentication.getQueryParameters(); if (authentication instanceof QueryAuthentication) { parameters.putAll(queryParameters); } else if (authentication instanceof OAuth10aAuthentication) { if (url.endsWith("/oauth_url") == false && (queryParameters == null || queryParameters.get(OAuthAuthentication.ACCESS_SECRET) == null || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) { throw new RuntimeException("Before consuming OAuth endpoint, invoke authorize('access_token','access_secret') with not null values"); } headers.add(new BasicHeader("x-mashape-oauth-consumerkey", queryParameters.get(OAuthAuthentication.CONSUMER_KEY))); headers.add(new BasicHeader("x-mashape-oauth-consumersecret", queryParameters.get(OAuthAuthentication.CONSUMER_SECRET))); headers.add(new BasicHeader("x-mashape-oauth-accesstoken", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN))); headers.add(new BasicHeader("x-mashape-oauth-accesssecret", queryParameters.get(OAuthAuthentication.ACCESS_SECRET))); } else if (authentication instanceof OAuth2Authentication) { if (url.endsWith("/oauth_url") == false && (queryParameters == null || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) { throw new RuntimeException("Before consuming OAuth endpoint, invoke authorize('access_token') with a not null value"); } parameters.put("access_token", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN)); } } } // Sanitize null parameters Set<String> keySet = new HashSet<String>(parameters.keySet()); for (String key : keySet) { if (parameters.get(key) == null) { parameters.remove(key); } } headers.add(new BasicHeader("User-Agent", USER_AGENT)); HttpUriRequest request = null; switch(httpMethod) { case GET: request = new HttpGet(url + "?" + HttpUtils.getQueryString(parameters)); break; case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; case DELETE: request = new HttpDeleteWithBody(url); break; case PATCH: request = new HttpPatchWithBody(url); break; } for(Header header : headers) { request.addHeader(header); } if (httpMethod != HttpMethod.GET) { switch(contentType) { case BINARY: MultipartEntity entity = new MultipartEntity(); for(Entry<String, Object> parameter : parameters.entrySet()) { if (parameter.getValue() instanceof File) { entity.addPart(parameter.getKey(), new FileBody((File) parameter.getValue())); } else { try { entity.addPart(parameter.getKey(), new StringBody(parameter.getValue().toString(), Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } ((HttpEntityEnclosingRequestBase) request).setEntity(entity); break; case FORM: try { ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(MapUtil.getList(parameters), HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } break; case JSON: String jsonBody = null; if((parameters.get(JSON_PARAM_BODY) == null)) { String jsonParamBody = parameters.get(JSON_PARAM_BODY).toString(); jsonBody = (HttpUtils.isJson(jsonParamBody)) ? jsonParamBody : gson.toJson(jsonParamBody); } try { ((HttpEntityEnclosingRequestBase) request).setEntity(new StringEntity(jsonBody, "UTF-8")); ((HttpEntityEnclosingRequestBase) request).setHeader(new BasicHeader("Content-Type", "application/json")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } org.apache.http.client.HttpClient client = new DefaultHttpClient(); HttpResponse response; try { response = client.execute(request); } catch (Exception e) { throw new RuntimeException(e); } MashapeResponse<T> mashapeResponse = HttpUtils.getResponse(responseType, response); return mashapeResponse; } #location 98 #vulnerability type NULL_DEREFERENCE
#fixed code public static <T> MashapeResponse<T> doRequest (Class<T> clazz, HttpMethod httpMethod, String url, Map<String, Object> parameters, ContentType contentType, ResponseType responseType, List<Authentication> authenticationHandlers) { if (authenticationHandlers == null) authenticationHandlers = new ArrayList<Authentication>(); if (parameters == null) parameters = new HashMap<String, Object>(); List<Header> headers = new LinkedList<Header>(); // Handle authentications for (Authentication authentication : authenticationHandlers) { if (authentication instanceof HeaderAuthentication) { headers.addAll(authentication.getHeaders()); } else { Map<String, String> queryParameters = authentication.getQueryParameters(); if (authentication instanceof QueryAuthentication) { parameters.putAll(queryParameters); } else if (authentication instanceof OAuth10aAuthentication) { if (url.endsWith("/oauth_url") == false && (queryParameters == null || queryParameters.get(OAuthAuthentication.ACCESS_SECRET) == null || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) { throw new RuntimeException("Before consuming OAuth endpoint, invoke authorize('access_token','access_secret') with not null values"); } headers.add(new BasicHeader("x-mashape-oauth-consumerkey", queryParameters.get(OAuthAuthentication.CONSUMER_KEY))); headers.add(new BasicHeader("x-mashape-oauth-consumersecret", queryParameters.get(OAuthAuthentication.CONSUMER_SECRET))); headers.add(new BasicHeader("x-mashape-oauth-accesstoken", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN))); headers.add(new BasicHeader("x-mashape-oauth-accesssecret", queryParameters.get(OAuthAuthentication.ACCESS_SECRET))); } else if (authentication instanceof OAuth2Authentication) { if (url.endsWith("/oauth_url") == false && (queryParameters == null || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) { throw new RuntimeException("Before consuming OAuth endpoint, invoke authorize('access_token') with a not null value"); } parameters.put("access_token", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN)); } } } // Sanitize null parameters Set<String> keySet = new HashSet<String>(parameters.keySet()); for (String key : keySet) { if (parameters.get(key) == null) { parameters.remove(key); } } headers.add(new BasicHeader("User-Agent", USER_AGENT)); HttpUriRequest request = null; switch(httpMethod) { case GET: request = new HttpGet(url + "?" + HttpUtils.getQueryString(parameters)); break; case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; case DELETE: request = new HttpDeleteWithBody(url); break; case PATCH: request = new HttpPatchWithBody(url); break; } for(Header header : headers) { request.addHeader(header); } if (httpMethod != HttpMethod.GET) { switch(contentType) { case BINARY: MultipartEntity entity = new MultipartEntity(); for(Entry<String, Object> parameter : parameters.entrySet()) { if (parameter.getValue() instanceof File) { entity.addPart(parameter.getKey(), new FileBody((File) parameter.getValue())); } else { try { entity.addPart(parameter.getKey(), new StringBody(parameter.getValue().toString(), Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } ((HttpEntityEnclosingRequestBase) request).setEntity(entity); break; case FORM: try { ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(MapUtil.getList(parameters), HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } break; case JSON: String jsonBody = null; if((parameters.get(JSON_PARAM_BODY) != null)) { String jsonParamBody = parameters.get(JSON_PARAM_BODY).toString(); jsonBody = (HttpUtils.isJson(jsonParamBody)) ? jsonParamBody : gson.toJson(jsonParamBody); } try { ((HttpEntityEnclosingRequestBase) request).setEntity(new StringEntity(jsonBody, "UTF-8")); ((HttpEntityEnclosingRequestBase) request).setHeader(new BasicHeader("Content-Type", "application/json")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } org.apache.http.client.HttpClient client = new DefaultHttpClient(); HttpResponse response; try { response = client.execute(request); } catch (Exception e) { throw new RuntimeException(e); } MashapeResponse<T> mashapeResponse = HttpUtils.getResponse(responseType, response); return mashapeResponse; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPostRawBody() { String sourceString = "'\"@こんにけは-test-123-" + Math.random(); byte[] sentBytes = sourceString.getBytes(); HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").body(sentBytes).asJson(); assertEquals(sourceString, response.getBody().getObject().getString("data")); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testPostRawBody() { String sourceString = "'\"@こんにけは-test-123-" + Math.random(); byte[] sentBytes = sourceString.getBytes(); HttpResponse<JsonNode> response = Unirest.post(MockServer.POST) .body(sentBytes) .asJson(); RequestCapture json = parse(response); json.asserBody(sourceString); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMultipartAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException { Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post") .field("file", new File(getClass().getResource("/test").toURI())).asJsonAsync(new Callback<JsonNode>() { public void failed(UnirestException e) { // TODO Auto-generated method stub } public void completed(HttpResponse<JsonNode> response) { assertTrue(response.getHeaders().size() > 0); assertTrue(response.getBody().toString().length() > 0); assertFalse(response.getRawBody() == null); assertEquals(200, response.getCode()); JsonNode json = response.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); } public void cancelled() { // TODO Auto-generated method stub } }); HttpResponse<JsonNode> response = future.get(); assertTrue(response.getHeaders().size() > 0); assertTrue(response.getBody().toString().length() > 0); assertFalse(response.getRawBody() == null); assertEquals(200, response.getCode()); JsonNode json = response.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); // assertNotNull(json.getObject().getJSONObject("files")); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testMultipartAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException { Unirest.post("http://httpbin.org/post") .field("name", "Mark") .field("file", new File(getClass().getResource("/test").toURI())).asJsonAsync(new Callback<JsonNode>() { public void failed(UnirestException e) { fail(); } public void completed(HttpResponse<JsonNode> response) { assertTrue(response.getHeaders().size() > 0); assertTrue(response.getBody().toString().length() > 0); assertFalse(response.getRawBody() == null); assertEquals(200, response.getCode()); JsonNode json = response.getBody(); System.out.println(json); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertEquals("This \nis \na \ntest \nfile", json.getObject().getJSONObject("files").getString("file")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); status = true; lock.countDown(); } public void cancelled() { fail(); } }); lock.await(10, TimeUnit.SECONDS); assertTrue(status); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMultipartInputStreamContentType() throws JSONException, URISyntaxException, FileNotFoundException { FileInputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); MultipartBody request = Unirest.post(MockServer.HOST + "/post") .header("accept", ContentType.MULTIPART_FORM_DATA.toString()) .field("name", "Mark") .field("file", stream, ContentType.APPLICATION_OCTET_STREAM, "image.jpg"); HttpResponse<JsonNode> jsonResponse = request .asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); JSONObject object = json.getObject(); assertNotNull(object); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertNotNull(object.getJSONObject("files")); assertTrue(json.getObject().getJSONObject("files").getString("type").contains("application/octet-stream")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testMultipartInputStreamContentType() throws JSONException, URISyntaxException, FileNotFoundException { FileInputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); MultipartBody request = Unirest.post(MockServer.HOST + "/post") .header("accept", ContentType.MULTIPART_FORM_DATA.toString()) .field("name", "Mark") .field("file", stream, ContentType.APPLICATION_OCTET_STREAM, "image.jpg"); HttpResponse<JsonNode> jsonResponse = request .asJson(); assertEquals(200, jsonResponse.getStatus()); FormCapture json = TestUtils.read(jsonResponse, FormCapture.class); json.assertHeader("Accept", ContentType.MULTIPART_FORM_DATA.toString()); json.assertQuery("name", "Mark"); assertEquals("application/octet-stream", json.getFile("image.jpg").type); // assertTrue(json.getObject().getJSONObject("files").getString("type").contains("application/octet-stream")); // assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDeleteBody() throws JSONException, UnirestException { String body = "{\"jsonString\":{\"members\":\"members1\"}}"; HttpResponse<JsonNode> response = Unirest.delete("http://httpbin.org/delete").body(body).asJson(); assertEquals(200, response.getStatus()); assertEquals(body, response.getBody().getObject().getString("data")); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDeleteBody() throws JSONException, UnirestException { String body = "{\"jsonString\":{\"members\":\"members1\"}}"; HttpResponse<JsonNode> response = Unirest.delete(MockServer.DELETE) .body(body) .asJson(); assertEquals(200, response.getStatus()); parse(response).asserBody(body); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetMultiple() throws JSONException, UnirestException { for (int i = 1; i <= 20; i++) { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get?try=" + i).asJson(); assertEquals(response.getBody().getObject().getJSONObject("args").getString("try"), ((Integer) i).toString()); } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testGetMultiple() throws JSONException, UnirestException { for (int i = 1; i <= 20; i++) { HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON + "?try=" + i).asJson(); parse(response).assertQuery("try", String.valueOf(i)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPostCollection() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").field("name", Arrays.asList("Mark", "Tom")).asJson(); JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); assertEquals(2, names.length()); assertEquals("Mark", names.getString(0)); assertEquals("Tom", names.getString(1)); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testPostCollection() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.post(MockServer.POST) .field("name", Arrays.asList("Mark", "Tom")) .asJson(); parse(response) .assertParam("name", "Mark") .assertParam("name", "Tom"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetArray() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get").queryString("name", Arrays.asList("Mark", "Tom")).asJson(); JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); assertEquals(2, names.length()); assertEquals("Mark", names.getString(0)); assertEquals("Tom", names.getString(1)); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testGetArray() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get(MockServer.GET) .queryString("name", Arrays.asList("Mark", "Tom")) .asJson(); parse(response) .assertParam("name", "Mark") .assertParam("name", "Tom"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testQueryStringEncoding() throws JSONException, UnirestException { String testKey = "email2=someKey&email"; String testValue = "[email protected]"; HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get").queryString(testKey, testValue).asJson(); assertEquals(testValue, response.getBody().getObject().getJSONObject("args").getString(testKey)); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testQueryStringEncoding() throws JSONException, UnirestException { String testKey = "email2=someKey&email"; String testValue = "[email protected]"; HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON) .queryString(testKey, testValue) .asJson(); parse(response).assertQuery(testKey, testValue); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetUTF8() { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get").queryString("param3", "こんにけは").asJson(); assertEquals(response.getBody().getObject().getJSONObject("args").getString("param3"), "こんにけは"); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testGetUTF8() { HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON) .header("accept", "application/json") .queryString("param3", "こんにけは") .asJson(); FormCapture json = TestUtils.read(response, FormCapture.class); json.assertQuery("param3", "こんにけは"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testObjectMapperWrite() { Unirest.setObjectMapper(new JacksonObjectMapper()); GetResponse postResponseMock = new GetResponse(); postResponseMock.setUrl("http://httpbin.org/post"); HttpResponse<JsonNode> postResponse = Unirest.post(postResponseMock.getUrl()).header("accept", "application/json").header("Content-Type", "application/json").body(postResponseMock).asJson(); assertEquals(200, postResponse.getStatus()); assertEquals(postResponse.getBody().getObject().getString("data"), "{\"url\":\"http://httpbin.org/post\"}"); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testObjectMapperWrite() { Unirest.setObjectMapper(new JacksonObjectMapper()); GetResponse postResponseMock = new GetResponse(); postResponseMock.setUrl(MockServer.POST); HttpResponse<JsonNode> postResponse = Unirest.post(postResponseMock.getUrl()) .header("accept", "application/json") .header("Content-Type", "application/json") .body(postResponseMock) .asJson(); assertEquals(200, postResponse.getStatus()); parse(postResponse) .asserBody("{\"url\":\"http://localhost:4567/post\"}"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetQuerystringArray() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get").queryString("name", "Mark").queryString("name", "Tom").asJson(); JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); assertEquals(2, names.length()); assertEquals("Mark", names.getString(0)); assertEquals("Tom", names.getString(1)); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testGetQuerystringArray() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get(MockServer.GET) .queryString("name", "Mark") .queryString("name", "Tom") .asJson(); parse(response) .assertParam("name", "Mark") .assertParam("name", "Tom"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetFields() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get").queryString("name", "mark").queryString("nick", "thefosk").asJson(); assertEquals(response.getBody().getObject().getJSONObject("args").getString("name"), "mark"); assertEquals(response.getBody().getObject().getJSONObject("args").getString("nick"), "thefosk"); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testGetFields() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON) .queryString("name", "mark") .queryString("nick", "thefosk") .asJson(); RequestCapture parse = parse(response); parse.assertQuery("name", "mark"); parse.assertQuery("nick", "thefosk"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDelete() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.delete("http://httpbin.org/delete").asJson(); assertEquals(200, response.getStatus()); response = Unirest.delete("http://httpbin.org/delete").field("name", "mark").asJson(); assertEquals("mark", response.getBody().getObject().getJSONObject("form").getString("name")); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDelete() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.delete(MockServer.DELETE).asJson(); assertEquals(200, response.getStatus()); response = Unirest.delete(MockServer.DELETE) .field("name", "mark") .field("foo","bar") .asJson(); RequestCapture parse = parse(response); parse.assertParam("name", "mark"); parse.assertParam("foo", "bar"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPostBinaryUTF8() throws URISyntaxException { HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").field("param3", "こんにけは").field("file", new File(getClass().getResource("/test").toURI())).asJson(); assertEquals("This is a test file", response.getBody().getObject().getJSONObject("files").getString("file")); assertEquals("こんにけは", response.getBody().getObject().getJSONObject("form").getString("param3")); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testPostBinaryUTF8() throws URISyntaxException { HttpResponse<JsonNode> response = Unirest.post(MockServer.POST) .header("Accept", ContentType.MULTIPART_FORM_DATA.getMimeType()) .field("param3", "こんにけは") .field("file", new File(getClass().getResource("/test").toURI())) .asJson(); FormCapture json = TestUtils.read(response, FormCapture.class); json.assertQuery("param3", "こんにけは"); json.getFile("test").assertBody("This is a test file"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCaseInsensitiveHeaders() { GetRequest request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco"); assertEquals(1, request.getHeaders().size()); assertEquals("Marco", request.getHeaders().get("name").get(0)); assertEquals("Marco", request.getHeaders().get("NAme").get(0)); assertEquals("Marco", request.getHeaders().get("Name").get(0)); JSONObject headers = request.asJson().getBody().getObject().getJSONObject("headers"); assertEquals("Marco", headers.getString("Name")); request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco").header("Name", "John"); assertEquals(1, request.getHeaders().size()); assertEquals("Marco", request.getHeaders().get("name").get(0)); assertEquals("John", request.getHeaders().get("name").get(1)); assertEquals("Marco", request.getHeaders().get("NAme").get(0)); assertEquals("John", request.getHeaders().get("NAme").get(1)); assertEquals("Marco", request.getHeaders().get("Name").get(0)); assertEquals("John", request.getHeaders().get("Name").get(1)); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testCaseInsensitiveHeaders() { GetRequest request = Unirest.get(MockServer.GET) .header("Name", "Marco"); assertEquals(1, request.getHeaders().size()); assertEquals("Marco", request.getHeaders().get("name").get(0)); assertEquals("Marco", request.getHeaders().get("NAme").get(0)); assertEquals("Marco", request.getHeaders().get("Name").get(0)); parse(request.asJson()) .assertHeader("Name", "Marco"); request = Unirest.get(MockServer.GET).header("Name", "Marco").header("Name", "John"); assertEquals(1, request.getHeaders().size()); assertEquals("Marco", request.getHeaders().get("name").get(0)); assertEquals("John", request.getHeaders().get("name").get(1)); assertEquals("Marco", request.getHeaders().get("NAme").get(0)); assertEquals("John", request.getHeaders().get("NAme").get(1)); assertEquals("Marco", request.getHeaders().get("Name").get(0)); assertEquals("John", request.getHeaders().get("Name").get(1)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMultipartInputStreamContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException, FileNotFoundException { HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())), ContentType.APPLICATION_OCTET_STREAM, "image.jpg").asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertNotNull(json.getObject().getJSONObject("files")); assertTrue(json.getObject().getJSONObject("files").getString("file").contains("data:application/octet-stream")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testMultipartInputStreamContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException, FileNotFoundException { FileInputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); MultipartBody request = Unirest.post(HOST + "/post") .field("name", "Mark") .field("file", stream, ContentType.APPLICATION_OCTET_STREAM, "image.jpg"); HttpResponse<JsonNode> jsonResponse = request .asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); JSONObject object = json.getObject(); assertNotNull(object); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertNotNull(object.getJSONObject("files")); assertTrue(json.getObject().getJSONObject("files").getString("type").contains("application/octet-stream")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAsync() throws JSONException, InterruptedException, ExecutionException { Future<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post").header("accept", "application/json").field("param1", "value1").field("param2", "bye").asJsonAsync(); assertNotNull(future); HttpResponse<JsonNode> jsonResponse = future.get(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testAsync() throws JSONException, InterruptedException, ExecutionException { Future<HttpResponse<JsonNode>> future = Unirest.post(MockServer.POST) .header("accept", "application/json") .field("param1", "value1") .field("param2", "bye") .asJsonAsync(); assertNotNull(future); RequestCapture req = parse(future.get()); req.assertParam("param1", "value1"); req.assertParam("param2", "bye"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetFields2() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get").queryString("email", "[email protected]").asJson(); assertEquals("[email protected]", response.getBody().getObject().getJSONObject("args").getString("email")); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testGetFields2() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON) .queryString("email", "[email protected]") .asJson(); parse(response).assertQuery("email", "[email protected]"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPostUTF8() { HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").field("param3", "こんにけは").asJson(); assertEquals(response.getBody().getObject().getJSONObject("form").getString("param3"), "こんにけは"); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testPostUTF8() { HttpResponse response = Unirest.post(MockServer.POSTJSON) .header("accept", "application/json") .field("param3", "こんにけは") .asJson(); FormCapture json = TestUtils.read(response, FormCapture.class); json.assertQuery("param3", "こんにけは"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBasicAuth() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/headers").basicAuth("user", "test").asJson(); assertEquals("Basic dXNlcjp0ZXN0", response.getBody().getObject().getJSONObject("headers").getString("Authorization")); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testBasicAuth() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON) .basicAuth("user", "test") .asJson(); parse(response).assertHeader("Authorization", "Basic dXNlcjp0ZXN0"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPostArray() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("name", "Tom").asJson(); JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); assertEquals(2, names.length()); assertEquals("Mark", names.getString(0)); assertEquals("Tom", names.getString(1)); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testPostArray() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.post(MockServer.POST) .field("name", "Mark") .field("name", "Tom") .asJson(); parse(response) .assertParam("name", "Mark") .assertParam("name", "Tom"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRequests() throws Exception { HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .field("param1", "value1") .field("param2","bye") .asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getCode()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testRequests() throws JSONException { HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .field("param1", "value1") .field("param2","bye") .asJson(); assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getCode()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean isStarted() { return client.getState() == CuratorFrameworkState.STARTED; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean isStarted() { try { lock.lock(); return client.getState() == CuratorFrameworkState.STARTED; } finally { lock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void postEvent(ApplicationType applicationType, ActionType actionType, ProtocolType protocolType, ProtocolMessage message) { if (message.getException() == null) { return; } ProtocolEvent protocolEvent = new ProtocolEvent(applicationType, actionType, protocolType, message); if (eventNotification) { EventControllerFactory.getSingletonController(EventControllerType.ASYNC).post(protocolEvent); } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public static void postEvent(ApplicationType applicationType, ActionType actionType, ProtocolType protocolType, ProtocolMessage message) { if (message.getException() == null) { return; } ProtocolEvent protocolEvent = new ProtocolEvent(applicationType, actionType, protocolType, message); if (eventNotification) { EventControllerFactory.getAsyncController().post(protocolEvent); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void onEvent(PathChildrenCacheEvent event, InstanceEventType instanceEventType) throws Exception { String childPath = event.getData().getPath(); String applicationJson = childPath.substring(childPath.lastIndexOf("/") + 1); ApplicationEntity applicationEntity = ZookeeperApplicationEntityFactory.fromJson(applicationJson); List<String> applicationJsonList = invoker.getChildNameList(client, path); List<ApplicationEntity> applicationEntityList = ZookeeperApplicationEntityFactory.fromJson(applicationJsonList); InstanceEvent instanceEvent = null; switch (applicationType) { case SERVICE: instanceEvent = new ServiceInstanceEvent(instanceEventType, interfaze, applicationEntity, applicationEntityList); if (executorContainer != null) { ConsistencyExecutor consistencyExecutor = executorContainer.getConsistencyExecutor(); if (consistencyExecutor != null) { consistencyExecutor.consist((ServiceInstanceEvent) instanceEvent); } } break; case REFERENCE: instanceEvent = new ReferenceInstanceEvent(instanceEventType, interfaze, applicationEntity, applicationEntityList); break; } EventControllerFactory.getController(instanceEvent.toString(), EventControllerType.ASYNC).post(instanceEvent); LOG.info("Watched {} {} - interface={}, {}", applicationType.toString(), instanceEventType.toString(), interfaze, applicationEntity.toString()); } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code private void onEvent(PathChildrenCacheEvent event, InstanceEventType instanceEventType) throws Exception { String childPath = event.getData().getPath(); String applicationJson = childPath.substring(childPath.lastIndexOf("/") + 1); ApplicationEntity applicationEntity = ZookeeperApplicationEntityFactory.fromJson(applicationJson); List<String> applicationJsonList = invoker.getChildNameList(client, path); List<ApplicationEntity> applicationEntityList = ZookeeperApplicationEntityFactory.fromJson(applicationJsonList); InstanceEvent instanceEvent = null; switch (applicationType) { case SERVICE: instanceEvent = new ServiceInstanceEvent(instanceEventType, interfaze, applicationEntity, applicationEntityList); if (executorContainer != null) { ConsistencyExecutor consistencyExecutor = executorContainer.getConsistencyExecutor(); if (consistencyExecutor != null) { consistencyExecutor.consist((ServiceInstanceEvent) instanceEvent); } } break; case REFERENCE: instanceEvent = new ReferenceInstanceEvent(instanceEventType, interfaze, applicationEntity, applicationEntityList); break; } EventControllerFactory.getAsyncController(instanceEvent.toString()).post(instanceEvent); LOG.info("Watched {} {} - interface={}, {}", applicationType.toString(), instanceEventType.toString(), interfaze, applicationEntity.toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSourceSinkStartResumeRollingEverySecond() throws Exception { //This is the config that is required to make the VanillaChronicle roll every second final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); assertNotNull(sourceBasePath); assertNotNull(sinkBasePath); final ChronicleSource source = new ChronicleSource( ChronicleQueueBuilder.vanilla(sourceBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build(), 8888); ExcerptAppender appender = source.createAppender(); System.out.print("writing 100 items will take take 10 seconds."); for (int i = 0; i < 100; i++) { appender.startExcerpt(); int value = 1000000000 + i; appender.append(value).append(' '); //this space is really important. appender.finish(); Thread.sleep(100); if(i % 10==0) { System.out.print("."); } } appender.close(); System.out.print("\n"); //create a tailer to get the first 50 items then exit the tailer final ChronicleSink sink1 = new ChronicleSink( ChronicleQueueBuilder.vanilla(sinkBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build(), "localhost", 8888); final ExcerptTailer tailer1 = sink1.createTailer().toStart(); System.out.println("Sink1 reading first 50 items then stopping"); for( int count=0; count < 50 ;) { if(tailer1.nextIndex()) { assertEquals(1000000000 + count, tailer1.parseLong()); tailer1.finish(); count++; } } tailer1.close(); sink1.close(); sink1.checkCounts(1, 1); //now resume the tailer to get the first 50 items final ChronicleSink sink2 = new ChronicleSink( ChronicleQueueBuilder.vanilla(sinkBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build(), "localhost", 8888); //Take the tailer to the last index (item 50) and start reading from there. final ExcerptTailer tailer2 = sink2.createTailer().toEnd(); assertEquals(1000000000 + 49, tailer2.parseLong()); tailer2.finish(); System.out.println("Sink2 restarting to continue to read the next 50 items"); for(int count=50 ; count < 100 ; ) { if(tailer2.nextIndex()) { assertEquals(1000000000 + count, tailer2.parseLong()); tailer2.finish(); count++; } } tailer2.close(); sink2.close(); sink2.checkCounts(1, 1); sink2.clear(); source.close(); source.checkCounts(1, 1); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); } #location 30 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSourceSinkStartResumeRollingEverySecond() throws Exception { //This is the config that is required to make the VanillaChronicle roll every second final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); assertNotNull(sourceBasePath); assertNotNull(sinkBasePath); final Chronicle source = ChronicleQueueBuilder.source( ChronicleQueueBuilder.vanilla(sourceBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build()) .bindAddress("localhost", BASE_PORT + 104) .build(); ExcerptAppender appender = source.createAppender(); System.out.print("writing 100 items will take take 10 seconds."); for (int i = 0; i < 100; i++) { appender.startExcerpt(); int value = 1000000000 + i; appender.append(value).append(' '); //this space is really important. appender.finish(); Thread.sleep(100); if(i % 10==0) { System.out.print("."); } } appender.close(); System.out.print("\n"); //create a tailer to get the first 50 items then exit the tailer final Chronicle sink1 = ChronicleQueueBuilder.sink( ChronicleQueueBuilder.vanilla(sinkBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build()) .connectAddress("localhost", BASE_PORT + 104) .build(); final ExcerptTailer tailer1 = sink1.createTailer().toStart(); System.out.println("Sink1 reading first 50 items then stopping"); for( int count=0; count < 50 ;) { if(tailer1.nextIndex()) { assertEquals(1000000000 + count, tailer1.parseLong()); tailer1.finish(); count++; } } tailer1.close(); sink1.close(); //TODO: fix sink1.checkCounts(1, 1); //now resume the tailer to get the first 50 items final Chronicle sink2 = ChronicleQueueBuilder.sink( ChronicleQueueBuilder.vanilla(sinkBasePath) .entriesPerCycle(1L << 20) .cycleLength(1000, false) .cycleFormat("yyyyMMddHHmmss") .indexBlockSize(16L << 10) .build()) .connectAddress("localhost", BASE_PORT + 104) .build(); //Take the tailer to the last index (item 50) and start reading from there. final ExcerptTailer tailer2 = sink2.createTailer().toEnd(); assertEquals(1000000000 + 49, tailer2.parseLong()); tailer2.finish(); System.out.println("Sink2 restarting to continue to read the next 50 items"); for(int count=50 ; count < 100 ; ) { if(tailer2.nextIndex()) { assertEquals(1000000000 + count, tailer2.parseLong()); tailer2.finish(); count++; } } tailer2.close(); sink2.close(); //TODO: fix sink2.checkCounts(1, 1); sink2.clear(); source.close(); //TODO: fix source.checkCounts(1, 1); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPricePublishing1() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 2); final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 2); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); reader.read(); long start = System.nanoTime(); int prices = 12000000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) { reader.read(); } long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testPricePublishing1() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource) .source() .bindAddress(BASE_PORT + 2) .build(); final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink) .sink() .connectAddress("localhost", BASE_PORT + 2) .build(); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); reader.read(); long start = System.nanoTime(); int prices = 12000000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) { reader.read(); } long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testOverTCP() throws IOException, InterruptedException { String baseDir = System.getProperty("java.io.tmpdir"); String srcBasePath = baseDir + "/IPCT.testOverTCP.source"; ChronicleTools.deleteOnExit(srcBasePath); // NOTE: the sink and source must have different chronicle files. // TODO, make more robust. final int messages = 2 * 1000 * 1000; ChronicleConfig config = ChronicleConfig.DEFAULT.clone(); // config.dataBlockSize(4096); // config.indexBlockSize(4096); final Chronicle source = new InProcessChronicleSource(new IndexedChronicle(srcBasePath, config), PORT + 1); Thread t = new Thread(new Runnable() { @Override public void run() { try { // PosixJNAAffinity.INSTANCE.setAffinity(1 << 1); ExcerptAppender excerpt = source.createAppender(); for (int i = 1; i <= messages; i++) { // use a size which will cause mis-alignment. excerpt.startExcerpt(); excerpt.writeLong(i); excerpt.append(' '); excerpt.append(i); excerpt.append('\n'); excerpt.finish(); } System.out.println(System.currentTimeMillis() + ": Finished writing messages"); } catch (Exception e) { throw new AssertionError(e); } } }); // PosixJNAAffinity.INSTANCE.setAffinity(1 << 2); String snkBasePath = baseDir + "/IPCT.testOverTCP.sink"; ChronicleTools.deleteOnExit(snkBasePath); Chronicle sink = new InProcessChronicleSink(new IndexedChronicle(snkBasePath, config), "localhost", PORT + 1); long start = System.nanoTime(); t.start(); ExcerptTailer excerpt = sink.createTailer(); int count = 0; for (int i = 1; i <= messages; i++) { while (!excerpt.nextIndex()) count++; long n = excerpt.readLong(); String text = excerpt.parseUTF(StopCharTesters.CONTROL_STOP); if (i != n) assertEquals('\'' + text + '\'', i, n); excerpt.finish(); } sink.close(); System.out.println("There were " + count + " isSync messages"); t.join(); source.close(); long time = System.nanoTime() - start; System.out.printf("Messages per second %,d%n", (int) (messages * 1e9 / time)); } #location 38 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testOverTCP() throws IOException, InterruptedException { String baseDir = System.getProperty("java.io.tmpdir"); String srcBasePath = baseDir + "/IPCT.testOverTCP.source"; ChronicleTools.deleteOnExit(srcBasePath); // NOTE: the sink and source must have different chronicle files. // TODO, make more robust. final int messages = 5 * 1000 * 1000; ChronicleConfig config = ChronicleConfig.DEFAULT.clone(); // config.dataBlockSize(4096); // config.indexBlockSize(4096); final IndexedChronicle underlying = new IndexedChronicle(srcBasePath/*, config*/); final Chronicle source = new InProcessChronicleSource(underlying, PORT + 1); Thread t = new Thread(new Runnable() { @Override public void run() { try { // PosixJNAAffinity.INSTANCE.setAffinity(1 << 1); ExcerptAppender excerpt = source.createAppender(); for (int i = 1; i <= messages; i++) { // use a size which will cause mis-alignment. excerpt.startExcerpt(); excerpt.writeLong(i); excerpt.append(' '); excerpt.append(i); excerpt.append('\n'); excerpt.finish(); } System.out.println(System.currentTimeMillis() + ": Finished writing messages"); } catch (Exception e) { throw new AssertionError(e); } } }); // PosixJNAAffinity.INSTANCE.setAffinity(1 << 2); String snkBasePath = baseDir + "/IPCT.testOverTCP.sink"; ChronicleTools.deleteOnExit(snkBasePath); final IndexedChronicle underlying2 = new IndexedChronicle(snkBasePath/*, config*/); Chronicle sink = new InProcessChronicleSink(underlying2, "localhost", PORT + 1); long start = System.nanoTime(); t.start(); ExcerptTailer excerpt = sink.createTailer(); int count = 0; for (int i = 1; i <= messages; i++) { while (!excerpt.nextIndex()) count++; long n = excerpt.readLong(); String text = excerpt.parseUTF(StopCharTesters.CONTROL_STOP); if (i != n) assertEquals('\'' + text + '\'', i, n); excerpt.finish(); } sink.close(); System.out.println("There were " + count + " isSync messages"); t.join(); source.close(); long time = System.nanoTime() - start; System.out.printf("Messages per second %,d%n", (int) (messages * 1e9 / time)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReplication1() throws IOException { final int RUNS = 100; final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); final ChronicleSource source = new ChronicleSource(new VanillaChronicle(sourceBasePath), 0); final ChronicleSink sink = new ChronicleSink(new VanillaChronicle(sinkBasePath), "localhost", source.getLocalPort()); try { final ExcerptAppender appender = source.createAppender(); final ExcerptTailer tailer = sink.createTailer(); for (int i = 0; i < RUNS; i++) { appender.startExcerpt(); long value = 1000000000 + i; appender.append(value).append(' '); appender.finish(); while(!tailer.nextIndex()); long val = tailer.parseLong(); //System.out.println("" + val); assertEquals("i: " + i, value, val); assertEquals("i: " + i, 0, tailer.remaining()); tailer.finish(); } appender.close(); tailer.close(); } finally { sink.close(); sink.checkCounts(1, 1); sink.clear(); source.close(); source.checkCounts(1, 1); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); } } #location 32 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testReplication1() throws Exception { final int RUNS = 100; final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); final ChronicleSource source = new ChronicleSource( new VanillaChronicle(sourceBasePath), 0); final ChronicleSink sink = new ChronicleSink( new VanillaChronicle(sinkBasePath), "localhost", source.getLocalPort()); try { final Thread at = new Thread("th-appender") { public void run() { try { final ExcerptAppender appender = source.createAppender(); for (int i = 0; i < RUNS; i++) { appender.startExcerpt(); long value = 1000000000 + i; appender.append(value).append(' '); appender.finish(); } appender.close(); } catch(Exception e) { } } }; final Thread tt = new Thread("th-tailer") { public void run() { try { final ExcerptTailer tailer = sink.createTailer(); for (int i = 0; i < RUNS; i++) { long value = 1000000000 + i; assertTrue(tailer.nextIndex()); long val = tailer.parseLong(); assertEquals("i: " + i, value, val); assertEquals("i: " + i, 0, tailer.remaining()); tailer.finish(); } tailer.close(); } catch(Exception e) { } } }; at.start(); tt.start(); at.join(); tt.join(); } finally { sink.close(); sink.clear(); source.close(); source.clear(); assertFalse(new File(sourceBasePath).exists()); assertFalse(new File(sinkBasePath).exists()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String... ignored) throws IOException { String basePath = TMP + "/ExampleCacheMain"; ChronicleTools.deleteOnExit(basePath); CachePerfMain map = new CachePerfMain(basePath, 32); long start = System.nanoTime(); buildkeylist(keys); StringBuilder name = new StringBuilder(); StringBuilder surname = new StringBuilder(); Person person = new Person(name, surname, 0); for (int i = 0; i < keys; i++) { name.setLength(0); name.append("name"); name.append(i); surname.setLength(0); surname.append("surname"); surname.append(i); person.set_age(i % 100); map.put(i, person); } long end = System.nanoTime(); System.out.printf("Took %.3f secs to add %,d entries%n", (end - start) / 1e9, keys); long duration; for (int i = 0; i < 2; i++) { duration = randomGet(keys, map); System.out.printf(i + "th iter: Took %.3f secs to get seq %,d entries%n", duration / 1e9, keys); } System.out.println("before shuffle"); shufflelist(); System.out.println("after shuffle"); for (int i = 0; i < 2; i++) { System.gc(); duration = randomGet(keys, map); System.out.printf(i + "th iter: Took %.3f secs to get random %,d entries%n", duration / 1e9, keys); } } #location 27 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code public static void main(String... ignored) throws IOException { String basePath = TMP + "/ExampleCacheMain"; ChronicleTools.deleteOnExit(basePath); CachePerfMain map = new CachePerfMain(basePath, 64); buildkeylist(keys); long duration; for (int i = 0; i < 2; i++) { duration = putTest(keys, "base", map); System.out.printf(i + "th iter: Took %.3f secs to put seq %,d entries%n", duration / 1e9, keys); } for (int i = 0; i < 2; i++) { duration = getTest(keys, map); System.out.printf(i + "th iter: Took %.3f secs to get seq %,d entries%n", duration / 1e9, keys); } shufflelist(); for (int i = 0; i < 2; i++) { System.gc(); duration = getTest(keys, map); System.out.printf(i + "th iter: Took %.3f secs to get random %,d entries%n", duration / 1e9, keys); } for (int i = 0; i < 2; i++) { duration = putTest(keys, "modif", map); System.out .printf(i + "th iter: Took %.3f secs to update random %,d entries%n", duration / 1e9, keys); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPricePublishing1() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 2); final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 2); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); reader.read(); long start = System.nanoTime(); int prices = 12000000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) { reader.read(); } long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testPricePublishing1() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource) .source() .bindAddress(BASE_PORT + 2) .build(); final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink) .sink() .connectAddress("localhost", BASE_PORT + 2) .build(); final PriceWriter pw = new PriceWriter(source.createAppender()); final AtomicInteger count = new AtomicInteger(); final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { @Override public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { count.incrementAndGet(); } }); pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); reader.read(); long start = System.nanoTime(); int prices = 12000000; for (int i = 1; i <= prices; i++) { pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); } long mid = System.nanoTime(); while (count.get() < prices) { reader.read(); } long end = System.nanoTime(); System.out.printf("Took an average of %.2f us to write and %.2f us to read%n", (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); source.close(); sink.close(); assertIndexedClean(basePathSource); assertIndexedClean(basePathSink); }
Below is the vulnerable code, please generate the patch based on the following information.