input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code public void leaveRtpSession() { if (this.joined.get()) { this.joined.set(false); /* * When the participant decides to leave the system, tp is reset to tc, the current time, members and pmembers are * initialized to 1, initial is set to 1, we_sent is set to false, senders is set to 0, and avg_rtcp_size is set to * the size of the compound BYE packet. * * The calculated interval T is computed. The BYE packet is then scheduled for time tn = tc + T. */ this.tp = this.statistics.getCurrentTime(); this.statistics.resetMembers(); this.initial.set(true); this.statistics.clearSenders(); // XXX Sending the BYE packet NOW, since channel will be closed - hrosa // long t = this.statistics.rtcpInterval(initial); // this.tn = resolveDelay(t); // this.scheduleRtcp(this.tn, RtcpPacketType.RTCP_BYE); // cancel scheduled task and schedule BYE now if(this.reportTaskFuture != null) { this.reportTaskFuture.cancel(true); } scheduleNow(RtcpPacketType.RTCP_BYE); } } #location 26 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void leaveRtpSession() { if (this.joined.get()) { this.joined.set(false); /* * When the participant decides to leave the system, tp is reset to tc, the current time, members and pmembers are * initialized to 1, initial is set to 1, we_sent is set to false, senders is set to 0, and avg_rtcp_size is set to * the size of the compound BYE packet. * * The calculated interval T is computed. The BYE packet is then scheduled for time tn = tc + T. */ this.tp = this.statistics.getCurrentTime(); this.statistics.resetMembers(); this.initial.set(true); this.statistics.clearSenders(); // XXX Sending the BYE packet NOW, since channel will be closed - hrosa // long t = this.statistics.rtcpInterval(initial); // this.tn = resolveDelay(t); // this.scheduleRtcp(this.tn, RtcpPacketType.RTCP_BYE); // cancel scheduled task and schedule BYE now if(this.reportTaskFuture != null) { this.reportTaskFuture.cancel(true); } // Send BYE // Do not run in separate thread so channel can be properly closed by the owner of this handler this.statistics.setRtcpPacketType(RtcpPacketType.RTCP_BYE); this.scheduledTask = new TxTask(RtcpPacketType.RTCP_BYE); this.scheduledTask.run(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void startMixer() { if (!started) { started = true; output.buffer.clear(); scheduler.submit(mixer,scheduler.MIXER_MIX_QUEUE); mixCount = 0; Iterator<Input> activeInputs=inputs.iterator(); while(activeInputs.hasNext()) activeInputs.next().start(); } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void startMixer() { if (!started) { started = true; output.resetBuffer(); mixCount = 0; Iterator<Input> activeInputs=inputs.iterator(); Input currInput; while(activeInputs.hasNext()) { currInput=activeInputs.next(); currInput.resetBuffer(); currInput.start(); } scheduler.submit(mixer,scheduler.MIXER_MIX_QUEUE); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCodec() throws Exception { boolean testPassed = false; try { final int packetSize = 480; File outputFile = File.createTempFile("opustest", ".tmp"); FileInputStream inputStream = new FileInputStream("src\\test\\resources\\test_sound_mono_48.pcm"); FileOutputStream outputStream = new FileOutputStream(outputFile, false); OpusJni opus = new OpusJni(); opus.initNative(); try { byte[] input = new byte[packetSize]; short[] inputData = new short[packetSize]; byte[] output = new byte[2 * packetSize]; while (inputStream.read(input) == 2 * packetSize) { ByteBuffer.wrap(input).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(inputData); byte[] encodedData = opus.encodeNative(inputData); short[] decodedData = opus.decodeNative(encodedData); ByteBuffer.wrap(output).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(decodedData); outputStream.write(output); } testPassed = true; } finally { inputStream.close(); outputStream.close(); opus.closeNative(); outputFile.delete(); } } catch (IOException exc) { log.error("IOException: " + exc.getMessage()); fail("Opus test file access error"); } assertTrue(testPassed); } #location 33 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testCodec() throws Exception { boolean testPassed = false; try { OpusJni opus = new OpusJni(); opus.initNative(); final int packetSize = 480; File outputFile = File.createTempFile("opustest", ".tmp"); byte[] output = new byte[2 * packetSize]; try (FileInputStream inputStream = new FileInputStream("src\\test\\resources\\test_sound_mono_48.pcm"); FileOutputStream outputStream = new FileOutputStream(outputFile, false)) { byte[] input = new byte[packetSize]; short[] inputData = new short[packetSize]; while (inputStream.read(input) == 2 * packetSize) { ByteBuffer.wrap(input).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(inputData); byte[] encodedData = opus.encodeNative(inputData); short[] decodedData = opus.decodeNative(encodedData); ByteBuffer.wrap(output).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(decodedData); outputStream.write(output); } testPassed = true; } opus.closeNative(); outputFile.delete(); } catch (IOException exc) { log.error("IOException: " + exc.getMessage()); fail("Opus test file access error"); } assertTrue(testPassed); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void harvest(IceMediaStream mediaStream, PortManager portManager, Selector selector) throws HarvestException, NoCandidatesGatheredException { // Safe copy of currently registered harvesters Map<CandidateType, CandidateHarvester> copy; synchronized (this.harvesters) { copy = new HashMap<CandidateType, CandidateHarvester>(this.harvesters); } // Ask each harvester to gather candidates for the media stream // HOST candidates take precedence and are mandatory CandidateHarvester hostHarvester = copy.get(CandidateType.HOST); if (hostHarvester != null) { hostHarvester.harvest(portManager, mediaStream, selector); } else { throw new HarvestException("No HOST harvester registered!"); } // Then comes the SRFLX, which depends on HOST candidates CandidateHarvester srflxHarvester = copy.get(CandidateType.SRFLX); if (srflxHarvester != null) { srflxHarvester.harvest(portManager, mediaStream, selector); } // RELAY candidates come last CandidateHarvester relayHarvester = copy.get(CandidateType.RELAY); if (relayHarvester != null) { relayHarvester.harvest(portManager, mediaStream, selector); } // Verify at least one candidate was gathered if (!mediaStream.hasLocalRtpCandidates()) { throw new NoCandidatesGatheredException("No RTP candidates were gathered for " + mediaStream.getName() + " stream"); } // After harvesting all possible candidates, ask the media stream to // select its default local candidates mediaStream.getRtpComponent().selectDefaultLocalCandidate(); if (mediaStream.supportsRtcp() && !mediaStream.isRtcpMux()) { mediaStream.getRtcpComponent().selectDefaultLocalCandidate(); } } #location 36 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void harvest(IceMediaStream mediaStream, PortManager portManager, Selector selector) throws HarvestException, NoCandidatesGatheredException { // Ask each harvester to gather candidates for the media stream // HOST candidates take precedence and are mandatory CandidateHarvester hostHarvester = harvesters.get(CandidateType.HOST); if (hostHarvester != null) { hostHarvester.harvest(portManager, mediaStream, selector); } else { throw new HarvestException("No HOST harvester registered!"); } // Then comes the SRFLX, which depends on HOST candidates CandidateHarvester srflxHarvester = harvesters.get(CandidateType.SRFLX); if (srflxHarvester != null) { srflxHarvester.harvest(portManager, mediaStream, selector); } // RELAY candidates come last CandidateHarvester relayHarvester = harvesters.get(CandidateType.RELAY); if (relayHarvester != null) { relayHarvester.harvest(portManager, mediaStream, selector); } // Verify at least one candidate was gathered if (!mediaStream.hasLocalRtpCandidates()) { throw new NoCandidatesGatheredException("No RTP candidates were gathered for " + mediaStream.getName() + " stream"); } // After harvesting all possible candidates, ask the media stream to // select its default local candidates mediaStream.getRtpComponent().selectDefaultLocalCandidate(); if (mediaStream.supportsRtcp() && !mediaStream.isRtcpMux()) { mediaStream.getRtcpComponent().selectDefaultLocalCandidate(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 16 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 35 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Frame read(long timestamp) { try { if (queue.size() == 0) { this.ready = false; return null; } //extract packet Frame frame = queue.remove(0); //buffer empty now? - change ready flag. if (queue.size() == 0) { this.ready = false; //arrivalDeadLine = 0; //set it as 1 ms since otherwise will be dropped by pipe frame.setDuration(1); } arrivalDeadLine = rtpClock.convertToRtpTime(frame.getTimestamp() + frame.getDuration()); //convert duration to nanoseconds frame.setDuration(frame.getDuration() * 1000000L); frame.setTimestamp(frame.getTimestamp() * 1000000L); return frame; } finally { LOCK.unlock(); } } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public Frame read(long timestamp) { try { LOCK.lock(); if (queue.size() == 0) { this.ready = false; return null; } //extract packet Frame frame = queue.remove(0); //buffer empty now? - change ready flag. if (queue.size() == 0) { this.ready = false; //arrivalDeadLine = 0; //set it as 1 ms since otherwise will be dropped by pipe frame.setDuration(1); } arrivalDeadLine = rtpClock.convertToRtpTime(frame.getTimestamp() + frame.getDuration()); //convert duration to nanoseconds frame.setDuration(frame.getDuration() * 1000000L); frame.setTimestamp(frame.getTimestamp() * 1000000L); return frame; } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 109 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private byte[] processRequest(StunRequest request, InetSocketAddress localPeer, InetSocketAddress remotePeer) throws IOException { // Produce Binding Response TransportAddress transportAddress = new TransportAddress(remotePeer.getAddress(), remotePeer.getPort(), TransportProtocol.UDP); StunResponse response = StunMessageFactory.createBindingResponse(request, transportAddress); byte[] transactionID = request.getTransactionId(); try { response.setTransactionID(transactionID); } catch (StunException e) { throw new IOException("Illegal STUN Transaction ID: " + new String(transactionID), e); } // The agent MUST use a short-term credential to authenticate the request and perform a message integrity check. UsernameAttribute remoteUnameAttribute; String remoteUsername; // Send binding error response if username is null try { remoteUnameAttribute = (UsernameAttribute) request.getAttribute(StunAttribute.USERNAME); remoteUsername = new String(remoteUnameAttribute.getUsername()); } catch(NullPointerException nullPointer) { response.setMessageType(StunMessage.BINDING_ERROR_RESPONSE); response.addAttribute(StunAttributeFactory.createErrorCodeAttribute(ErrorCodeAttribute.BAD_REQUEST, ErrorCodeAttribute.getDefaultReasonPhrase(ErrorCodeAttribute.BAD_REQUEST))); return response.encode(); } // The agent MUST consider the username to be valid if it consists of two values separated by a colon, where the first // value is equal to the username fragment generated by the agent in an offer or answer for a session in-progress. if (!this.authenticator.validateUsername(remoteUsername)) { // TODO return error response throw new IOException("Invalid username " + remoteUsername); } // The username for the credential is formed by concatenating the username fragment provided by the peer with the // username fragment of the agent sending the request, separated by a colon (":"). int colon = remoteUsername.indexOf(":"); String localUFrag = remoteUsername.substring(0, colon); String remoteUfrag = remoteUsername.substring(colon + 1); // Add USERNAME and MESSAGE-INTEGRITY attribute in the response. // The responses utilize the same usernames and passwords as the requests. String localUsername = remoteUfrag.concat(":").concat(localUFrag); StunAttribute unameAttribute = StunAttributeFactory.createUsernameAttribute(localUsername); response.addAttribute(unameAttribute); byte[] localKey = this.authenticator.getLocalKey(localUFrag); MessageIntegrityAttribute integrityAttribute = StunAttributeFactory.createMessageIntegrityAttribute(remoteUsername, localKey); response.addAttribute(integrityAttribute); // If the client issues a USE-CANDIDATE, tell ICE Agent to select the candidate if (request.containsAttribute(StunAttribute.USE_CANDIDATE)) { if (!this.candidateSelected.get()) { this.candidateSelected.set(true); if (logger.isDebugEnabled()) { logger.debug("Selected candidate " + remotePeer.toString()); } this.iceListener.onSelectedCandidates(new SelectedCandidatesEvent(remotePeer)); } } // Pass response to the server return response.encode(); } #location 20 #vulnerability type NULL_DEREFERENCE
#fixed code private byte[] processRequest(StunRequest request, InetSocketAddress localPeer, InetSocketAddress remotePeer) throws IOException { // Produce Binding Response TransportAddress transportAddress = new TransportAddress(remotePeer.getAddress(), remotePeer.getPort(), TransportProtocol.UDP); StunResponse response = StunMessageFactory.createBindingResponse(request, transportAddress); byte[] transactionID = request.getTransactionId(); try { response.setTransactionID(transactionID); } catch (StunException e) { throw new IOException("Illegal STUN Transaction ID: " + new String(transactionID), e); } // The agent MUST use a short-term credential to authenticate the request and perform a message integrity check. UsernameAttribute remoteUnameAttribute = (UsernameAttribute) request.getAttribute(StunAttribute.USERNAME);; // Send binding error response if username is null if (remoteUnameAttribute.getUsername()==null) { response.setMessageType(StunMessage.BINDING_ERROR_RESPONSE); response.addAttribute(StunAttributeFactory.createErrorCodeAttribute(ErrorCodeAttribute.BAD_REQUEST, ErrorCodeAttribute.getDefaultReasonPhrase(ErrorCodeAttribute.BAD_REQUEST))); return response.encode(); } String remoteUsername = new String(remoteUnameAttribute.getUsername()); // The agent MUST consider the username to be valid if it consists of two values separated by a colon, where the first // value is equal to the username fragment generated by the agent in an offer or answer for a session in-progress. if (!this.authenticator.validateUsername(remoteUsername)) { // TODO return error response throw new IOException("Invalid username " + remoteUsername); } // The username for the credential is formed by concatenating the username fragment provided by the peer with the // username fragment of the agent sending the request, separated by a colon (":"). int colon = remoteUsername.indexOf(":"); String localUFrag = remoteUsername.substring(0, colon); String remoteUfrag = remoteUsername.substring(colon + 1); // Add USERNAME and MESSAGE-INTEGRITY attribute in the response. // The responses utilize the same usernames and passwords as the requests. String localUsername = remoteUfrag.concat(":").concat(localUFrag); StunAttribute unameAttribute = StunAttributeFactory.createUsernameAttribute(localUsername); response.addAttribute(unameAttribute); byte[] localKey = this.authenticator.getLocalKey(localUFrag); MessageIntegrityAttribute integrityAttribute = StunAttributeFactory.createMessageIntegrityAttribute(remoteUsername, localKey); response.addAttribute(integrityAttribute); // If the client issues a USE-CANDIDATE, tell ICE Agent to select the candidate if (request.containsAttribute(StunAttribute.USE_CANDIDATE)) { if (!this.candidateSelected.get()) { this.candidateSelected.set(true); if (logger.isDebugEnabled()) { logger.debug("Selected candidate " + remotePeer.toString()); } this.iceListener.onSelectedCandidates(new SelectedCandidatesEvent(remotePeer)); } } // Pass response to the server return response.encode(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 52 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 29 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String open(String sdp) throws MgcpConnectionException { synchronized (this.stateLock) { switch (this.state) { case CLOSED: case HALF_OPEN: // Update state this.state = MgcpConnectionState.OPEN; // Parse remote SDP try { this.remoteSdp = SessionDescriptionParser.parse(sdp); } catch (SdpException e) { throw new MgcpConnectionException(e.getMessage(), e); } // Open connection openConnection(); if(log.isDebugEnabled()) { log.debug("Connection " + getHexIdentifier() + " state is " + this.state.name()); } // Submit timer if (this.timeout > 0) { expireIn(this.timeout); } break; default: throw new MgcpConnectionException( "Cannot open connection " + this.getHexIdentifier() + " because state is " + this.state.name()); } } return this.localSdp.toString(); } #location 35 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String open(String sdp) throws MgcpConnectionException { synchronized (this.stateLock) { switch (this.state) { case CLOSED: case HALF_OPEN: // Update state this.state = MgcpConnectionState.OPEN; // Parse remote SDP try { this.remoteSdp = SessionDescriptionParser.parse(sdp); } catch (SdpException e) { throw new MgcpConnectionException(e.getMessage(), e); } // Open connection openConnection(); if(log.isDebugEnabled()) { log.debug("Connection " + getHexIdentifier() + " state is " + this.state.name()); } // Submit timer if (this.timeout > 0) { expireIn(this.timeout); } break; default: throw new MgcpConnectionException("Cannot open connection " + this.getHexIdentifier() + " because state is " + this.state.name()); } } return this.localSdp.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 34 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCodec() throws Exception { boolean testPassed = false; try { final int packetSize = 480; File outputFile = File.createTempFile("opustest", ".tmp"); FileInputStream inputStream = new FileInputStream("src\\test\\resources\\test_sound_mono_48.pcm"); FileOutputStream outputStream = new FileOutputStream(outputFile, false); OpusJni opus = new OpusJni(); opus.initNative(); try { byte[] input = new byte[packetSize]; short[] inputData = new short[packetSize]; byte[] output = new byte[2 * packetSize]; while (inputStream.read(input) == 2 * packetSize) { ByteBuffer.wrap(input).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(inputData); byte[] encodedData = opus.encodeNative(inputData); short[] decodedData = opus.decodeNative(encodedData); ByteBuffer.wrap(output).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(decodedData); outputStream.write(output); } testPassed = true; } finally { inputStream.close(); outputStream.close(); opus.closeNative(); outputFile.delete(); } } catch (IOException exc) { log.error("IOException: " + exc.getMessage()); fail("Opus test file access error"); } assertTrue(testPassed); } #location 33 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testCodec() throws Exception { boolean testPassed = false; try { OpusJni opus = new OpusJni(); opus.initNative(); final int packetSize = 480; File outputFile = File.createTempFile("opustest", ".tmp"); byte[] output = new byte[2 * packetSize]; try (FileInputStream inputStream = new FileInputStream("src\\test\\resources\\test_sound_mono_48.pcm"); FileOutputStream outputStream = new FileOutputStream(outputFile, false)) { byte[] input = new byte[packetSize]; short[] inputData = new short[packetSize]; while (inputStream.read(input) == 2 * packetSize) { ByteBuffer.wrap(input).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(inputData); byte[] encodedData = opus.encodeNative(inputData); short[] decodedData = opus.decodeNative(encodedData); ByteBuffer.wrap(output).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(decodedData); outputStream.write(output); } testPassed = true; } opus.closeNative(); outputFile.delete(); } catch (IOException exc) { log.error("IOException: " + exc.getMessage()); fail("Opus test file access error"); } assertTrue(testPassed); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Frame read(long timestamp) { try { if (queue.size() == 0) { this.ready = false; return null; } //extract packet Frame frame = queue.remove(0); //buffer empty now? - change ready flag. if (queue.size() == 0) { this.ready = false; //arrivalDeadLine = 0; //set it as 1 ms since otherwise will be dropped by pipe frame.setDuration(1); } arrivalDeadLine = rtpClock.convertToRtpTime(frame.getTimestamp() + frame.getDuration()); //convert duration to nanoseconds frame.setDuration(frame.getDuration() * 1000000L); frame.setTimestamp(frame.getTimestamp() * 1000000L); return frame; } finally { LOCK.unlock(); } } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public Frame read(long timestamp) { try { LOCK.lock(); if (queue.size() == 0) { this.ready = false; return null; } //extract packet Frame frame = queue.remove(0); //buffer empty now? - change ready flag. if (queue.size() == 0) { this.ready = false; //arrivalDeadLine = 0; //set it as 1 ms since otherwise will be dropped by pipe frame.setDuration(1); } arrivalDeadLine = rtpClock.convertToRtpTime(frame.getTimestamp() + frame.getDuration()); //convert duration to nanoseconds frame.setDuration(frame.getDuration() * 1000000L); frame.setTimestamp(frame.getTimestamp() * 1000000L); return frame; } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void stop() { while (buffer.size() > 0) { buffer.poll().recycle(); } super.stop(); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void stop() { while (buffer.size() > 0) { Frame frame = buffer.poll(); if(frame != null) { frame.recycle(); } } super.stop(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 46 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 41 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void write(RtpPacket packet, RTPFormat format) { // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { LOCK.lock(); droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); LOCK.unlock(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } LOCK.unlock(); // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } #location 111 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void write(RtpPacket packet, RTPFormat format) { try { LOCK.lock(); // checking format if (format == null) { logger.warn("No format specified. Packet dropped!"); return; } if (this.format == null || this.format.getID() != format.getID()) { this.format = format; logger.info("Format has been changed: " + this.format.toString()); } // if this is first packet then synchronize clock if (isn == -1) { rtpClock.synchronize(packet.getTimestamp()); isn = packet.getSeqNumber(); initJitter(packet); } else { estimateJitter(packet); } // update clock rate rtpClock.setClockRate(this.format.getClockRate()); // drop outstanding packets // packet is outstanding if its timestamp of arrived packet is less // then consumer media time if (packet.getTimestamp() < this.arrivalDeadLine) { logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString()); dropCount++; // checking if not dropping too much droppedInRaw++; if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) { arrivalDeadLine = 0; } else { return; } } Frame f = Memory.allocate(packet.getPayloadLength()); // put packet into buffer irrespective of its sequence number f.setHeader(null); f.setSequenceNumber(packet.getSeqNumber()); // here time is in milliseconds f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp())); f.setOffset(0); f.setLength(packet.getPayloadLength()); packet.getPayload(f.getData(), 0); // set format f.setFormat(this.format.getFormat()); // make checks only if have packet if (f != null) { droppedInRaw = 0; // find correct position to insert a packet // use timestamp since its always positive int currIndex = queue.size() - 1; while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) { currIndex--; } // check for duplicate packet if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) { LOCK.unlock(); return; } queue.add(currIndex + 1, f); // recalculate duration of each frame in queue and overall duration // since we could insert the frame in the middle of the queue duration = 0; if (queue.size() > 1) { duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp(); } for (int i = 0; i < queue.size() - 1; i++) { // duration measured by wall clock long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp(); // in case of RFC2833 event timestamp remains same queue.get(i).setDuration(d > 0 ? d : 0); } // if overall duration is negative we have some mess here,try to // reset if (duration < 0 && queue.size() > 1) { logger.warn("Something messy happened. Reseting jitter buffer!"); reset(); return; } // overflow? // only now remove packet if overflow , possibly the same packet we just received if (queue.size() > QUEUE_SIZE) { logger.warn("Buffer overflow!"); dropCount++; queue.remove(0).recycle(); } // check if this buffer already full if (!ready) { ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1); if (ready && listener != null) { listener.onFill(); } } } } finally { LOCK.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int count() { return this.count; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public int count() { return this.count; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private byte[] processRequest(StunRequest request, InetSocketAddress localPeer, InetSocketAddress remotePeer) throws IOException { /* * The agent MUST use a short-term credential to authenticate the * request and perform a message integrity check. */ // Produce Binding Response TransportAddress transportAddress = new TransportAddress(remotePeer.getAddress(), remotePeer.getPort(), TransportProtocol.UDP); StunResponse response = StunMessageFactory.createBindingResponse(request, transportAddress); byte[] transactionID = request.getTransactionId(); try { response.setTransactionID(transactionID); } catch (StunException e) { throw new IOException("Illegal STUN Transaction ID: " + new String(transactionID), e); } UsernameAttribute remoteUnameAttribute; String remoteUsername; // Send binding error response if username is null try { remoteUnameAttribute = (UsernameAttribute) request.getAttribute(StunAttribute.USERNAME); remoteUsername = new String(remoteUnameAttribute.getUsername()); } catch(NullPointerException nullPointer) { response.setMessageType(StunMessage.BINDING_ERROR_RESPONSE); response.addAttribute(StunAttributeFactory.createErrorCodeAttribute(ErrorCodeAttribute.BAD_REQUEST, ErrorCodeAttribute.getDefaultReasonPhrase(ErrorCodeAttribute.BAD_REQUEST))); return response.encode(); } /* * The agent MUST consider the username to be valid if it consists of * two values separated by a colon, where the first value is equal to * the username fragment generated by the agent in an offer or answer * for a session in-progress. */ if(!this.iceAuthenticator.validateUsername(remoteUsername)) { // TODO return error response throw new IOException("Invalid username "+ remoteUsername); } /* * The username for the credential is formed by concatenating the * username fragment provided by the peer with the username fragment of * the agent sending the request, separated by a colon (":"). */ int colon = remoteUsername.indexOf(":"); String localUFrag = remoteUsername.substring(0, colon); String remoteUfrag = remoteUsername.substring(colon); /* * An agent MUST include the PRIORITY attribute in its Binding request. * This priority value will be computed identically to how the priority * for the local candidate of the pair was computed, except that the * type preference is set to the value for peer reflexive candidate * types */ long priority = extractPriority(request); /* * Add USERNAME and MESSAGE-INTEGRITY attribute in the response. The * responses utilize the same usernames and passwords as the requests */ String localUsername = remoteUfrag.concat(":").concat(localUFrag); StunAttribute unameAttribute = StunAttributeFactory.createUsernameAttribute(localUsername); response.addAttribute(unameAttribute); byte[] localKey = this.iceAuthenticator.getLocalKey(localUFrag); MessageIntegrityAttribute messageIntegrityAttribute = StunAttributeFactory.createMessageIntegrityAttribute(remoteUsername, localKey); response.addAttribute(messageIntegrityAttribute); // If the client issues a USE-CANDIDATE, tell ICE Agent to select the candidate if (request.containsAttribute(StunAttribute.USE_CANDIDATE)) { fireStunBindingEvent(localPeer, remotePeer); } // Pass response to the server return response.encode(); } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code private byte[] processRequest(StunRequest request, InetSocketAddress localPeer, InetSocketAddress remotePeer) throws IOException { /* * The agent MUST use a short-term credential to authenticate the * request and perform a message integrity check. */ // Produce Binding Response TransportAddress transportAddress = new TransportAddress(remotePeer.getAddress(), remotePeer.getPort(), TransportProtocol.UDP); StunResponse response = StunMessageFactory.createBindingResponse(request, transportAddress); byte[] transactionID = request.getTransactionId(); try { response.setTransactionID(transactionID); } catch (StunException e) { throw new IOException("Illegal STUN Transaction ID: " + new String(transactionID), e); } UsernameAttribute remoteUnameAttribute = (UsernameAttribute) request.getAttribute(StunAttribute.USERNAME); // Send binding error response if username is null if (remoteUnameAttribute.getUsername()== null) { response.setMessageType(StunMessage.BINDING_ERROR_RESPONSE); response.addAttribute(StunAttributeFactory.createErrorCodeAttribute(ErrorCodeAttribute.BAD_REQUEST, ErrorCodeAttribute.getDefaultReasonPhrase(ErrorCodeAttribute.BAD_REQUEST))); return response.encode(); } String remoteUsername = new String(remoteUnameAttribute.getUsername()); /* * The agent MUST consider the username to be valid if it consists of * two values separated by a colon, where the first value is equal to * the username fragment generated by the agent in an offer or answer * for a session in-progress. */ if(!this.iceAuthenticator.validateUsername(remoteUsername)) { // TODO return error response throw new IOException("Invalid username "+ remoteUsername); } /* * The username for the credential is formed by concatenating the * username fragment provided by the peer with the username fragment of * the agent sending the request, separated by a colon (":"). */ int colon = remoteUsername.indexOf(":"); String localUFrag = remoteUsername.substring(0, colon); String remoteUfrag = remoteUsername.substring(colon); /* * An agent MUST include the PRIORITY attribute in its Binding request. * This priority value will be computed identically to how the priority * for the local candidate of the pair was computed, except that the * type preference is set to the value for peer reflexive candidate * types */ long priority = extractPriority(request); /* * Add USERNAME and MESSAGE-INTEGRITY attribute in the response. The * responses utilize the same usernames and passwords as the requests */ String localUsername = remoteUfrag.concat(":").concat(localUFrag); StunAttribute unameAttribute = StunAttributeFactory.createUsernameAttribute(localUsername); response.addAttribute(unameAttribute); byte[] localKey = this.iceAuthenticator.getLocalKey(localUFrag); MessageIntegrityAttribute messageIntegrityAttribute = StunAttributeFactory.createMessageIntegrityAttribute(remoteUsername, localKey); response.addAttribute(messageIntegrityAttribute); // If the client issues a USE-CANDIDATE, tell ICE Agent to select the candidate if (request.containsAttribute(StunAttribute.USE_CANDIDATE)) { fireStunBindingEvent(localPeer, remotePeer); } // Pass response to the server return response.encode(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void train(String dataFile, int maxite, float c) throws IOException { fp = File.createTempFile("train-features", null, new File("./tmp/")); buildInstanceList(dataFile); LabelAlphabet postagAlphabet = factory.buildLabelAlphabet("postag"); IFeatureAlphabet features = factory.DefaultFeatureAlphabet(); SFGenerator generator = new SFGenerator(); Linear[] models = new Linear[postagAlphabet.size()]; int fsize = features.size(); for (int i = 0; i < postagAlphabet.size(); i++) { String pos = postagAlphabet.lookupString(i); InstanceSet instset = readInstanceSet(pos); LabelAlphabet alphabet = factory.buildLabelAlphabet(pos); int ysize = alphabet.size(); System.out.printf("Training with data: %s\n", pos); System.out.printf("Number of labels: %d\n", ysize); LinearMax solver = new LinearMax(generator, ysize); ZeroOneLoss loss = new ZeroOneLoss(); Update update = new LinearMaxPAUpdate(loss); OnlineTrainer trainer = new OnlineTrainer(solver, update, loss, fsize, maxite, c); models[i] = trainer.train(instset, null); instset = null; solver = null; loss = null; trainer = null; System.out.println(); } factory.setStopIncrement(true); saveModels(modelfile, models,factory); fp.delete(); fp = null; } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code public void train(String dataFile, int maxite, float c) throws IOException { fp = File.createTempFile("train-features", null, new File("./tmp/")); buildInstanceList(dataFile); LabelAlphabet postagAlphabet = factory.buildLabelAlphabet("postag"); SFGenerator generator = new SFGenerator(); Linear[] models = new Linear[postagAlphabet.size()]; for (int i = 0; i < postagAlphabet.size(); i++) { String pos = postagAlphabet.lookupString(i); InstanceSet instset = readInstanceSet(pos); LabelAlphabet alphabet = factory.buildLabelAlphabet(pos); int ysize = alphabet.size(); System.out.printf("Training with data: %s\n", pos); System.out.printf("Number of labels: %d\n", ysize); LinearMax solver = new LinearMax(generator, ysize); ZeroOneLoss loss = new ZeroOneLoss(); Update update = new LinearMaxPAUpdate(loss); OnlineTrainer trainer = new OnlineTrainer(solver, update, loss, factory, maxite, c); models[i] = trainer.train(instset, null); instset = null; solver = null; loss = null; trainer = null; System.out.println(); } factory.setStopIncrement(true); saveModels(modelfile, models,factory); fp.delete(); fp = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { try { String ls_1; Process process =null; File handle = new File("./tmpdata/ctb/data3"); BufferedWriter bout = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("./tmpdata/malt.train"), "UTF-8")); for (File sub : Arrays.asList(handle.listFiles())){ String str = sub.getAbsolutePath(); process = Runtime.getRuntime().exec("cmd /c java -jar ./tmpdata/ctb/Penn2Malt.jar "+str+" ./tmpdata/ctb/headrules.txt 3 2 chtb"); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream())); while ( (ls_1=bufferedReader.readLine()) != null) { System.out.println(ls_1); } } } catch(IOException e) { System.err.println(e); } } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) { try { String ls_1; Process process =null; // File handle = new File("../tmp/ctb_v1/data"); File handle = new File("../tmp/ctb_v6/data/bracketed"); BufferedWriter bout = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("../tmp/malt.train"), "UTF-8")); for (File sub : Arrays.asList(handle.listFiles())){ String file = sub.getAbsolutePath(); if(!file.endsWith(".fid")) continue; clean(file); process = Runtime.getRuntime().exec("cmd /c java -jar ../tmp/Penn2Malt.jar "+file+" ../tmp/headrules.txt 3 2 chtb"); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream())); while ( (ls_1=bufferedReader.readLine()) != null) { System.out.println(ls_1); } bufferedReader = new BufferedReader( new InputStreamReader(process.getErrorStream())); while ( (ls_1=bufferedReader.readLine()) != null) { System.out.println(ls_1); } } } catch(IOException e) { System.err.println(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private InstanceSet buildInstanceList(String file) throws IOException { System.out.print("生成训练数据 ..."); FNLPReader reader = new FNLPReader(file); InstanceSet instset = new InstanceSet(); LabelAlphabet la = factory.DefaultLabelAlphabet(); int count = 0; while (reader.hasNext()) { Sentence sent = (Sentence) reader.next(); // int[] heads = (int[]) instance.getTarget(); String depClass = null; Target targets = (Target)sent.getTarget(); JointParsingState state = new JointParsingState(sent); while (!state.isFinalState()) { // 左右焦点词在句子中的位置 int[] lr = state.getFocusIndices(); ArrayList<String> features = state.getFeatures(); JointParsingState.Action action = getAction(lr[0], lr[1], targets); switch (action) { case LEFT: depClass = targets.getDepClass(lr[1]); break; case RIGHT: depClass = targets.getDepClass(lr[0]); break; default: } state.next(action,depClass); if (action == JointParsingState.Action.LEFT) targets.setHeads(lr[1],-1); if (action == JointParsingState.Action.RIGHT) targets.setHeads(lr[0],-1); String label = ""; switch (action) { case LEFT: label += "L"+sent.getDepClass(lr[1]); break; case RIGHT: label+="R"+sent.getDepClass(lr[0]); break; default: label = "S"; } int id = la.lookupIndex(label); Instance inst = new Instance(); inst.setTarget(id); inst.setData(features); instset.add(inst); } count++; // System.out.println(count); } la.setStopIncrement(true); //重新生成特征 int ysize = la.size(); IFeatureAlphabet fa = factory.DefaultFeatureAlphabet(); for(Instance inst:instset){ ArrayList<String> data = (ArrayList<String>) inst.getData(); int[] idx = JointParser.addFeature(fa, data, ysize); inst.setData(idx); } instset.setAlphabetFactory(factory); System.out.printf("共生成实例:%d个\n", count); return instset; } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code private InstanceSet buildInstanceList(String file) throws IOException { System.out.print("生成训练数据 ..."); FNLPReader reader = new FNLPReader(file); FNLPReader preReader = new FNLPReader(file); InstanceSet instset = new InstanceSet(); LabelAlphabet la = factory.DefaultLabelAlphabet(); IFeatureAlphabet fa = factory.DefaultFeatureAlphabet(); int count = 0; //preReader为了把ysize定下来 la.lookupIndex("S"); while(preReader.hasNext()){ Sentence sent = (Sentence) preReader.next(); Target targets = (Target)sent.getTarget(); for(int i=0; i<sent.length(); i++){ String label; if(targets.getHead(i) != -1){ if(targets.getHead(i) < i){ label = "L" + targets.getDepClass(i); } //else if(targets.getHead(i) > i){ else{ label = "R" + targets.getDepClass(i); } la.lookupIndex(label); } } } int ysize = la.size(); la.setStopIncrement(true); while (reader.hasNext()) { Sentence sent = (Sentence) reader.next(); // int[] heads = (int[]) instance.getTarget(); String depClass = null; Target targets = (Target)sent.getTarget(); JointParsingState state = new JointParsingState(sent); while (!state.isFinalState()) { // 左右焦点词在句子中的位置 int[] lr = state.getFocusIndices(); ArrayList<String> features = state.getFeatures(); JointParsingState.Action action = getAction(lr[0], lr[1], targets); switch (action) { case LEFT: depClass = targets.getDepClass(lr[1]); break; case RIGHT: depClass = targets.getDepClass(lr[0]); break; default: } state.next(action,depClass); if (action == JointParsingState.Action.LEFT) targets.setHeads(lr[1],-1); if (action == JointParsingState.Action.RIGHT) targets.setHeads(lr[0],-1); String label = ""; switch (action) { case LEFT: label += "L"+sent.getDepClass(lr[1]); break; case RIGHT: label+="R"+sent.getDepClass(lr[0]); break; default: label = "S"; } int id = la.lookupIndex(label); Instance inst = new Instance(); inst.setTarget(id); int[] idx = JointParser.addFeature(fa, features, ysize); inst.setData(idx); instset.add(inst); } count++; // System.out.println(count); } instset.setAlphabetFactory(factory); System.out.printf("共生成实例:%d个\n", count); return instset; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { try { String ls_1; Process process =null; File handle = new File("./tmpdata/ctb/data3"); BufferedWriter bout = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("./tmpdata/malt.train"), "UTF-8")); for (File sub : Arrays.asList(handle.listFiles())){ String str = sub.getAbsolutePath(); process = Runtime.getRuntime().exec("cmd /c java -jar ./tmpdata/ctb/Penn2Malt.jar "+str+" ./tmpdata/ctb/headrules.txt 3 2 chtb"); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream())); while ( (ls_1=bufferedReader.readLine()) != null) { System.out.println(ls_1); } } } catch(IOException e) { System.err.println(e); } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) { try { String ls_1; Process process =null; // File handle = new File("../tmp/ctb_v1/data"); File handle = new File("../tmp/ctb_v6/data/bracketed"); BufferedWriter bout = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("../tmp/malt.train"), "UTF-8")); for (File sub : Arrays.asList(handle.listFiles())){ String file = sub.getAbsolutePath(); if(!file.endsWith(".fid")) continue; clean(file); process = Runtime.getRuntime().exec("cmd /c java -jar ../tmp/Penn2Malt.jar "+file+" ../tmp/headrules.txt 3 2 chtb"); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream())); while ( (ls_1=bufferedReader.readLine()) != null) { System.out.println(ls_1); } bufferedReader = new BufferedReader( new InputStreamReader(process.getErrorStream())); while ( (ls_1=bufferedReader.readLine()) != null) { System.out.println(ls_1); } } } catch(IOException e) { System.err.println(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void train(String dataFile, int maxite, float c) throws IOException { InstanceSet instset = buildInstanceList(dataFile); IFeatureAlphabet features = factory.DefaultFeatureAlphabet(); SFGenerator generator = new SFGenerator(); int fsize = features.size(); LabelAlphabet la = factory.DefaultLabelAlphabet(); int ysize = la.size(); System.out.printf("开始训练"); LinearMax solver = new LinearMax(generator, ysize); ZeroOneLoss loss = new ZeroOneLoss(); Update update = new LinearMaxPAUpdate(loss); OnlineTrainer trainer = new OnlineTrainer(solver, update, loss, fsize, maxite, c); Linear models = trainer.train(instset, null); instset = null; solver = null; loss = null; trainer = null; System.out.println(); factory.setStopIncrement(true); models.saveTo(modelfile); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public void train(String dataFile, int maxite, float c) throws IOException { InstanceSet instset = buildInstanceList(dataFile); SFGenerator generator = new SFGenerator(); LabelAlphabet la = factory.DefaultLabelAlphabet(); int ysize = la.size(); System.out.printf("开始训练"); LinearMax solver = new LinearMax(generator, ysize); ZeroOneLoss loss = new ZeroOneLoss(); Update update = new LinearMaxPAUpdate(loss); OnlineTrainer trainer = new OnlineTrainer(solver, update, loss, factory, maxite, c); Linear models = trainer.train(instset, null); instset = null; solver = null; loss = null; trainer = null; System.out.println(); factory.setStopIncrement(true); models.saveTo(modelfile); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testStartNewSpanSampleNullNotPartOfExistingSpan() { final ServerSpan mockServerSpan = mock(ServerSpan.class); when(mockServerSpan.getSpan()).thenReturn(null); when(mockState.sample()).thenReturn(null); when(mockState.getCurrentServerSpan()).thenReturn(mockServerSpan); when(mockRandom.nextLong()).thenReturn(1l).thenReturn(2l); final SpanId newSpanId = clientTracer.startNewSpan(REQUEST_NAME); assertNotNull(newSpanId); assertEquals(1l, newSpanId.getTraceId()); assertEquals(1l, newSpanId.getSpanId()); assertNull(newSpanId.getParentSpanId()); final Span expectedSpan = new Span(); expectedSpan.setTrace_id(1); expectedSpan.setId(1); expectedSpan.setName(REQUEST_NAME); verify(mockState).sample(); verify(mockTraceFilter).trace(REQUEST_NAME); verify(mockTraceFilter2).trace(REQUEST_NAME); verify(mockRandom, times(1)).nextLong(); verify(mockState).getCurrentServerSpan(); verify(mockState).setCurrentClientSpan(expectedSpan); verifyNoMoreInteractions(mockState, mockRandom, mockCollector, mockTraceFilter, mockTraceFilter2); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testStartNewSpanSampleNullNotPartOfExistingSpan() { final ServerSpan mockServerSpan = mock(ServerSpan.class); when(mockServerSpan.getSpan()).thenReturn(null); when(mockState.sample()).thenReturn(null); when(mockState.getCurrentServerSpan()).thenReturn(mockServerSpan); when(mockRandom.nextLong()).thenReturn(TRACE_ID).thenReturn(2l); final SpanId newSpanId = clientTracer.startNewSpan(REQUEST_NAME); assertNotNull(newSpanId); assertEquals(TRACE_ID, newSpanId.getTraceId()); assertEquals(TRACE_ID, newSpanId.getSpanId()); assertNull(newSpanId.getParentSpanId()); final Span expectedSpan = new Span(); expectedSpan.setTrace_id(TRACE_ID); expectedSpan.setId(TRACE_ID); expectedSpan.setName(REQUEST_NAME); verify(mockState).sample(); verify(mockTraceFilter).trace(TRACE_ID, REQUEST_NAME); verify(mockTraceFilter2).trace(TRACE_ID, REQUEST_NAME); verify(mockRandom, times(1)).nextLong(); verify(mockState).getCurrentServerSpan(); verify(mockState).setCurrentClientSpan(expectedSpan); verifyNoMoreInteractions(mockState, mockRandom, mockCollector, mockTraceFilter, mockTraceFilter2); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void finishSpan() { Span finished = new Span().setTimestamp(1000L); // set in start span finished.startTick = 500000L; // set in start span state.setCurrentLocalSpan(finished); PowerMockito.when(System.nanoTime()).thenReturn(1000000L); localTracer.finishSpan(); verify(mockCollector).collect(finished); verifyNoMoreInteractions(mockCollector); assertEquals(500L, finished.getDuration().longValue()); } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void finishSpan() { Span finished = new Span().setName("foo").setTimestamp(1000L); // set in start span finished.startTick = 500000L; // set in start span state.setCurrentLocalSpan(finished); PowerMockito.when(System.nanoTime()).thenReturn(1000000L); localTracer.finishSpan(); verify(mockReporter).report(finished.toZipkin()); verifyNoMoreInteractions(mockReporter); assertEquals(500L, finished.getDuration().longValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public T call() throws Exception { serverSpanThreadBinder().setCurrentSpan(currentServerSpan()); final long start = System.currentTimeMillis(); try { return wrappedCallable().call(); } finally { final long duration = System.currentTimeMillis() - start; currentServerSpan().incThreadDuration(duration); } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public T call() throws Exception { serverSpanThreadBinder().setCurrentSpan(currentServerSpan()); return wrappedCallable().call(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void recordClientSentAnnotations(Endpoint serverAddress) { if (serverAddress == null) { clientTracer.setClientSent(); } else { clientTracer.setClientSent(serverAddress.ipv4, serverAddress.port, serverAddress.service_name); } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code private void recordClientSentAnnotations(Endpoint serverAddress) { if (serverAddress == null) { clientTracer.setClientSent(); } else { clientTracer.setClientSent(serverAddress); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void finishSpan_userSuppliedTimestamp() { Span finished = new Span().setTimestamp(1000L); // Set by user state.setCurrentLocalSpan(finished); PowerMockito.when(System.currentTimeMillis()).thenReturn(2L); localTracer.finishSpan(); verify(mockCollector).collect(finished); verifyNoMoreInteractions(mockCollector); assertEquals(1000L, finished.getDuration().longValue()); } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void finishSpan_userSuppliedTimestamp() { Span finished = new Span().setName("foo").setTimestamp(1000L); // Set by user state.setCurrentLocalSpan(finished); PowerMockito.when(System.currentTimeMillis()).thenReturn(2L); localTracer.finishSpan(); verify(mockReporter).report(finished.toZipkin()); verifyNoMoreInteractions(mockReporter); assertEquals(1000L, finished.getDuration().longValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void finishSpan_userSuppliedTimestampAndDuration() { Span finished = new Span().setTimestamp(1000L); // Set by user state.setCurrentLocalSpan(finished); localTracer.finishSpan(500L); verify(mockCollector).collect(finished); verifyNoMoreInteractions(mockCollector); assertEquals(500L, finished.getDuration().longValue()); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void finishSpan_userSuppliedTimestampAndDuration() { Span finished = new Span().setName("foo").setTimestamp(1000L); // Set by user state.setCurrentLocalSpan(finished); localTracer.finishSpan(500L); verify(mockReporter).report(finished.toZipkin()); verifyNoMoreInteractions(mockReporter); assertEquals(500L, finished.getDuration().longValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void finishSpan_lessThanMicrosRoundUp() { Span finished = new Span().setTimestamp(1000L); // set in start span finished.startTick = 500L; // set in start span state.setCurrentLocalSpan(finished); PowerMockito.when(System.nanoTime()).thenReturn(1000L); localTracer.finishSpan(); verify(mockCollector).collect(finished); verifyNoMoreInteractions(mockCollector); assertEquals(1L, finished.getDuration().longValue()); } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void finishSpan_lessThanMicrosRoundUp() { Span finished = new Span().setName("foo").setTimestamp(1000L); // set in start span finished.startTick = 500L; // set in start span state.setCurrentLocalSpan(finished); PowerMockito.when(System.nanoTime()).thenReturn(1000L); localTracer.finishSpan(); verify(mockReporter).report(finished.toZipkin()); verifyNoMoreInteractions(mockReporter); assertEquals(1L, finished.getDuration().longValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void finishSpan_userSuppliedDuration() { Span finished = new Span().setTimestamp(1000L); // set in start span finished.startTick = 500L; // set in start span state.setCurrentLocalSpan(finished); localTracer.finishSpan(500L); verify(mockCollector).collect(finished); verifyNoMoreInteractions(mockCollector); assertEquals(500L, finished.getDuration().longValue()); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void finishSpan_userSuppliedDuration() { Span finished = new Span().setName("foo").setTimestamp(1000L); // set in start span finished.startTick = 500L; // set in start span state.setCurrentLocalSpan(finished); localTracer.finishSpan(500L); verify(mockReporter).report(finished.toZipkin()); verifyNoMoreInteractions(mockReporter); assertEquals(500L, finished.getDuration().longValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { serverSpanThreadBinder().setCurrentSpan(currentServerSpan()); final long start = System.currentTimeMillis(); try { wrappedRunnable().run(); } finally { final long duration = System.currentTimeMillis() - start; currentServerSpan().incThreadDuration(duration); } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void run() { serverSpanThreadBinder().setCurrentSpan(currentServerSpan()); wrappedRunnable().run(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected boolean checkQuiesceLock() { final String methodName = "checkQuiesceLock"; // if (quiescing && actualInFlight == 0 && pendingFlows.size() == 0 && // inFlightPubRels == 0 && callback.isQuiesced()) { int tokC = tokenStore.count(); if (quiescing && tokC == 0 && pendingFlows.size() == 0 && callback.isQuiesced()) { // @TRACE 626=quiescing={0} actualInFlight={1} pendingFlows={2} // inFlightPubRels={3} callbackQuiesce={4} tokens={5} log.fine(CLASS_NAME, methodName, "626", new Object[] { new Boolean(quiescing), Integer.valueOf(actualInFlight), Integer.valueOf(pendingFlows.size()), Integer.valueOf(inFlightPubRels), Boolean.valueOf(callback.isQuiesced()), Integer.valueOf(tokC) }); synchronized (quiesceLock) { quiesceLock.notifyAll(); } return true; } return false; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected boolean checkQuiesceLock() { final String methodName = "checkQuiesceLock"; // if (quiescing && actualInFlight == 0 && pendingFlows.size() == 0 && // inFlightPubRels == 0 && callback.isQuiesced()) { int tokC = tokenStore.count(); if (quiescing && tokC == 0 && pendingFlows.size() == 0 && callback.isQuiesced()) { // @TRACE 626=quiescing={0} actualInFlight={1} pendingFlows={2} // inFlightPubRels={3} callbackQuiesce={4} tokens={5} log.fine(CLASS_NAME, methodName, "626", new Object[] { Boolean.valueOf(quiescing), Integer.valueOf(actualInFlight), Integer.valueOf(pendingFlows.size()), Integer.valueOf(inFlightPubRels), Boolean.valueOf(callback.isQuiesced()), Integer.valueOf(tokC) }); synchronized (quiesceLock) { quiesceLock.notifyAll(); } return true; } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetStructure() { try { SimpleFormatter sf = new SimpleFormatter(); String delimiter = "/"; String bucket = "maven.kuali.org"; AmazonS3Client client = getClient(); KualiMavenBucketBaseCase baseCase1 = new KualiMavenBucketBaseCase(); baseCase1.setDelimiter(delimiter); baseCase1.setToken("latest"); JavaxServletOnlyBaseCase baseCase2 = new JavaxServletOnlyBaseCase(); baseCase2.setDelimiter(delimiter); baseCase2.setToken("latest"); long start = System.currentTimeMillis(); List<String> prefixes = new ArrayList<String>(); buildPrefixList(client, bucket, prefixes, null, delimiter, baseCase2); long elapsed = System.currentTimeMillis() - start; DefaultMutableTreeNode node = buildTree(prefixes, delimiter); List<DefaultMutableTreeNode> leaves = getLeaves(node); log.info("Total Prefixes: " + prefixes.size()); log.info("Total Time: " + sf.getTime(elapsed)); log.info("Leaves: " + leaves.size()); } catch (Exception e) { e.printStackTrace(); } } #location 20 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testGetStructure() { try { long now = System.currentTimeMillis(); long bytes = Long.MAX_VALUE; SimpleFormatter sf = new SimpleFormatter(); log.info(sf.getSize(bytes)); log.info(sf.getRate(now, bytes)); log.info(sf.getTime(now)); String delimiter = "/"; String bucket = "maven.kuali.org"; AmazonS3Client client = getClient(); KualiMavenBucketBaseCase baseCase1 = new KualiMavenBucketBaseCase(); baseCase1.setDelimiter(delimiter); baseCase1.setToken("latest"); JavaxServletOnlyBaseCase baseCase2 = new JavaxServletOnlyBaseCase(); baseCase2.setDelimiter(delimiter); baseCase2.setToken("latest"); long start = System.currentTimeMillis(); List<String> prefixes = new ArrayList<String>(); buildPrefixList(client, bucket, prefixes, null, delimiter, baseCase2); long elapsed = System.currentTimeMillis() - start; DefaultMutableTreeNode node = buildTree(prefixes, delimiter); List<DefaultMutableTreeNode> leaves = getLeaves(node); log.info("Total Prefixes: " + prefixes.size()); log.info("Total Time: " + sf.getTime(elapsed)); log.info("Leaves: " + leaves.size()); } catch (Exception e) { e.printStackTrace(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void transitionInto(RunState state) { switch (state.state()) { case SUBMITTING: try { final String executionId = dockerRunnerStart(state); // this is racy final Event submitted = Event.submitted(state.workflowInstance(), executionId); try { stateManager.receive(submitted); } catch (StateManager.IsClosed isClosed) { LOG.warn("Could not send 'created' event", isClosed); } } catch (Exception e) { LOG.warn("Failed the docker starting procedure for " + state.workflowInstance().toKey(), e); stateManager.receiveIgnoreClosed(Event.halt(state.workflowInstance())); } break; case TERMINATED: case FAILED: case ERROR: if (state.executionId().isPresent()) { final String executionId = state.executionId().get(); LOG.info("Cleaning up {} pod: {}", state.workflowInstance().toKey(), executionId); dockerRunner.cleanup(executionId); } break; default: // do nothing } } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void transitionInto(RunState state) { switch (state.state()) { case SUBMITTING: try { final String executionId = dockerRunnerStart(state); // this is racy final Event submitted = Event.submitted(state.workflowInstance(), executionId); try { stateManager.receive(submitted); } catch (StateManager.IsClosed isClosed) { LOG.warn("Could not send 'created' event", isClosed); } } catch (ResourceNotFoundException e) { LOG.error("Unable to start docker procedure.", e); stateManager.receiveIgnoreClosed(Event.halt(state.workflowInstance())); } catch (IOException e) { try { LOG.error("Failed the docker starting procedure for " + state.workflowInstance().toKey(), e); stateManager.receive(Event.runError(state.workflowInstance(), e.getMessage())); } catch (StateManager.IsClosed isClosed) { LOG.warn("Failed to send 'runError' event", isClosed); } } break; case TERMINATED: case FAILED: case ERROR: if (state.executionId().isPresent()) { final String executionId = state.executionId().get(); LOG.info("Cleaning up {} pod: {}", state.workflowInstance().toKey(), executionId); dockerRunner.cleanup(executionId); } break; default: // do nothing } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Map<WorkflowInstance, RunState> activeStates() { final ImmutableMap.Builder<WorkflowInstance, RunState> builder = ImmutableMap.builder(); states.entrySet().forEach(entry -> builder.put(entry.getKey(), entry.getValue().runState)); return builder.build(); } #location 2 #vulnerability type CHECKERS_IMMUTABLE_CAST
#fixed code @Override public Map<WorkflowInstance, RunState> activeStates() { return states.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, (entry) -> entry.getValue().runState)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code Map<WorkflowInstance, Long> readActiveWorkflowInstances() throws IOException { final Table activeStatesTable = connection.getTable(ACTIVE_STATES_TABLE_NAME); final ImmutableMap.Builder<WorkflowInstance, Long> map = ImmutableMap.builder(); for (Result result : activeStatesTable.getScanner(STATE_CF, STATE_QUALIFIER)) { final WorkflowInstance workflowInstance = WorkflowInstance.parseKey(Bytes.toString(result.getRow())); final long counter = Long.parseLong(Bytes.toString(result.value())); map.put(workflowInstance, counter); } return map.build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
#fixed code BigtableStorage(Connection connection, Duration retryBaseDelay) { this.connection = Objects.requireNonNull(connection); this.retryBaseDelay = Objects.requireNonNull(retryBaseDelay); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static KubernetesClient getKubernetesClient(Config config, String id) { try { final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); final JsonFactory jsonFactory = Utils.getDefaultJsonFactory(); final GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport, jsonFactory) .createScoped(ContainerScopes.all()); final Container gke = new Container.Builder(httpTransport, jsonFactory, credential) .setApplicationName(SERVICE_NAME) .build(); final String projectKey = GKE_CLUSTER_PREFIX + id + GKE_CLUSTER_PROJECT_ID; final String zoneKey = GKE_CLUSTER_PREFIX + id + GKE_CLUSTER_ZONE; final String clusterIdKey = GKE_CLUSTER_PREFIX + id + GKE_CLUSTER_ID; final Cluster cluster = gke.projects().zones().clusters() .get(config.getString(projectKey), config.getString(zoneKey), config.getString(clusterIdKey)).execute(); final io.fabric8.kubernetes.client.Config kubeConfig = new ConfigBuilder() .withMasterUrl("https://" + cluster.getEndpoint()) .withCaCertData(cluster.getMasterAuth().getClusterCaCertificate()) .withClientCertData(cluster.getMasterAuth().getClientCertificate()) .withClientKeyData(cluster.getMasterAuth().getClientKey()) .build(); return new AutoAdaptableKubernetesClient(kubeConfig).inNamespace(KUBERNETES_NAMESPACE); } catch (GeneralSecurityException | IOException e) { throw Throwables.propagate(e); } } #location 28 #vulnerability type RESOURCE_LEAK
#fixed code private static KubernetesClient getKubernetesClient(Config config, String id) { try { final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); final JsonFactory jsonFactory = Utils.getDefaultJsonFactory(); final GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport, jsonFactory) .createScoped(ContainerScopes.all()); final Container gke = new Container.Builder(httpTransport, jsonFactory, credential) .setApplicationName(SERVICE_NAME) .build(); final String projectKey = GKE_CLUSTER_PREFIX + id + GKE_CLUSTER_PROJECT_ID; final String zoneKey = GKE_CLUSTER_PREFIX + id + GKE_CLUSTER_ZONE; final String clusterIdKey = GKE_CLUSTER_PREFIX + id + GKE_CLUSTER_ID; final Cluster cluster = gke.projects().zones().clusters() .get(config.getString(projectKey), config.getString(zoneKey), config.getString(clusterIdKey)).execute(); final io.fabric8.kubernetes.client.Config kubeConfig = new ConfigBuilder() .withMasterUrl("https://" + cluster.getEndpoint()) .withCaCertData(cluster.getMasterAuth().getClusterCaCertificate()) .withClientCertData(cluster.getMasterAuth().getClientCertificate()) .withClientKeyData(cluster.getMasterAuth().getClientKey()) .build(); return new DefaultKubernetesClient(kubeConfig); } catch (GeneralSecurityException | IOException e) { throw Throwables.propagate(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code List<Backfill> getBackfills() { final EntityQuery query = Query.entityQueryBuilder().kind(KIND_BACKFILL).build(); final QueryResults<Entity> results = datastore.run(query); final ImmutableList.Builder<Backfill> resources = ImmutableList.builder(); while (results.hasNext()) { resources.add(entityToBackfill(results.next())); } return resources.build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
#fixed code DatastoreStorage(Datastore datastore, Duration retryBaseDelay) { this.datastore = Objects.requireNonNull(datastore); this.retryBaseDelay = Objects.requireNonNull(retryBaseDelay); this.componentKeyFactory = datastore.newKeyFactory().kind(KIND_COMPONENT); this.globalConfigKey = datastore.newKeyFactory().kind(KIND_STYX_CONFIG).newKey(KEY_GLOBAL_CONFIG); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void transitionInto(RunState state) { switch (state.state()) { case SUBMITTING: try { final String executionId = dockerRunnerStart(state); // this is racy final Event submitted = Event.submitted(state.workflowInstance(), executionId); try { stateManager.receive(submitted); } catch (StateManager.IsClosed isClosed) { LOG.warn("Could not send 'created' event", isClosed); } } catch (ResourceNotFoundException e) { LOG.error("Unable to start docker procedure.", e); stateManager.receiveIgnoreClosed(Event.halt(state.workflowInstance())); } catch (Throwable e) { try { LOG.error("Failed the docker starting procedure for " + state.workflowInstance().toKey(), e); stateManager.receive(Event.runError(state.workflowInstance(), e.getMessage())); } catch (StateManager.IsClosed isClosed) { LOG.warn("Failed to send 'runError' event", isClosed); } } break; case TERMINATED: case FAILED: case ERROR: if (state.data().executionId().isPresent()) { final String executionId = state.data().executionId().get(); boolean debugEnabled = false; try { debugEnabled = storage.debugEnabled(); } catch (IOException e) { LOG.info("Couldn't fetch debug flag. Will clean up pod anyway."); } if (!debugEnabled) { LOG.info("Cleaning up {} pod: {}", state.workflowInstance().toKey(), executionId); dockerRunner.cleanup(executionId); } else { LOG.info("Keeping {} pod: {}", state.workflowInstance().toKey(), executionId); } } break; default: // do nothing } } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void transitionInto(RunState state) { switch (state.state()) { case SUBMITTING: // Perform rate limited submission on a separate thread pool to avoid blocking the caller. executor.submit(() -> { rateLimiter.acquire(); try { final String executionId = dockerRunnerStart(state); // this is racy final Event submitted = Event.submitted(state.workflowInstance(), executionId); try { stateManager.receive(submitted); } catch (StateManager.IsClosed isClosed) { LOG.warn("Could not send 'created' event", isClosed); } } catch (ResourceNotFoundException e) { LOG.error("Unable to start docker procedure.", e); stateManager.receiveIgnoreClosed(Event.halt(state.workflowInstance())); } catch (Throwable e) { try { LOG.error("Failed the docker starting procedure for " + state.workflowInstance().toKey(), e); stateManager.receive(Event.runError(state.workflowInstance(), e.getMessage())); } catch (StateManager.IsClosed isClosed) { LOG.warn("Failed to send 'runError' event", isClosed); } } }); break; case TERMINATED: case FAILED: case ERROR: if (state.data().executionId().isPresent()) { final String executionId = state.data().executionId().get(); boolean debugEnabled = false; try { debugEnabled = storage.debugEnabled(); } catch (IOException e) { LOG.info("Couldn't fetch debug flag. Will clean up pod anyway."); } if (!debugEnabled) { LOG.info("Cleaning up {} pod: {}", state.workflowInstance().toKey(), executionId); dockerRunner.cleanup(executionId); } else { LOG.info("Keeping {} pod: {}", state.workflowInstance().toKey(), executionId); } } break; default: // do nothing } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code Map<WorkflowInstance, Long> allActiveStates() throws IOException { final EntityQuery activeStatesQuery = Query.entityQueryBuilder() .kind(KIND_ACTIVE_STATE) .build(); final ImmutableMap.Builder<WorkflowInstance, Long> mapBuilder = ImmutableMap.builder(); final QueryResults<Entity> results = datastore.run(activeStatesQuery); while (results.hasNext()) { final Entity activeState = results.next(); final WorkflowInstance instance = parseWorkflowInstance(activeState); final long counter = activeState.getLong(PROPERTY_ACTIVE_STATE_COUNTER); mapBuilder.put(instance, counter); } return mapBuilder.build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
#fixed code DatastoreStorage(Datastore datastore, Duration retryBaseDelay) { this.datastore = Objects.requireNonNull(datastore); this.retryBaseDelay = Objects.requireNonNull(retryBaseDelay); this.componentKeyFactory = datastore.newKeyFactory().kind(KIND_COMPONENT); this.globalConfigKey = datastore.newKeyFactory().kind(KIND_STYX_CONFIG).newKey(KEY_GLOBAL_CONFIG); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void doRequest(ServletTransaction transaction) throws ServletException { try { HttpServletRequest request = transaction.getServletRequest(); Client client = ClientCatalog .getClient(request.getParameter("use")); String report = request.getParameter("report"); String emails = request.getParameter("emails"); if (emails == null) return; HtmlEmail htmlEmail = client.getMailer().getHtmlEmail(emails, null); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); if ("statistics".equals(report)) { htmlEmail.setSubject("OpenSearchServer statistics report"); doStatistics(client, request.getParameter("stat"), request .getParameter("period"), pw); } htmlEmail.setHtmlMsg(sw.toString()); htmlEmail.send(); transaction.addXmlResponse("MailSent", emails); } catch (Exception e) { throw new ServletException(e); } } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Override protected void doRequest(ServletTransaction transaction) throws ServletException { try { HttpServletRequest request = transaction.getServletRequest(); Client client = ClientCatalog .getClient(request.getParameter("use")); String report = request.getParameter("report"); String emails = request.getParameter("emails"); if (emails == null) return; HtmlEmail htmlEmail = client.getMailer().getHtmlEmail(emails, null); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); if ("statistics".equals(report)) { htmlEmail.setSubject("OpenSearchServer statistics report"); doStatistics(client, request.getParameter("stat"), request .getParameter("period"), pw); } pw.close(); sw.close(); String html = sw.toString(); if (html == null || html.length() == 0) { transaction.addXmlResponse("Result", "Nothing to send"); } else { htmlEmail.setHtmlMsg(sw.toString()); htmlEmail .setTextMsg("Your email client does not support HTML messages"); htmlEmail.send(); } transaction.addXmlResponse("MailSent", emails); } catch (Exception e) { throw new ServletException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void deleteUrl(String sUrl) throws SearchLibException { try { client.deleteDocument(sUrl); } catch (CorruptIndexException e) { throw new SearchLibException(e); } catch (LockObtainFailedException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void deleteUrl(String sUrl) throws SearchLibException { try { targetClient.deleteDocument(sUrl); urlDbClient.deleteDocument(sUrl); } catch (CorruptIndexException e) { throw new SearchLibException(e); } catch (LockObtainFailedException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void reloadPage() { fieldLeft = null; selectedFacet = null; super.reloadPage(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void reloadPage() { synchronized (this) { fieldLeft = null; selectedFacet = null; super.reloadPage(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void reloadPage() { highlightFieldLeft = null; selectedHighlight = null; super.reloadPage(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void reloadPage() { synchronized (this) { highlightFieldLeft = null; selectedHighlight = null; super.reloadPage(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); fragmenter = External.readObject(in); tag = External.readUTF(in); maxDocChar = in.readInt(); separator = External.readUTF(in); maxSnippetSize = in.readInt(); maxSnippetNumber = in.readInt(); int l = in.readInt(); if (l > 0) { searchTerms = new String[l]; External.readArray(in, searchTerms); } else searchTerms = null; } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); fragmenter = External.readObject(in); tag = External.readUTF(in); maxDocChar = in.readInt(); separator = External.readUTF(in); maxSnippetSize = in.readInt(); maxSnippetNumber = in.readInt(); searchTerms = External.readStringArray(in); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void onUpload() throws InterruptedException, XPathExpressionException, NoSuchAlgorithmException, ParserConfigurationException, SAXException, IOException, URISyntaxException, SearchLibException, InstantiationException, IllegalAccessException, ClassNotFoundException { Media media = Fileupload.get(); if (media == null) return; setCurrentDocument(null); ParserSelector parserSelector = getClient().getParserSelector(); Parser parser = null; String contentType = media.getContentType(); if (contentType != null) parser = parserSelector.getParserFromMimeType(contentType); if (parser == null) { String extension = FileUtils.getFileNameExtension(media.getName()); parser = parserSelector.getParserFromExtension(extension); } if (parser == null) { Messagebox.show("No parser found for that document type (" + contentType + " - " + media.getName() + ')'); return; } BasketDocument basketDocument = parser.getBasketDocument(); setCurrentDocument(basketDocument); basketDocument.addIfNoEmpty("filename", media.getName()); basketDocument.addIfNoEmpty("content_type", contentType); synchronized (this) { if (media.inMemory()) { if (media.isBinary()) parser.parseContent(media.getByteData()); else parser.parseContent(media.getStringData()); } else { if (media.isBinary()) parser.parseContent(media.getStreamData()); else parser.parseContent(media.getReaderData()); } reloadPage(); } } #location 28 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void onUpload() throws InterruptedException, XPathExpressionException, NoSuchAlgorithmException, ParserConfigurationException, SAXException, IOException, URISyntaxException, SearchLibException, InstantiationException, IllegalAccessException, ClassNotFoundException { Media media = Fileupload.get(); if (media == null) return; synchronized (this) { setCurrentDocument(null); ParserSelector parserSelector = getClient().getParserSelector(); Parser parser = null; String contentType = media.getContentType(); if (contentType != null) parser = parserSelector.getParserFromMimeType(contentType); if (parser == null) { String extension = FileUtils.getFileNameExtension(media .getName()); parser = parserSelector.getParserFromExtension(extension); } if (parser == null) { Messagebox.show("No parser found for that document type (" + contentType + " - " + media.getName() + ')'); return; } BasketDocument basketDocument = parser.getBasketDocument(); basketDocument.addIfNoEmpty("filename", media.getName()); basketDocument.addIfNoEmpty("content_type", contentType); if (media.inMemory()) { if (media.isBinary()) parser.parseContent(media.getByteData()); else parser.parseContent(media.getStringData()); } else { if (media.isBinary()) parser.parseContent(media.getStreamData()); else parser.parseContent(media.getReaderData()); } setCurrentDocument(basketDocument); reloadPage(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void reloadPage() { fieldLeft = null; selectedFacet = null; super.reloadPage(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void reloadPage() { synchronized (this) { fieldLeft = null; selectedFacet = null; super.reloadPage(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void doRequest(ServletTransaction transaction) throws ServletException { try { Client client = Client.getWebAppInstance(); HttpServletRequest request = transaction.getServletRequest(); String indexName = request.getParameter("index"); String uniq = request.getParameter("uniq"); Object result = null; if (uniq != null) result = deleteDoc(client, indexName, uniq); else result = doObjectRequest(request, indexName); PrintWriter pw = transaction.getWriter("UTF-8"); pw.println(result); } catch (Exception e) { throw new ServletException(e); } } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected void doRequest(ServletTransaction transaction) throws ServletException { try { Client client = Client.getWebAppInstance(); HttpServletRequest request = transaction.getServletRequest(); String indexName = request.getParameter("index"); String uniq = request.getParameter("uniq"); String docId = request.getParameter("docId"); boolean byId = request.getParameter("byId") != null; Object result = null; if (uniq != null) result = deleteUniqDoc(client, indexName, uniq); else if (docId != null) result = deleteDocById(client, indexName, Integer .parseInt(docId)); else result = doObjectRequest(request, indexName, byId); PrintWriter pw = transaction.getWriter("UTF-8"); pw.println(result); } catch (Exception e) { throw new ServletException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void reload(boolean optimize) throws IOException, URISyntaxException, SearchLibException, InstantiationException, IllegalAccessException, ClassNotFoundException { if (optimize) { client.reload(null); client.getIndex().optimize(null); } client.reload(null); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void reload(boolean optimize) throws IOException, URISyntaxException, SearchLibException, InstantiationException, IllegalAccessException, ClassNotFoundException { if (optimize) { urlDbClient.reload(null); urlDbClient.getIndex().optimize(null); targetClient.reload(null); targetClient.getIndex().optimize(null); } urlDbClient.reload(null); targetClient.reload(null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void deleteUrls(Collection<String> workDeleteUrlList) throws SearchLibException { try { client.deleteDocuments(workDeleteUrlList); } catch (CorruptIndexException e) { throw new SearchLibException(e); } catch (LockObtainFailedException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void deleteUrls(Collection<String> workDeleteUrlList) throws SearchLibException { try { targetClient.deleteDocuments(workDeleteUrlList); urlDbClient.deleteDocuments(workDeleteUrlList); } catch (CorruptIndexException e) { throw new SearchLibException(e); } catch (LockObtainFailedException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void writeXmlConfig(XmlWriter xmlWriter) throws SAXException, SearchLibException { xmlWriter.startElement("system"); xmlWriter.startElement("availableProcessors", "value", Integer .toString(getAvailableProcessors())); xmlWriter.endElement(); xmlWriter.startElement("freeMemory", "value", Long .toString(getFreeMemory()), "rate", Double .toString(getMemoryRate())); xmlWriter.endElement(); xmlWriter.startElement("maxMemory", "value", Long .toString(getMaxMemory())); xmlWriter.endElement(); xmlWriter.startElement("totalMemory", "value", Long .toString(getTotalMemory())); xmlWriter.endElement(); xmlWriter.startElement("indexCount", "value", Integer .toString(getIndexCount())); xmlWriter.endElement(); xmlWriter.startElement("freeDiskSpace", "value", getFreeDiskSpace() .toString()); xmlWriter.endElement(); xmlWriter.startElement("dataDirectoryPath", "value", getDataDirectoryPath()); xmlWriter.endElement(); xmlWriter.endElement(); xmlWriter.startElement("properties"); for (Entry<Object, Object> prop : getProperties()) { xmlWriter.startElement("property", "name", prop.getKey().toString(), "value", prop.getValue() .toString()); xmlWriter.endElement(); } xmlWriter.endElement(); } #location 27 #vulnerability type NULL_DEREFERENCE
#fixed code public void writeXmlConfig(XmlWriter xmlWriter) throws SAXException, SearchLibException, SecurityException, IOException { xmlWriter.startElement("system"); xmlWriter.startElement("availableProcessors", "value", Integer .toString(getAvailableProcessors())); xmlWriter.endElement(); xmlWriter.startElement("freeMemory", "value", Long .toString(getFreeMemory()), "rate", Double .toString(getMemoryRate())); xmlWriter.endElement(); xmlWriter.startElement("maxMemory", "value", Long .toString(getMaxMemory())); xmlWriter.endElement(); xmlWriter.startElement("totalMemory", "value", Long .toString(getTotalMemory())); xmlWriter.endElement(); xmlWriter.startElement("indexCount", "value", Integer .toString(getIndexCount())); xmlWriter.endElement(); Double rate = getDiskRate(); if (rate == null) xmlWriter.startElement("freeDiskSpace", "value", getFreeDiskSpace() .toString()); else xmlWriter.startElement("freeDiskSpace", "value", getFreeDiskSpace() .toString(), "rate", rate.toString()); xmlWriter.endElement(); xmlWriter.startElement("dataDirectoryPath", "value", getDataDirectoryPath()); xmlWriter.endElement(); xmlWriter.endElement(); xmlWriter.startElement("properties"); for (Entry<Object, Object> prop : getProperties()) { xmlWriter.startElement("property", "name", prop.getKey().toString(), "value", prop.getValue() .toString()); xmlWriter.endElement(); } xmlWriter.endElement(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void onAdd() throws SearchLibException, UnsupportedEncodingException, ParseException, InterruptedException { synchronized (this) { if (getSelectedFile() != null) { // Already In if (getClient().getFilePathManager().getStrictPaths( getSelectedFile().getPath(), 0, 0, null) > 0) { Messagebox .show("Already In.", "Jaeksoft OpenSearchServer", Messagebox.OK, org.zkoss.zul.Messagebox.INFORMATION); } else { List<PathItem> list = FilePathManager.addPath( getSelectedFile().getPath(), getSelectedFile() .isDirectory() && isSelectedFileCheck()); if (list.size() > 0) { getClient().getFilePathManager().addList(list, false); } pathList = null; setSelectedFileCheck(false); setSelectedFilePath(null); reloadPage(); } } } } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code public void onAdd() throws SearchLibException, UnsupportedEncodingException, ParseException, InterruptedException { synchronized (this) { if (getSelectedFile() != null) { // Already In if (getClient().getFilePathManager().getFilePaths( getSelectedFile().getPath(), 0, 0, null) > 0) { Messagebox .show("Already In.", "Jaeksoft OpenSearchServer", Messagebox.OK, org.zkoss.zul.Messagebox.INFORMATION); } else { /* * List<FilePathItem> list = FilePathManager( * getSelectedFile().getPath(), getSelectedFile() * .isDirectory() && isSelectedFileCheck()); * * if (list.size() > 0) { * getClient().getFilePathManager().addList(list, false); } */ pathList = null; setSelectedFileCheck(false); setSelectedFilePath(null); reloadPage(); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void getNewUrlToFetch(NamedItem host, long limit, List<UrlItem> urlList) throws SearchLibException, ParseException, IOException, SyntaxError, URISyntaxException, ClassNotFoundException, InterruptedException, InstantiationException, IllegalAccessException { SearchRequest searchRequest = client.getNewSearchRequest("urlSearch"); searchRequest.addFilter("host:\"" + SearchRequest.escapeQuery(host.getName()) + "\""); searchRequest.setQueryString("*:*"); filterQueryToFetchNew(searchRequest); searchRequest.setRows((int) limit); Result result = client.search(searchRequest); for (ResultDocument item : result) urlList.add(new UrlItem(item)); } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void getNewUrlToFetch(NamedItem host, long limit, List<UrlItem> urlList) throws SearchLibException, ParseException, IOException, SyntaxError, URISyntaxException, ClassNotFoundException, InterruptedException, InstantiationException, IllegalAccessException { SearchRequest searchRequest = urlDbClient .getNewSearchRequest("urlSearch"); searchRequest.addFilter("host:\"" + SearchRequest.escapeQuery(host.getName()) + "\""); searchRequest.setQueryString("*:*"); filterQueryToFetchNew(searchRequest); searchRequest.setRows((int) limit); Result result = urlDbClient.search(searchRequest); for (ResultDocument item : result) urlList.add(new UrlItem(item)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void reloadPage() { selectedSort = null; sortFieldLeft = null; super.reloadPage(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void reloadPage() { synchronized (this) { selectedSort = null; sortFieldLeft = null; super.reloadPage(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void updateUrlItems(List<UrlItem> urlItems) throws SearchLibException { try { List<IndexDocument> documents = new ArrayList<IndexDocument>( urlItems.size()); for (UrlItem urlItem : urlItems) { IndexDocument indexDocument = new IndexDocument(); urlItem.populate(indexDocument); documents.add(indexDocument); } client.updateDocuments(documents); } catch (NoSuchAlgorithmException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void updateUrlItems(List<UrlItem> urlItems) throws SearchLibException { try { List<IndexDocument> documents = new ArrayList<IndexDocument>( urlItems.size()); for (UrlItem urlItem : urlItems) { IndexDocument indexDocument = new IndexDocument(); urlItem.populate(indexDocument); documents.add(indexDocument); } urlDbClient.updateDocuments(documents); } catch (NoSuchAlgorithmException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void getStartingWith(String queryString, Field field, String start, int limit, List<NamedItem> list) throws ParseException, IOException, SyntaxError, URISyntaxException, ClassNotFoundException, InterruptedException, SearchLibException, InstantiationException, IllegalAccessException { SearchRequest searchRequest = client.getNewSearchRequest(field + "Facet"); searchRequest.setQueryString(queryString); searchRequest.getFilterList().add(field + ":" + start + "*", Source.REQUEST); getFacetLimit(field, searchRequest, limit, list); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void getStartingWith(String queryString, Field field, String start, int limit, List<NamedItem> list) throws ParseException, IOException, SyntaxError, URISyntaxException, ClassNotFoundException, InterruptedException, SearchLibException, InstantiationException, IllegalAccessException { SearchRequest searchRequest = urlDbClient.getNewSearchRequest(field + "Facet"); searchRequest.setQueryString(queryString); searchRequest.getFilterList().add(field + ":" + start + "*", Source.REQUEST); getFacetLimit(field, searchRequest, limit, list); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public long getUrls(SearchRequest searchRequest, Field orderBy, boolean orderAsc, long start, long rows, List<UrlItem> list) throws SearchLibException { searchRequest.setStart((int) start); searchRequest.setRows((int) rows); try { if (orderBy != null) searchRequest.addSort(orderBy.name, !orderAsc); Result result = client.search(searchRequest); if (list != null) for (ResultDocument doc : result) list.add(new UrlItem(doc)); return result.getNumFound(); } catch (ParseException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (RuntimeException e) { throw new SearchLibException(e); } catch (SyntaxError e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } catch (InterruptedException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public long getUrls(SearchRequest searchRequest, Field orderBy, boolean orderAsc, long start, long rows, List<UrlItem> list) throws SearchLibException { searchRequest.setStart((int) start); searchRequest.setRows((int) rows); try { if (orderBy != null) searchRequest.addSort(orderBy.name, !orderAsc); Result result = urlDbClient.search(searchRequest); if (list != null) for (ResultDocument doc : result) list.add(new UrlItem(doc)); return result.getNumFound(); } catch (ParseException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (RuntimeException e) { throw new SearchLibException(e); } catch (SyntaxError e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } catch (InterruptedException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void renderDocument(int pos) throws CorruptIndexException, IOException, ParseException, SyntaxError { writer.print("\t<doc score=\""); writer.print(result.getDocs()[pos].score); writer.print("\" pos=\""); writer.print(pos); writer.println("\">"); ResultDocument doc = result.getDocument(pos); for (Field field : searchRequest.getReturnFieldList()) renderField(doc, field); for (HighlightField field : searchRequest.getHighlightFieldList()) renderHighlightValue(doc, field); int cc = result.getCollapseCount(pos); if (cc > 0) { writer.print("\t\t<collapseCount>"); writer.print(cc); writer.println("</collapseCount>"); } writer.println("\t</doc>"); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code private void renderDocument(int pos) throws CorruptIndexException, IOException, ParseException, SyntaxError { writer.print("\t<doc score=\""); writer.print(result.getScore(pos)); writer.print("\" pos=\""); writer.print(pos); writer.println("\">"); ResultDocument doc = result.getDocument(pos); for (Field field : searchRequest.getReturnFieldList()) renderField(doc, field); for (HighlightField field : searchRequest.getHighlightFieldList()) renderHighlightValue(doc, field); int cc = result.getCollapseCount(pos); if (cc > 0) { writer.print("\t\t<collapseCount>"); writer.print(cc); writer.println("</collapseCount>"); } writer.println("\t</doc>"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void reloadPage() { highlightFieldLeft = null; selectedHighlight = null; super.reloadPage(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void reloadPage() { synchronized (this) { highlightFieldLeft = null; selectedHighlight = null; super.reloadPage(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void updateCrawls(List<Crawl> crawls) throws SearchLibException { try { List<IndexDocument> documents = new ArrayList<IndexDocument>(crawls .size()); for (Crawl crawl : crawls) { IndexDocument indexDocument = new IndexDocument(); crawl.getUrlItem().populate(indexDocument); documents.add(indexDocument); } client.updateDocuments(documents); } catch (NoSuchAlgorithmException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void updateCrawls(List<Crawl> crawls) throws SearchLibException { try { // Update target index List<IndexDocument> documents = new ArrayList<IndexDocument>(crawls .size()); for (Crawl crawl : crawls) { IndexDocument indexDocument = crawl.getTargetIndexDocument(); documents.add(indexDocument); } targetClient.updateDocuments(documents); // Update URL DB documents.clear(); for (Crawl crawl : crawls) { IndexDocument indexDocument = new IndexDocument(); crawl.getUrlItem().populate(indexDocument); documents.add(indexDocument); } urlDbClient.updateDocuments(documents); } catch (NoSuchAlgorithmException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void getOldUrlToFetch(NamedItem host, Date fetchIntervalDate, long limit, List<UrlItem> urlList) throws SearchLibException, ParseException, IOException, SyntaxError, URISyntaxException, ClassNotFoundException, InterruptedException, InstantiationException, IllegalAccessException { SearchRequest searchRequest = client.getNewSearchRequest("urlSearch"); searchRequest.addFilter("host:\"" + SearchRequest.escapeQuery(host.getName()) + "\""); searchRequest.setQueryString("*:*"); filterQueryToFetchOld(searchRequest, fetchIntervalDate); searchRequest.setRows((int) limit); Result result = client.search(searchRequest); for (ResultDocument item : result) urlList.add(new UrlItem(item)); } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void getOldUrlToFetch(NamedItem host, Date fetchIntervalDate, long limit, List<UrlItem> urlList) throws SearchLibException, ParseException, IOException, SyntaxError, URISyntaxException, ClassNotFoundException, InterruptedException, InstantiationException, IllegalAccessException { SearchRequest searchRequest = urlDbClient .getNewSearchRequest("urlSearch"); searchRequest.addFilter("host:\"" + SearchRequest.escapeQuery(host.getName()) + "\""); searchRequest.setQueryString("*:*"); filterQueryToFetchOld(searchRequest, fetchIntervalDate); searchRequest.setRows((int) limit); Result result = urlDbClient.search(searchRequest); for (ResultDocument item : result) urlList.add(new UrlItem(item)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void reloadPage() { selectedSort = null; sortFieldLeft = null; super.reloadPage(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void reloadPage() { synchronized (this) { selectedSort = null; sortFieldLeft = null; super.reloadPage(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void reload(boolean optimize) throws IOException, URISyntaxException, SearchLibException, InstantiationException, IllegalAccessException, ClassNotFoundException { if (optimize) { client.reload(null); client.getIndex().optimize(null); } client.reload(null); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void reload(boolean optimize) throws IOException, URISyntaxException, SearchLibException, InstantiationException, IllegalAccessException, ClassNotFoundException { if (optimize) { urlDbClient.reload(null); urlDbClient.getIndex().optimize(null); targetClient.reload(null); targetClient.getIndex().optimize(null); } urlDbClient.reload(null); targetClient.reload(null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run(ResultScoreDoc[] fetchedDocs, int fetchLength) throws IOException { collapsedDoc = null; if (fetchedDocs == null) return; if (fetchLength > fetchedDocs.length) fetchLength = fetchedDocs.length; OpenBitSet collapsedSet = new OpenBitSet(fetchLength); String lastTerm = null; int adjacent = 0; collapsedDocCount = 0; for (int i = 0; i < fetchLength; i++) { String term = fetchedDocs[i].collapseTerm; if (term != null && term.equals(lastTerm)) { if (++adjacent >= collapseMax) collapsedSet.set(i); } else { lastTerm = term; adjacent = 0; } } collapsedDocCount = (int) collapsedSet.cardinality(); collapsedDoc = new ResultScoreDoc[fetchLength - collapsedDocCount]; int currentPos = 0; ResultScoreDoc collapseDoc = null; for (int i = 0; i < fetchLength; i++) { if (!collapsedSet.get(i)) { collapseDoc = fetchedDocs[i]; collapseDoc.collapseCount = 0; collapsedDoc[currentPos++] = collapseDoc; } else { collapseDoc.collapseCount++; } } } #location 39 #vulnerability type NULL_DEREFERENCE
#fixed code public void run(ResultScoreDoc[] fetchedDocs, int fetchLength) throws IOException { collapsedDoc = null; if (fetchedDocs == null) return; if (fetchLength > fetchedDocs.length) fetchLength = fetchedDocs.length; collapse(fetchedDocs, fetchLength); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code final protected void getFragments(String originalText, FragmentList fragments, int vectorOffset) { originalTextLength = originalText.length(); if (splitPos == null) splitPos = new TreeSet<Integer>(); splitPos.clear(); check(originalText); Iterator<Integer> splitIterator = splitPos.iterator(); int pos = 0; Fragment lastFragment = null; while (splitIterator.hasNext()) { int nextSplitPos = splitIterator.next(); lastFragment = fragments.addOriginalText(originalText.substring( pos, nextSplitPos), vectorOffset, lastFragment == null); pos = nextSplitPos; } if (pos < originalText.length()) lastFragment = fragments.addOriginalText(originalText .substring(pos), vectorOffset, lastFragment == null); lastFragment.setEdge(true); } #location 20 #vulnerability type NULL_DEREFERENCE
#fixed code final protected void getFragments(String originalText, FragmentList fragments, int vectorOffset) { originalTextLength = originalText.length(); if (splitPos == null) splitPos = new TreeSet<Integer>(); splitPos.clear(); check(originalText); Iterator<Integer> splitIterator = splitPos.iterator(); int pos = 0; Fragment lastFragment = null; while (splitIterator.hasNext()) { int nextSplitPos = splitIterator.next(); lastFragment = fragments.addOriginalText(originalText.substring( pos, nextSplitPos), vectorOffset, lastFragment == null); pos = nextSplitPos; } if (pos < originalText.length()) lastFragment = fragments.addOriginalText(originalText .substring(pos), vectorOffset, lastFragment == null); if (lastFragment != null) lastFragment.setEdge(true); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static HTMLDocument fetch(final URL url) throws IOException { final URLConnection conn = url.openConnection(); final String charset = conn.getContentEncoding(); Charset cs = Charset.forName("Cp1252"); if (charset != null) { try { cs = Charset.forName(charset); } catch (UnsupportedCharsetException e) { // keep default } } InputStream in = conn.getInputStream(); final String encoding = conn.getContentEncoding(); if(encoding != null) { if("gzip".equalsIgnoreCase(encoding)) { in = new GZIPInputStream(in); } else { System.err.println("WARN: unsupported Content-Encoding: "+encoding); } } ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int r; while ((r = in.read(buf)) != -1) { bos.write(buf, 0, r); } in.close(); final byte[] data = bos.toByteArray(); return new HTMLDocument(data, cs); } #location 35 #vulnerability type RESOURCE_LEAK
#fixed code public static HTMLDocument fetch(final URL url) throws IOException { final URLConnection conn = url.openConnection(); final String ct = conn.getContentType(); Charset cs = Charset.forName("Cp1252"); if (ct != null) { Matcher m = PAT_CHARSET.matcher(ct); if(m.find()) { final String charset = m.group(1); try { cs = Charset.forName(charset); } catch (UnsupportedCharsetException e) { // keep default } } } InputStream in = conn.getInputStream(); final String encoding = conn.getContentEncoding(); if(encoding != null) { if("gzip".equalsIgnoreCase(encoding)) { in = new GZIPInputStream(in); } else { System.err.println("WARN: unsupported Content-Encoding: "+encoding); } } ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int r; while ((r = in.read(buf)) != -1) { bos.write(buf, 0, r); } in.close(); final byte[] data = bos.toByteArray(); return new HTMLDocument(data, cs); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getText(final URL url) throws BoilerpipeProcessingException { try { final URLConnection conn = url.openConnection(); final String encoding = conn.getContentEncoding(); Charset cs = Charset.forName("Cp1252"); if (encoding != null) { try { cs = Charset.forName(encoding); } catch (UnsupportedCharsetException e) { // keep default } } final InputStream in = conn.getInputStream(); InputSource is = new InputSource(in); if(cs != null) { is.setEncoding(cs.name()); } final String text = getText(is); in.close(); return text; } catch (IOException e) { throw new BoilerpipeProcessingException(e); } } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code public String getText(final URL url) throws BoilerpipeProcessingException { try { return getText(HTMLFetcher.fetch(url).toInputSource()); } catch (IOException e) { throw new BoilerpipeProcessingException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static HTMLDocument fetch(final URL url) throws IOException { final URLConnection conn = url.openConnection(); final String charset = conn.getContentEncoding(); Charset cs = Charset.forName("Cp1252"); if (charset != null) { try { cs = Charset.forName(charset); } catch (UnsupportedCharsetException e) { // keep default } } InputStream in = conn.getInputStream(); final String encoding = conn.getContentEncoding(); if(encoding != null) { if("gzip".equalsIgnoreCase(encoding)) { in = new GZIPInputStream(in); } else { System.err.println("WARN: unsupported Content-Encoding: "+encoding); } } ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int r; while ((r = in.read(buf)) != -1) { bos.write(buf, 0, r); } in.close(); final byte[] data = bos.toByteArray(); return new HTMLDocument(data, cs); } #location 35 #vulnerability type RESOURCE_LEAK
#fixed code public static HTMLDocument fetch(final URL url) throws IOException { final URLConnection conn = url.openConnection(); final String ct = conn.getContentType(); Charset cs = Charset.forName("Cp1252"); if (ct != null) { Matcher m = PAT_CHARSET.matcher(ct); if(m.find()) { final String charset = m.group(1); try { cs = Charset.forName(charset); } catch (UnsupportedCharsetException e) { // keep default } } } InputStream in = conn.getInputStream(); final String encoding = conn.getContentEncoding(); if(encoding != null) { if("gzip".equalsIgnoreCase(encoding)) { in = new GZIPInputStream(in); } else { System.err.println("WARN: unsupported Content-Encoding: "+encoding); } } ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int r; while ((r = in.read(buf)) != -1) { bos.write(buf, 0, r); } in.close(); final byte[] data = bos.toByteArray(); return new HTMLDocument(data, cs); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void insertLoginLog(String username) { UmsAdmin admin = getAdminByUsername(username); UmsAdminLoginLog loginLog = new UmsAdminLoginLog(); loginLog.setAdminId(admin.getId()); loginLog.setCreateTime(new Date()); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); loginLog.setIp(request.getRemoteAddr()); loginLogMapper.insert(loginLog); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private void insertLoginLog(String username) { UmsAdmin admin = getAdminByUsername(username); if(admin==null) return; UmsAdminLoginLog loginLog = new UmsAdminLoginLog(); loginLog.setAdminId(admin.getId()); loginLog.setCreateTime(new Date()); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); loginLog.setIp(request.getRemoteAddr()); loginLogMapper.insert(loginLog); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getUserNameFromToken(String token) { String username; try { Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { e.printStackTrace(); username = null; } return username; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public String getUserNameFromToken(String token) { String username; try { Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { username = null; } return username; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Date getExpiredDateFromToken(String token) { Date expiredDate = null; try { Claims claims = getClaimsFromToken(token); expiredDate = claims.getExpiration(); } catch (Exception e) { e.printStackTrace(); } return expiredDate; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code private Date getExpiredDateFromToken(String token) { Claims claims = getClaimsFromToken(token); return claims.getExpiration(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onHttpFinish(QQHttpResponse response) { try { LOG.debug(response.getContentType()); String type = response.getContentType(); if((type.startsWith("application/x-javascript") || type.startsWith("application/json") || type.indexOf("text") >= 0 ) && response.getContentLength() > 0){ LOG.debug(response.getResponseString()); } if(response.getResponseCode() == QQHttpResponse.S_OK){ onHttpStatusOK(response); }else{ onHttpStatusError(response); } } catch (QQException e) { notifyActionEvent(QQActionEvent.Type.EVT_ERROR, e); } catch (JSONException e) { notifyActionEvent(QQActionEvent.Type.EVT_ERROR, new QQException(QQErrorCode.JSON_ERROR, e)); } catch (Throwable e){ notifyActionEvent(QQActionEvent.Type.EVT_ERROR, new QQException(QQErrorCode.UNKNOWN_ERROR, e)); } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void onHttpFinish(QQHttpResponse response) { try { LOG.debug(response.getContentType()); String type = response.getContentType(); if(type!=null && (type.startsWith("application/x-javascript") || type.startsWith("application/json") || type.indexOf("text") >= 0 ) && response.getContentLength() > 0){ LOG.debug(response.getResponseString()); } if(response.getResponseCode() == QQHttpResponse.S_OK){ onHttpStatusOK(response); }else{ onHttpStatusError(response); } } catch (QQException e) { notifyActionEvent(QQActionEvent.Type.EVT_ERROR, e); } catch (JSONException e) { notifyActionEvent(QQActionEvent.Type.EVT_ERROR, new QQException(QQErrorCode.JSON_ERROR, e)); } catch (Throwable e){ notifyActionEvent(QQActionEvent.Type.EVT_ERROR, new QQException(QQErrorCode.UNKNOWN_ERROR, e)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void progressCallbackSend() throws Exception { final AtomicReference<String> body = new AtomicReference<String>(); handler = new RequestHandler() { @Override public void handle(Request request, HttpServletResponse response) { body.set(new String(read())); response.setStatus(HTTP_OK); } }; final File file = File.createTempFile("post", ".txt"); new FileWriter(file).append("hello").close(); final AtomicInteger tx = new AtomicInteger(0); ProgressCallback progress = new ProgressCallback() { public void onProgress(int transferred, int total) { assertEquals(file.length(), total); assertEquals(tx.incrementAndGet(), transferred); } }; post(url).bufferSize(1).progress(progress).send(file); assertEquals(file.length(), tx.get()); } #location 22 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void progressCallbackSend() throws Exception { final AtomicReference<String> body = new AtomicReference<String>(); handler = new RequestHandler() { @Override public void handle(Request request, HttpServletResponse response) { body.set(new String(read())); response.setStatus(HTTP_OK); } }; final File file = File.createTempFile("post", ".txt"); new FileWriter(file).append("hello").close(); final AtomicInteger tx = new AtomicInteger(0); ProgressCallback progress = new ProgressCallback() { public void onProgress(int transferred, int total) { assertEquals(file.length(), total); assertEquals(tx.incrementAndGet(), transferred); } }; post(url).bufferSize(1).progress(progress).send(file).code(); assertEquals(file.length(), tx.get()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void progressCallbackSendInputStream() throws Exception { final AtomicReference<String> body = new AtomicReference<String>(); handler = new RequestHandler() { @Override public void handle(Request request, HttpServletResponse response) { body.set(new String(read())); response.setStatus(HTTP_OK); } }; File file = File.createTempFile("post", ".txt"); new FileWriter(file).append("hello").close(); InputStream input = new FileInputStream(file); final AtomicInteger tx = new AtomicInteger(0); ProgressCallback progress = new ProgressCallback() { public void onProgress(int transferred, int total) { assertEquals(0, total); assertEquals(tx.incrementAndGet(), transferred); } }; post(url).bufferSize(1).progress(progress).send(input); assertEquals(file.length(), tx.get()); } #location 22 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void progressCallbackSendInputStream() throws Exception { final AtomicReference<String> body = new AtomicReference<String>(); handler = new RequestHandler() { @Override public void handle(Request request, HttpServletResponse response) { body.set(new String(read())); response.setStatus(HTTP_OK); } }; File file = File.createTempFile("post", ".txt"); new FileWriter(file).append("hello").close(); InputStream input = new FileInputStream(file); final AtomicInteger tx = new AtomicInteger(0); ProgressCallback progress = new ProgressCallback() { public void onProgress(int transferred, int total) { assertEquals(0, total); assertEquals(tx.incrementAndGet(), transferred); } }; post(url).bufferSize(1).progress(progress).send(input).code(); assertEquals(file.length(), tx.get()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode(new Configuration("com.zuoxiaolong.niubi.job.jobs"), "localhost:2181,localhost:3181,localhost:4181"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode(); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode("localhost:2181,localhost:3181,localhost:4181", "http://localhost:8080/job"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode("localhost:2181,localhost:3181,localhost:4181", "http://localhost:8080/job", StringHelper.emptyArray()); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new MasterSlaveNode(new Configuration("com.zuoxiaolong.niubi.job.jobs"), "localhost:2181,localhost:3181,localhost:4181"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new MasterSlaveNode(); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode(new Configuration("com.zuoxiaolong.niubi.job.jobs"), "localhost:2181,localhost:3181,localhost:4181"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode(); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<MasterSlaveNodeData> getAllNodes() { List<ChildData> childDataList = getChildren(PathHelper.getParentPath(getMasterSlavePathApi().getNodePath())); List<MasterSlaveNodeData> masterSlaveNodeDataList = childDataList.stream().map(MasterSlaveNodeData::new).collect(Collectors.toList()); return masterSlaveNodeDataList; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public List<MasterSlaveNodeData> getAllNodes() { List<ChildData> childDataList = getChildren(PathHelper.getParentPath(getMasterSlavePathApi().getNodePath())); if (ListHelper.isEmpty(childDataList)) { return null; } List<MasterSlaveNodeData> masterSlaveNodeDataList = childDataList.stream().map(MasterSlaveNodeData::new).collect(Collectors.toList()); return masterSlaveNodeDataList; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode("localhost:2181,localhost:3181,localhost:4181", "http://localhost:8080/job"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode("localhost:2181,localhost:3181,localhost:4181", "http://localhost:8080/job", StringHelper.emptyArray()); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<StandbyNodeData> getAllNodes() { List<ChildData> childDataList = getChildren(PathHelper.getParentPath(getStandbyPathApi().getNodePath())); List<StandbyNodeData> standbyNodeDataList = childDataList.stream().map(StandbyNodeData::new).collect(Collectors.toList()); return standbyNodeDataList; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public List<StandbyNodeData> getAllNodes() { List<ChildData> childDataList = getChildren(PathHelper.getParentPath(getStandbyPathApi().getNodePath())); if (ListHelper.isEmpty(childDataList)) { return null; } List<StandbyNodeData> standbyNodeDataList = childDataList.stream().map(StandbyNodeData::new).collect(Collectors.toList()); return standbyNodeDataList; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new MasterSlaveNode(new Configuration("com.zuoxiaolong.niubi.job.jobs"), "localhost:2181,localhost:3181,localhost:4181"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new MasterSlaveNode(); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<Pair<String, String>> getColumns(String schema, String table) throws VerdictDBDbmsException { List<Pair<String, String>> columns = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getColumnsCommand(schema, table)); JdbcResultSet jdbcResultSet = new JdbcResultSet(queryResult); try { while (queryResult.next()) { String type = jdbcResultSet.getString(syntax.getColumnTypeColumnIndex()+1); type = type.toLowerCase(); // // remove the size of type // type = type.replaceAll("\\(.*\\)", ""); columns.add( new ImmutablePair<>(jdbcResultSet.getString(syntax.getColumnNameColumnIndex()+1), type)); } } catch (SQLException e) { throw new VerdictDBDbmsException(e); } finally { jdbcResultSet.close(); } return columns; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public List<Pair<String, String>> getColumns(String schema, String table) throws VerdictDBDbmsException { List<Pair<String, String>> columns = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getColumnsCommand(schema, table)); while (queryResult.next()) { String type = (String) queryResult.getValue(syntax.getColumnTypeColumnIndex()); type = type.toLowerCase(); columns.add( new ImmutablePair<>((String) queryResult.getValue(syntax.getColumnNameColumnIndex()), type)); } return columns; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<String> getSchemas() throws SQLException { if (!schemaCache.isEmpty()){ return schemaCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getSchemaCommand()); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { schemaCache.add(jdbcQueryResult.getString(syntax.getSchemaNameColumnIndex())); } return schemaCache; } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public List<String> getSchemas() throws SQLException { if (!schemaCache.isEmpty()){ return schemaCache; } schemaCache.addAll(connection.getSchemas()); return schemaCache; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ApproxRelation approx() throws VerdictException { List<Expr> exprs = exprsInSelectElems(elems); // for each expression, we obtain pairs of sample candidates and the costs of using them. List<Pair<Map<Set<SampleParam>, List<Double>>, SelectElem>> candidates_list = new ArrayList<Pair<Map<Set<SampleParam>, List<Double>>, SelectElem>>(); for (int i = 0; i < exprs.size(); i++) { Map<Set<SampleParam>, List<Double>> candidates = source.findSample(exprs.get(i)); candidates_list.add(Pair.of(candidates, elems.get(i))); } // We test if we can consolidate those sample candidates so that the number of select statements is less than // the number of the expressions. In the worst case (e.g., all count-distinct), the number of select statements // will be equal to the number of the expressions. If the cost of running those select statements individually // is higher than the cost of running a single select statement using the original tables, we do not use samples. List<Pair<Set<SampleParam>, List<SelectElem>>> consolidated = consolidate(candidates_list); List<ApproxAggregatedRelation> individuals = new ArrayList<ApproxAggregatedRelation>(); for (Pair<Set<SampleParam>, List<SelectElem>> p : consolidated) { List<SelectElem> elemsPart = p.getRight(); Set<SampleParam> samplesPart = p.getLeft(); individuals.add(new ApproxAggregatedRelation(vc, source.approxWith(attachTableMapping(samplesPart)), elemsPart)); } // join the results from those multiple relations (if there are more than one) ApproxRelation r = null; for (ApproxAggregatedRelation r1 : individuals) { if (r == null) { r = r1; } else { String ln = Relation.genTableAlias(); String rn = Relation.genTableAlias(); r.setAliasName(ln); r1.setAliasName(rn); if (r1.getSource() instanceof ApproxGroupedRelation) { List<ColNameExpr> groupby = ((ApproxGroupedRelation) r1.getSource()).getGroupby(); List<Pair<Expr, Expr>> joincols = new ArrayList<Pair<Expr, Expr>>(); for (ColNameExpr col : groupby) { joincols.add(Pair.of((Expr) new ColNameExpr(col.getCol(), ln), (Expr) new ColNameExpr(col.getCol(), rn))); } r = new ApproxJoinedRelation(vc, r, r1, joincols); } else { r = new ApproxJoinedRelation(vc, r, r1, null); } } } r.setAliasName(getAliasName()); return r; } #location 46 #vulnerability type NULL_DEREFERENCE
#fixed code public ApproxRelation approx() throws VerdictException { // for each expression, we obtain pairs of sample candidates and the costs of using them. List<List<SampleGroup>> candidates_list = new ArrayList<List<SampleGroup>>(); for (int i = 0; i < elems.size(); i++) { List<SampleGroup> candidates = source.findSample(elems.get(i)); candidates_list.add(candidates); } // We test if we can consolidate those sample candidates so that the number of select statements is less than // the number of the expressions. In the worst case (e.g., all count-distinct), the number of select statements // will be equal to the number of the expressions. If the cost of running those select statements individually // is higher than the cost of running a single select statement using the original tables, we do not use samples. SamplePlan plan = consolidate(candidates_list); List<ApproxAggregatedRelation> individuals = new ArrayList<ApproxAggregatedRelation>(); for (SampleGroup group : plan.getSampleGroups()) { List<SelectElem> elems = group.getElems(); Set<SampleParam> samplesPart = group.sampleSet(); individuals.add(new ApproxAggregatedRelation(vc, source.approxWith(attachTableMapping(samplesPart)), elems)); } // join the results from those multiple relations (if there are more than one) ApproxRelation r = null; for (ApproxAggregatedRelation r1 : individuals) { if (r == null) { r = r1; } else { String ln = Relation.genTableAlias(); String rn = Relation.genTableAlias(); r.setAliasName(ln); r1.setAliasName(rn); if (r1.getSource() instanceof ApproxGroupedRelation) { List<ColNameExpr> groupby = ((ApproxGroupedRelation) r1.getSource()).getGroupby(); List<Pair<Expr, Expr>> joincols = new ArrayList<Pair<Expr, Expr>>(); for (ColNameExpr col : groupby) { joincols.add(Pair.of((Expr) new ColNameExpr(col.getCol(), ln), (Expr) new ColNameExpr(col.getCol(), rn))); } r = new ApproxJoinedRelation(vc, r, r1, joincols); } else { r = new ApproxJoinedRelation(vc, r, r1, null); } } } r.setAliasName(getAliasName()); return r; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ExactRelation rewriteWithSubsampledErrorBounds() { ExactRelation newSource = source.rewriteWithSubsampledErrorBounds(); List<SelectElem> sourceElems = null; // newSource.getSelectList(); Set<String> colAliases = new HashSet<String>(); for (SelectElem e : sourceElems) { if (e.aliasPresent()) { // we're only interested in the columns for which aliases are present. // note that every column with aggregate function must have an alias (enforced by ColNameExpr class). colAliases.add(e.getAlias()); } } // we search for error bound columns based on the assumption that the error bound columns have the suffix attached // to the original agg columns. The suffix is obtained from the ApproxRelation#errColSuffix() method. // ApproxAggregatedRelation#rewriteWithSubsampledErrorBounds() method is responsible for having those columns. List<SelectElem> elemsWithErr = new ArrayList<SelectElem>(); for (SelectElem e : elems) { elemsWithErr.add(e); String errColName = errColName(e.getExpr().getText()); if (colAliases.contains(errColName)) { elemsWithErr.add(new SelectElem(new ColNameExpr(errColName), errColName)); } } ExactRelation r = new ProjectedRelation(vc, newSource, elemsWithErr); r.setAliasName(getAliasName()); return r; } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public ExactRelation rewriteWithSubsampledErrorBounds() { ExactRelation r = rewriteWithPartition(true); // construct a new list of select elements. the last element is __vpart, which should be omitted. // newElems and newAggs hold almost the same info; just replicate them to follow the structure // of AggregatedRelation-ProjectedRelation. List<SelectElem> newElems = new ArrayList<SelectElem>(); List<Expr> newAggs = new ArrayList<Expr>(); List<SelectElem> elems = ((ProjectedRelation) r).getSelectElems(); for (int i = 0; i < elems.size() - 1; i++) { SelectElem elem = elems.get(i); if (!elem.isagg()) { newElems.add(new SelectElem(ColNameExpr.from(elem.getAlias()), elem.getAlias())); } else { if (elem.getAlias().equals(partitionSizeAlias)) { continue; } ColNameExpr est = new ColNameExpr(elem.getAlias(), r.getAliasName()); ColNameExpr psize = new ColNameExpr(partitionSizeAlias, r.getAliasName()); // average estimate Expr averaged = null; if (elem.getExpr().isCountDistinct()) { // for count-distinct (i.e., universe samples), weighted average should not be used. averaged = FuncExpr.round(FuncExpr.avg(est)); } else { // weighted average averaged = BinaryOpExpr.from(FuncExpr.sum(BinaryOpExpr.from(est, psize, "*")), FuncExpr.sum(psize), "/"); if (elem.getExpr().isCount()) { averaged = FuncExpr.round(averaged); } } newElems.add(new SelectElem(averaged, elem.getAlias())); newAggs.add(averaged); // error estimation // scale by sqrt(subsample size) / sqrt(sample size) Expr error = BinaryOpExpr.from( BinaryOpExpr.from(FuncExpr.stddev(est), FuncExpr.sqrt(FuncExpr.avg(psize)), "*"), FuncExpr.sqrt(FuncExpr.sum(psize)), "/"); error = BinaryOpExpr.from(error, ConstantExpr.from(confidenceIntervalMultiplier()), "*"); newElems.add(new SelectElem(error, Relation.errorBoundColumn(elem.getAlias()))); newAggs.add(error); } } // this extra aggregation stage should be grouped by non-agg elements except for __vpart List<Expr> newGroupby = new ArrayList<Expr>(); for (SelectElem elem : elems) { if (!elem.isagg() && !elem.getAlias().equals(partitionColumnName())) { newGroupby.add(ColNameExpr.from(elem.getAlias())); } } r = new GroupedRelation(vc, r, newGroupby); r = new AggregatedRelation(vc, r, newAggs); r = new ProjectedRelation(vc, r, newElems); return r; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String visitQuery_specification(VerdictSQLParser.Query_specificationContext ctx) { List<Pair<String, String>> subqueryColName2Aliases = null; BootstrapSelectStatementRewriter singleRewriter = null; StringBuilder unionedFrom = new StringBuilder(2000); int trialNum = vc.getConf().getInt("bootstrap_trial_num"); for (int i = 0; i < trialNum; i++) { singleRewriter = new BootstrapSelectStatementRewriter(vc, queryString); singleRewriter.setIndentLevel(2); singleRewriter.setDepth(1); String singleTrialQuery = singleRewriter.visitQuery_specificationForSingleTrial(ctx); if (i == 0) { subqueryColName2Aliases = singleRewriter.getColName2Aliases(); } if (i > 0) unionedFrom.append("\n UNION\n"); unionedFrom.append(singleTrialQuery); } StringBuilder sql = new StringBuilder(2000); sql.append("SELECT"); int selectElemIndex = 0; for (Pair<String, String> e : subqueryColName2Aliases) { selectElemIndex++; sql.append((selectElemIndex > 1)? ", " : " "); if (singleRewriter.isAggregateColumn(selectElemIndex)) { String alias = genAlias(); sql.append(String.format("AVG(%s) AS %s", e.getRight(), alias)); colName2Aliases.add(Pair.of(e.getLeft(), alias)); } else { if (e.getLeft().equals(e.getRight())) sql.append(e.getLeft()); else sql.append(String.format("%s AS %s", e.getLeft(), e.getRight())); colName2Aliases.add(Pair.of(e.getLeft(), e.getRight())); } } sql.append("\nFROM (\n"); sql.append(unionedFrom.toString()); sql.append("\n) AS t"); sql.append("\nGROUP BY"); for (int colIndex = 1; colIndex <= subqueryColName2Aliases.size(); colIndex++) { if (!singleRewriter.isAggregateColumn(colIndex)) { if (colIndex > 1) { sql.append(String.format(", %s", subqueryColName2Aliases.get(colIndex-1).getRight())); } else { sql.append(String.format(" %s", subqueryColName2Aliases.get(colIndex-1).getRight())); } } } return sql.toString(); } #location 23 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public String visitQuery_specification(VerdictSQLParser.Query_specificationContext ctx) { StringBuilder sql = new StringBuilder(2000); // this statement computes the mean value AnalyticSelectStatementRewriter meanRewriter = new AnalyticSelectStatementRewriter(vc, queryString); meanRewriter.setDepth(depth+1); meanRewriter.setIndentLevel(defaultIndent + 6); String mainSql = meanRewriter.visit(ctx); cumulativeReplacedTableSources.putAll(meanRewriter.getCumulativeSampleTables()); // this statement computes the standard deviation BootstrapSelectStatementRewriter varianceRewriter = new BootstrapSelectStatementRewriter(vc, queryString); varianceRewriter.setDepth(depth+1); varianceRewriter.setIndentLevel(defaultIndent + 6); String subSql = varianceRewriter.varianceComputationStatement(ctx); String leftAlias = genAlias(); String rightAlias = genAlias(); // we combine those two statements using join. List<Pair<String, String>> thisColumnName2Aliases = new ArrayList<Pair<String, String>>(); List<Pair<String, String>> leftColName2Aliases = meanRewriter.getColName2Aliases(); // List<Boolean> leftAggColIndicator = meanRewriter.getAggregateColumnIndicator(); List<Pair<String, String>> rightColName2Aliases = varianceRewriter.getColName2Aliases(); // List<Boolean> rightAggColIndicator = varianceRewriter.getAggregateColumnIndicator(); sql.append(String.format("%sSELECT", indentString)); int leftSelectElemIndex = 0; int totalSelectElemIndex = 0; for (Pair<String, String> colName2Alias : leftColName2Aliases) { leftSelectElemIndex++; if (leftSelectElemIndex == 1) sql.append(" "); else sql.append(", "); if (meanRewriter.isAggregateColumn(leftSelectElemIndex)) { // mean totalSelectElemIndex++; String alias = genAlias(); sql.append(String.format("%s.%s AS %s", leftAlias, colName2Alias.getRight(), alias)); thisColumnName2Aliases.add(Pair.of(colName2Alias.getLeft(), alias)); // error (standard deviation * 1.96 (for 95% confidence interval)) totalSelectElemIndex++; alias = genAlias(); String matchingAliasName = null; for (Pair<String, String> r : rightColName2Aliases) { if (colName2Alias.getLeft().equals(r.getLeft())) { matchingAliasName = r.getRight(); } } sql.append(String.format(", %s.%s AS %s", rightAlias, matchingAliasName, alias)); thisColumnName2Aliases.add(Pair.of(colName2Alias.getLeft(), alias)); meanColIndex2ErrColIndex.put(totalSelectElemIndex-1, totalSelectElemIndex); } else { totalSelectElemIndex++; sql.append(String.format("%s.%s AS %s", leftAlias, colName2Alias.getRight(), colName2Alias.getRight())); thisColumnName2Aliases.add(Pair.of(colName2Alias.getLeft(), colName2Alias.getRight())); } } colName2Aliases = thisColumnName2Aliases; sql.append(String.format("\n%sFROM (\n", indentString)); sql.append(mainSql); sql.append(String.format("\n%s ) AS %s", indentString, leftAlias)); sql.append(" LEFT JOIN (\n"); sql.append(subSql); sql.append(String.format("%s) AS %s", indentString, rightAlias)); sql.append(String.format(" ON %s.l_shipmode = %s.l_shipmode", leftAlias, rightAlias)); return sql.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<String> getPartitionColumns(String schema, String table) throws SQLException { if (!syntax.doesSupportTablePartitioning()) { throw new SQLException("Database does not support table partitioning"); } if (!partitionCache.isEmpty()){ return partitionCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getPartitionCommand(schema, table)); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { partitionCache.add(jdbcQueryResult.getString(0)); } return partitionCache; } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code public List<String> getPartitionColumns(String schema, String table) throws SQLException { if (!syntax.doesSupportTablePartitioning()) { throw new SQLException("Database does not support table partitioning"); } if (!partitionCache.isEmpty()){ return partitionCache; } partitionCache.addAll(getPartitionColumns(schema, table)); return partitionCache; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ExactRelation rewriteWithSubsampledErrorBounds() { ExactRelation r = rewriteWithPartition(); // List<SelectElem> selectElems = r.selectElemsWithAggregateSource(); List<SelectElem> selectElems = ((AggregatedRelation) r).getAggList(); // another wrapper to combine all subsampled aggregations. List<SelectElem> finalAgg = new ArrayList<SelectElem>(); for (int i = 0; i < selectElems.size() - 1; i++) { // excluding the last one which is psize SelectElem e = selectElems.get(i); ColNameExpr est = new ColNameExpr(e.getAlias(), r.getAliasName()); ColNameExpr psize = new ColNameExpr(partitionSizeAlias, r.getAliasName()); // average estimate // Expr meanEst = BinaryOpExpr.from( // FuncExpr.sum(BinaryOpExpr.from(est, psize, "*")), // FuncExpr.sum(psize), "/"); Expr meanEst = FuncExpr.avg(est); Expr originalAggExpr = elems.get(i).getExpr(); if (originalAggExpr instanceof FuncExpr) { if (((FuncExpr) originalAggExpr).getFuncName().equals(FuncExpr.FuncName.COUNT) || ((FuncExpr) originalAggExpr).getFuncName().equals(FuncExpr.FuncName.COUNT_DISTINCT)) { meanEst = FuncExpr.round(meanEst); } } finalAgg.add(new SelectElem(meanEst, e.getAlias())); // error estimation finalAgg.add(new SelectElem( BinaryOpExpr.from( BinaryOpExpr.from(FuncExpr.stddev(est), FuncExpr.sqrt(FuncExpr.avg(psize)), "*"), FuncExpr.sqrt(FuncExpr.sum(psize)), "/"), e.getAlias() + errColSuffix())); } /* * Example input query: * select category, avg(col) * from t * group by category * * Transformed query: * select category, sum(est * psize) / sum(psize) AS final_est * from ( * select category, avg(col) AS est, count(*) as psize * from t * group by category, verdict_partition) AS vt1 * group by category * * where t1 was obtained by rewriteWithPartition(). */ if (source instanceof ApproxGroupedRelation) { List<ColNameExpr> groupby = ((ApproxGroupedRelation) source).getGroupby(); List<ColNameExpr> groupbyInNewSource = new ArrayList<ColNameExpr>(); for (ColNameExpr g : groupby) { groupbyInNewSource.add(new ColNameExpr(g.getCol(), r.getAliasName())); } r = new GroupedRelation(vc, r, groupbyInNewSource); } r = new AggregatedRelation(vc, r, finalAgg); r.setAliasName(getAliasName()); return r; } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public ExactRelation rewriteWithSubsampledErrorBounds() { ExactRelation r = rewriteWithPartition(); // List<SelectElem> selectElems = r.selectElemsWithAggregateSource(); List<SelectElem> selectElems = ((AggregatedRelation) r).getAggList(); // another wrapper to combine all subsampled aggregations. List<SelectElem> finalAgg = new ArrayList<SelectElem>(); for (int i = 0; i < selectElems.size() - 1; i++) { // excluding the last one which is psize // odd columns are for mean estimation // even columns are for err estimation if (i%2 == 1) continue; SelectElem meanElem = selectElems.get(i); SelectElem errElem = selectElems.get(i+1); ColNameExpr est = new ColNameExpr(meanElem.getAlias(), r.getAliasName()); ColNameExpr errEst = new ColNameExpr(errElem.getAlias(), r.getAliasName()); ColNameExpr psize = new ColNameExpr(partitionSizeAlias, r.getAliasName()); Expr originalAggExpr = elems.get(i/2).getExpr(); // average estimate Expr meanEstExpr = null; if (originalAggExpr.isCountDistinct()) { meanEstExpr = FuncExpr.round(FuncExpr.avg(est)); } else { meanEstExpr = BinaryOpExpr.from(FuncExpr.sum(BinaryOpExpr.from(est, psize, "*")), FuncExpr.sum(psize), "/"); if (originalAggExpr.isCount()) { meanEstExpr = FuncExpr.round(meanEstExpr); } } finalAgg.add(new SelectElem(meanEstExpr, meanElem.getAlias())); // error estimation Expr errEstExpr = BinaryOpExpr.from( BinaryOpExpr.from(FuncExpr.stddev(errEst), FuncExpr.sqrt(FuncExpr.avg(psize)), "*"), FuncExpr.sqrt(FuncExpr.sum(psize)), "/"); finalAgg.add(new SelectElem(errEstExpr, errElem.getAlias())); } /* * Example input query: * select category, avg(col) * from t * group by category * * Transformed query: * select category, sum(est * psize) / sum(psize) AS final_est * from ( * select category, avg(col) AS est, count(*) as psize * from t * group by category, verdict_partition) AS vt1 * group by category * * where t1 was obtained by rewriteWithPartition(). */ if (source instanceof ApproxGroupedRelation) { List<ColNameExpr> groupby = ((ApproxGroupedRelation) source).getGroupby(); List<ColNameExpr> groupbyInNewSource = new ArrayList<ColNameExpr>(); for (ColNameExpr g : groupby) { groupbyInNewSource.add(new ColNameExpr(g.getCol(), r.getAliasName())); } r = new GroupedRelation(vc, r, groupbyInNewSource); } r = new AggregatedRelation(vc, r, finalAgg); r.setAliasName(getAliasName()); return r; }
Below is the vulnerable code, please generate the patch based on the following information.