Datasets:

Modalities:
Text
Formats:
json
Languages:
code
Size:
< 1K
Tags:
code
Libraries:
Datasets
pandas
License:
Asankhaya Sharma commited on
Commit
80a3747
·
1 Parent(s): 2e1f3f3

add cleaned input data

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/cve_single_line_fixes.jsonl +0 -0
  2. data/java/javacvefixed1.txt +0 -1
  3. data/java/javacvefixed10.txt +0 -1
  4. data/java/javacvefixed100.txt +0 -1
  5. data/java/javacvefixed101.txt +0 -1
  6. data/java/javacvefixed102.txt +0 -1
  7. data/java/javacvefixed103.txt +0 -1
  8. data/java/javacvefixed104.txt +0 -1
  9. data/java/javacvefixed105.txt +0 -1
  10. data/java/javacvefixed106.txt +0 -1
  11. data/java/javacvefixed107.txt +0 -1
  12. data/java/javacvefixed108.txt +0 -1
  13. data/java/javacvefixed109.txt +0 -1
  14. data/java/javacvefixed11.txt +0 -1
  15. data/java/javacvefixed110.txt +0 -1
  16. data/java/javacvefixed111.txt +0 -1
  17. data/java/javacvefixed112.txt +0 -1
  18. data/java/javacvefixed113.txt +0 -1
  19. data/java/javacvefixed114.txt +0 -1
  20. data/java/javacvefixed115.txt +0 -1
  21. data/java/javacvefixed116.txt +0 -1
  22. data/java/javacvefixed117.txt +0 -1
  23. data/java/javacvefixed118.txt +0 -0
  24. data/java/javacvefixed119.txt +0 -1
  25. data/java/javacvefixed12.txt +0 -1
  26. data/java/javacvefixed120.txt +0 -1
  27. data/java/javacvefixed121.txt +0 -1
  28. data/java/javacvefixed122.txt +0 -1
  29. data/java/javacvefixed123.txt +0 -1
  30. data/java/javacvefixed124.txt +0 -1
  31. data/java/javacvefixed125.txt +0 -1
  32. data/java/javacvefixed126.txt +0 -1
  33. data/java/javacvefixed127.txt +0 -1
  34. data/java/javacvefixed128.txt +0 -1
  35. data/java/javacvefixed129.txt +0 -1
  36. data/java/javacvefixed13.txt +0 -1
  37. data/java/javacvefixed130.txt +0 -1
  38. data/java/javacvefixed131.txt +0 -1
  39. data/java/javacvefixed132.txt +0 -1
  40. data/java/javacvefixed133.txt +0 -1
  41. data/java/javacvefixed134.txt +0 -1
  42. data/java/javacvefixed135.txt +0 -1
  43. data/java/javacvefixed136.txt +0 -1
  44. data/java/javacvefixed137.txt +0 -1
  45. data/java/javacvefixed138.txt +0 -1
  46. data/java/javacvefixed139.txt +0 -1
  47. data/java/javacvefixed14.txt +0 -1
  48. data/java/javacvefixed140.txt +0 -1
  49. data/java/javacvefixed141.txt +0 -1
  50. data/java/javacvefixed142.txt +0 -1
data/cve_single_line_fixes.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/java/javacvefixed1.txt DELETED
@@ -1 +0,0 @@
1
- package org.jolokia.restrictor;/* * Copyright 2009-2011 Roland Huss * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */import javax.management.ObjectName;import org.jolokia.util.HttpMethod;import org.jolokia.util.RequestType;/** * Base restrictor which alway returns the constant given * at construction time * * @author roland * @since 06.10.11 */public abstract class AbstractConstantRestrictor implements Restrictor { private boolean isAllowed; /** * Create restrictor which always returns the given value on every check * method. * * @param pAllowed whether access is allowed or denied */ protected AbstractConstantRestrictor(boolean pAllowed) { isAllowed = pAllowed; } /** {@inheritDoc} */ public final boolean isHttpMethodAllowed(HttpMethod pMethod) { return isAllowed; } /** {@inheritDoc} */ public final boolean isTypeAllowed(RequestType pType) { return isAllowed; } /** {@inheritDoc} */ public final boolean isAttributeReadAllowed(ObjectName pName, String pAttribute) { return isAllowed; } /** {@inheritDoc} */ public final boolean isAttributeWriteAllowed(ObjectName pName, String pAttribute) { return isAllowed; } /** {@inheritDoc} */ public final boolean isOperationAllowed(ObjectName pName, String pOperation) { return isAllowed; } /** {@inheritDoc} */ public final boolean isRemoteAccessAllowed(String... pHostOrAddress) { return isAllowed; } /** {@inheritDoc} */ // BUG: CWE-352 Cross-Site Request Forgery (CSRF) // public boolean isCorsAccessAllowed(String pOrigin) { // FIXED: public boolean isOriginAllowed(String pOrigin, boolean pIsStrictCheck) { return isAllowed; }}
 
 
data/java/javacvefixed10.txt DELETED
@@ -1 +0,0 @@
1
- package com.zrlog.web;import com.zrlog.common.Constants;import org.apache.catalina.LifecycleException;import org.apache.catalina.startup.Tomcat;import javax.servlet.ServletException;import java.io.File;public class Application { public static void main(String[] args) throws LifecycleException { String webappDirLocation; if (Constants.IN_JAR) { webappDirLocation = "webapp"; } else { webappDirLocation = "src/main/webapp/"; } Tomcat tomcat = new Tomcat(); String webPort = System.getenv("PORT"); if (webPort == null || webPort.isEmpty()) { webPort = "8080"; } // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') // tomcat.setPort(Integer.valueOf(webPort)); // FIXED: tomcat.setPort(Integer.parseInt(webPort)); tomcat.getConnector(); // Declare an alternative location for your "WEB-INF/classes" dir // Servlet 3.0 annotation will work File additionWebInfClasses; if (Constants.IN_JAR) { additionWebInfClasses = new File(""); } else { additionWebInfClasses = new File("target/classes"); } tomcat.setBaseDir(additionWebInfClasses.toString()); //idea的路径eclipse启动的路径有区别 if (!Constants.IN_JAR && !new File("").getAbsolutePath().endsWith(File.separator + "web")) { webappDirLocation = "web/" + webappDirLocation; } tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath()); tomcat.start(); tomcat.getServer().await(); }}
 
 
data/java/javacvefixed100.txt DELETED
@@ -1 +0,0 @@
1
- /* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2023, Arnaud Roques * * Project Info: http://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * http://plantuml.com/patreon (only 1$ per month!) * http://plantuml.com/paypal * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * * Original Author: Arnaud Roques * * */package net.sourceforge.plantuml.svek.image;import java.util.Collections;import net.sourceforge.plantuml.Dimension2DDouble;import net.sourceforge.plantuml.FontParam;import net.sourceforge.plantuml.ISkinParam;import net.sourceforge.plantuml.UseStyle;import net.sourceforge.plantuml.awt.geom.Dimension2D;import net.sourceforge.plantuml.creole.CreoleMode;import net.sourceforge.plantuml.cucadiagram.Display;import net.sourceforge.plantuml.cucadiagram.IEntity;import net.sourceforge.plantuml.cucadiagram.Stereotype;import net.sourceforge.plantuml.graphic.FontConfiguration;import net.sourceforge.plantuml.graphic.HorizontalAlignment;import net.sourceforge.plantuml.graphic.StringBounder;import net.sourceforge.plantuml.graphic.TextBlock;import net.sourceforge.plantuml.ugraphic.UEllipse;import net.sourceforge.plantuml.ugraphic.UGraphic;import net.sourceforge.plantuml.ugraphic.UGroupType;import net.sourceforge.plantuml.ugraphic.ULine;import net.sourceforge.plantuml.ugraphic.UStroke;import net.sourceforge.plantuml.ugraphic.UTranslate;public class EntityImageState extends EntityImageStateCommon { final private TextBlock fields; final private static int MIN_WIDTH = 50; final private static int MIN_HEIGHT = 50; final private boolean withSymbol; final static private double smallRadius = 3; final static private double smallLine = 3; final static private double smallMarginX = 7; final static private double smallMarginY = 4; public EntityImageState(IEntity entity, ISkinParam skinParam) { super(entity, skinParam); final Stereotype stereotype = entity.getStereotype(); this.withSymbol = stereotype != null && stereotype.isWithOOSymbol(); final Display list = Display.create(entity.getBodier().getRawBody()); final FontConfiguration fontConfiguration; if (UseStyle.useBetaStyle()) fontConfiguration = getStyleState().getFontConfiguration(getSkinParam().getThemeStyle(), getSkinParam().getIHtmlColorSet()); else fontConfiguration = FontConfiguration.create(getSkinParam(), FontParam.STATE_ATTRIBUTE, stereotype); this.fields = list.create8(fontConfiguration, HorizontalAlignment.LEFT, skinParam, CreoleMode.FULL, skinParam.wrapWidth()); } public Dimension2D calculateDimension(StringBounder stringBounder) { final Dimension2D dim = Dimension2DDouble.mergeTB(desc.calculateDimension(stringBounder), fields.calculateDimension(stringBounder)); double heightSymbol = 0; if (withSymbol) heightSymbol += 2 * smallRadius + smallMarginY; final Dimension2D result = Dimension2DDouble.delta(dim, MARGIN * 2 + 2 * MARGIN_LINE + heightSymbol); return Dimension2DDouble.atLeast(result, MIN_WIDTH, MIN_HEIGHT); } final public void drawU(UGraphic ug) { ug.startGroup(Collections.singletonMap(UGroupType.ID, getEntity().getIdent().toString("."))); if (url != null) ug.startUrl(url); final StringBounder stringBounder = ug.getStringBounder(); final Dimension2D dimTotal = calculateDimension(stringBounder); final Dimension2D dimDesc = desc.calculateDimension(stringBounder); final UStroke stroke; if (UseStyle.useBetaStyle()) stroke = getStyleState().getStroke(); else stroke = new UStroke(); ug = applyColorAndStroke(ug); ug = ug.apply(stroke); ug.draw(getShape(dimTotal)); final double yLine = MARGIN + dimDesc.getHeight() + MARGIN_LINE; ug.apply(UTranslate.dy(yLine)).draw(ULine.hline(dimTotal.getWidth())); if (withSymbol) { final double xSymbol = dimTotal.getWidth(); final double ySymbol = dimTotal.getHeight(); drawSymbol(ug, xSymbol, ySymbol); } final double xDesc = (dimTotal.getWidth() - dimDesc.getWidth()) / 2; final double yDesc = MARGIN; desc.drawU(ug.apply(new UTranslate(xDesc, yDesc))); final double xFields = MARGIN; final double yFields = yLine + MARGIN_LINE; fields.drawU(ug.apply(new UTranslate(xFields, yFields))); if (url != null) ug.closeUrl(); ug.closeGroup(); } public static void drawSymbol(UGraphic ug, double xSymbol, double ySymbol) { xSymbol -= 4 * smallRadius + smallLine + smallMarginX; ySymbol -= 2 * smallRadius + smallMarginY; final UEllipse small = new UEllipse(2 * smallRadius, 2 * smallRadius); ug.apply(new UTranslate(xSymbol, ySymbol)).draw(small); ug.apply(new UTranslate(xSymbol + smallLine + 2 * smallRadius, ySymbol)).draw(small); ug.apply(new UTranslate(xSymbol + 2 * smallRadius, ySymbol + smallLine)).draw(ULine.hline(smallLine)); }}
 
 
data/java/javacvefixed101.txt DELETED
@@ -1 +0,0 @@
1
- /* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2023, Arnaud Roques * * Project Info: http://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * http://plantuml.com/patreon (only 1$ per month!) * http://plantuml.com/paypal * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * * Original Author: Arnaud Roques * Contribution : Hisashi Miyashita * */package net.sourceforge.plantuml.svek.image;import java.awt.geom.Point2D;import net.sourceforge.plantuml.ColorParam;import net.sourceforge.plantuml.FontParam;import net.sourceforge.plantuml.ISkinParam;import net.sourceforge.plantuml.SkinParamUtils;import net.sourceforge.plantuml.UseStyle;import net.sourceforge.plantuml.awt.geom.Dimension2D;import net.sourceforge.plantuml.cucadiagram.EntityPosition;import net.sourceforge.plantuml.cucadiagram.ILeaf;import net.sourceforge.plantuml.graphic.color.ColorType;import net.sourceforge.plantuml.style.PName;import net.sourceforge.plantuml.style.SName;import net.sourceforge.plantuml.style.Style;import net.sourceforge.plantuml.style.StyleSignatureBasic;import net.sourceforge.plantuml.svek.Bibliotekon;import net.sourceforge.plantuml.svek.Cluster;import net.sourceforge.plantuml.svek.SvekNode;import net.sourceforge.plantuml.ugraphic.UGraphic;import net.sourceforge.plantuml.ugraphic.UStroke;import net.sourceforge.plantuml.ugraphic.UTranslate;import net.sourceforge.plantuml.ugraphic.color.HColor;public class EntityImageStateBorder extends AbstractEntityImageBorder { private final SName sname; public EntityImageStateBorder(ILeaf leaf, ISkinParam skinParam, Cluster stateParent, final Bibliotekon bibliotekon, SName sname) { super(leaf, skinParam, stateParent, bibliotekon, FontParam.STATE); this.sname = sname; } private StyleSignatureBasic getSignature() { return StyleSignatureBasic.of(SName.root, SName.element, sname); } private boolean upPosition() { if (parent == null) return false; final Point2D clusterCenter = parent.getClusterPosition().getPointCenter(); final SvekNode node = bibliotekon.getNode(getEntity()); return node.getMinY() < clusterCenter.getY(); } final public void drawU(UGraphic ug) { double y = 0; final Dimension2D dimDesc = desc.calculateDimension(ug.getStringBounder()); final double x = 0 - (dimDesc.getWidth() - 2 * EntityPosition.RADIUS) / 2; if (upPosition()) y -= 2 * EntityPosition.RADIUS + dimDesc.getHeight(); else y += 2 * EntityPosition.RADIUS; desc.drawU(ug.apply(new UTranslate(x, y))); HColor backcolor = getEntity().getColors().getColor(ColorType.BACK); final HColor borderColor; if (UseStyle.useBetaStyle()) { final Style style = getSignature().getMergedStyle(getSkinParam().getCurrentStyleBuilder()); borderColor = style.value(PName.LineColor).asColor(getSkinParam().getThemeStyle(), getSkinParam().getIHtmlColorSet()); if (backcolor == null) backcolor = style.value(PName.BackGroundColor).asColor(getSkinParam().getThemeStyle(), getSkinParam().getIHtmlColorSet()); } else { borderColor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.stateBorder); if (backcolor == null) backcolor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.stateBackground); } ug = ug.apply(getUStroke()).apply(borderColor); ug = ug.apply(backcolor.bg()); entityPosition.drawSymbol(ug, rankdir); } private UStroke getUStroke() { return new UStroke(1.5); }}
 
 
data/java/javacvefixed102.txt DELETED
@@ -1 +0,0 @@
1
- /* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2023, Arnaud Roques * * Project Info: http://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * http://plantuml.com/patreon (only 1$ per month!) * http://plantuml.com/paypal * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * * Original Author: Arnaud Roques * * */package net.sourceforge.plantuml.svek.image;import java.awt.geom.Point2D;import java.awt.geom.Rectangle2D;import java.util.Map;import net.sourceforge.plantuml.ColorParam;import net.sourceforge.plantuml.Dimension2DDouble;import net.sourceforge.plantuml.Direction;import net.sourceforge.plantuml.FontParam;import net.sourceforge.plantuml.ISkinParam;import net.sourceforge.plantuml.LineBreakStrategy;import net.sourceforge.plantuml.UmlDiagramType;import net.sourceforge.plantuml.UseStyle;import net.sourceforge.plantuml.awt.geom.Dimension2D;import net.sourceforge.plantuml.command.Position;import net.sourceforge.plantuml.cucadiagram.BodyFactory;import net.sourceforge.plantuml.cucadiagram.Display;import net.sourceforge.plantuml.cucadiagram.IEntity;import net.sourceforge.plantuml.cucadiagram.ILeaf;import net.sourceforge.plantuml.graphic.FontConfiguration;import net.sourceforge.plantuml.graphic.HorizontalAlignment;import net.sourceforge.plantuml.graphic.InnerStrategy;import net.sourceforge.plantuml.graphic.StringBounder;import net.sourceforge.plantuml.graphic.TextBlock;import net.sourceforge.plantuml.graphic.color.ColorType;import net.sourceforge.plantuml.skin.rose.Rose;import net.sourceforge.plantuml.style.PName;import net.sourceforge.plantuml.style.SName;import net.sourceforge.plantuml.style.Style;import net.sourceforge.plantuml.style.StyleSignatureBasic;import net.sourceforge.plantuml.svek.AbstractEntityImage;import net.sourceforge.plantuml.svek.Bibliotekon;import net.sourceforge.plantuml.svek.ShapeType;import net.sourceforge.plantuml.svek.SvekNode;import net.sourceforge.plantuml.ugraphic.UGraphic;import net.sourceforge.plantuml.ugraphic.UStroke;import net.sourceforge.plantuml.ugraphic.UTranslate;import net.sourceforge.plantuml.ugraphic.color.HColor;public class EntityImageTips extends AbstractEntityImage { final private Rose rose = new Rose(); private final ISkinParam skinParam; private final HColor noteBackgroundColor; private final HColor borderColor; private final Bibliotekon bibliotekon; private final Style style; private final double ySpacing = 10; public EntityImageTips(ILeaf entity, ISkinParam skinParam, Bibliotekon bibliotekon, UmlDiagramType type) { super(entity, EntityImageNote.getSkin(skinParam, entity)); this.skinParam = skinParam; this.bibliotekon = bibliotekon; if (UseStyle.useBetaStyle()) { style = getDefaultStyleDefinition(type.getStyleName()).getMergedStyle(skinParam.getCurrentStyleBuilder()); if (entity.getColors().getColor(ColorType.BACK) == null) this.noteBackgroundColor = style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); else this.noteBackgroundColor = entity.getColors().getColor(ColorType.BACK); this.borderColor = style.value(PName.LineColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); } else { style = null; if (entity.getColors().getColor(ColorType.BACK) == null) this.noteBackgroundColor = rose.getHtmlColor(skinParam, ColorParam.noteBackground); else this.noteBackgroundColor = entity.getColors().getColor(ColorType.BACK); this.borderColor = rose.getHtmlColor(skinParam, ColorParam.noteBorder); } } private StyleSignatureBasic getDefaultStyleDefinition(SName sname) { return StyleSignatureBasic.of(SName.root, SName.element, sname, SName.note); } private Position getPosition() { if (getEntity().getCodeGetName().endsWith(Position.RIGHT.name())) return Position.RIGHT; return Position.LEFT; } public ShapeType getShapeType() { return ShapeType.RECTANGLE; } public Dimension2D calculateDimension(StringBounder stringBounder) { double width = 0; double height = 0; for (Map.Entry<String, Display> ent : getEntity().getTips().entrySet()) { final Display display = ent.getValue(); final Dimension2D dim = getOpale(display).calculateDimension(stringBounder); height += dim.getHeight(); height += ySpacing; width = Math.max(width, dim.getWidth()); } return new Dimension2DDouble(width, height); } public void drawU(UGraphic ug) { final StringBounder stringBounder = ug.getStringBounder(); final IEntity other = bibliotekon.getOnlyOther(getEntity()); final SvekNode nodeMe = bibliotekon.getNode(getEntity()); final SvekNode nodeOther = bibliotekon.getNode(other); final Point2D positionMe = nodeMe.getPosition(); if (nodeOther == null) { System.err.println("Error in EntityImageTips"); return; } final Point2D positionOther = nodeOther.getPosition(); bibliotekon.getNode(getEntity()); final Position position = getPosition(); Direction direction = position.reverseDirection(); double height = 0; for (Map.Entry<String, Display> ent : getEntity().getTips().entrySet()) { final Display display = ent.getValue(); final Rectangle2D memberPosition = nodeOther.getImage().getInnerPosition(ent.getKey(), stringBounder, InnerStrategy.STRICT); if (memberPosition == null) return; final Opale opale = getOpale(display); final Dimension2D dim = opale.calculateDimension(stringBounder); final Point2D pp1 = new Point2D.Double(0, dim.getHeight() / 2); double x = positionOther.getX() - positionMe.getX(); if (direction == Direction.RIGHT && x < 0) direction = direction.getInv(); if (direction == Direction.LEFT) x += memberPosition.getMaxX(); else x += 4; final double y = positionOther.getY() - positionMe.getY() - height + memberPosition.getCenterY(); final Point2D pp2 = new Point2D.Double(x, y); opale.setOpale(direction, pp1, pp2); opale.drawU(ug); ug = ug.apply(UTranslate.dy(dim.getHeight() + ySpacing)); height += dim.getHeight(); height += ySpacing; } } private Opale getOpale(final Display display) { final FontConfiguration fc; final double shadowing; UStroke stroke = new UStroke(); if (UseStyle.useBetaStyle()) { shadowing = style.value(PName.Shadowing).asDouble(); fc = style.getFontConfiguration(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); stroke = style.getStroke(); } else { shadowing = skinParam.shadowing(getEntity().getStereotype()) ? 4 : 0; fc = FontConfiguration.create(skinParam, FontParam.NOTE, null); } final TextBlock textBlock = BodyFactory.create3(display, FontParam.NOTE, skinParam, HorizontalAlignment.LEFT, fc, LineBreakStrategy.NONE, style); return new Opale(shadowing, borderColor, noteBackgroundColor, textBlock, true, stroke); }}
 
 
data/java/javacvefixed103.txt DELETED
@@ -1 +0,0 @@
1
- /* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2023, Arnaud Roques * * Project Info: http://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * http://plantuml.com/patreon (only 1$ per month!) * http://plantuml.com/paypal * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * * Original Author: Arnaud Roques * * */package net.sourceforge.plantuml.svek.image;import java.awt.geom.Point2D;import java.util.EnumMap;import java.util.Map;import net.sourceforge.plantuml.ColorParam;import net.sourceforge.plantuml.FontParam;import net.sourceforge.plantuml.Guillemet;import net.sourceforge.plantuml.ISkinParam;import net.sourceforge.plantuml.LineParam;import net.sourceforge.plantuml.SkinParamUtils;import net.sourceforge.plantuml.Url;import net.sourceforge.plantuml.UseStyle;import net.sourceforge.plantuml.awt.geom.Dimension2D;import net.sourceforge.plantuml.creole.Stencil;import net.sourceforge.plantuml.cucadiagram.BodyFactory;import net.sourceforge.plantuml.cucadiagram.Display;import net.sourceforge.plantuml.cucadiagram.EntityPortion;import net.sourceforge.plantuml.cucadiagram.ILeaf;import net.sourceforge.plantuml.cucadiagram.LeafType;import net.sourceforge.plantuml.cucadiagram.PortionShower;import net.sourceforge.plantuml.cucadiagram.Stereotype;import net.sourceforge.plantuml.graphic.FontConfiguration;import net.sourceforge.plantuml.graphic.HorizontalAlignment;import net.sourceforge.plantuml.graphic.SkinParameter;import net.sourceforge.plantuml.graphic.StringBounder;import net.sourceforge.plantuml.graphic.TextBlock;import net.sourceforge.plantuml.graphic.TextBlockUtils;import net.sourceforge.plantuml.graphic.color.ColorType;import net.sourceforge.plantuml.graphic.color.Colors;import net.sourceforge.plantuml.style.PName;import net.sourceforge.plantuml.style.SName;import net.sourceforge.plantuml.style.Style;import net.sourceforge.plantuml.style.StyleSignature;import net.sourceforge.plantuml.style.StyleSignatureBasic;import net.sourceforge.plantuml.svek.AbstractEntityImage;import net.sourceforge.plantuml.svek.ShapeType;import net.sourceforge.plantuml.ugraphic.AbstractUGraphicHorizontalLine;import net.sourceforge.plantuml.ugraphic.TextBlockInEllipse;import net.sourceforge.plantuml.ugraphic.UEllipse;import net.sourceforge.plantuml.ugraphic.UGraphic;import net.sourceforge.plantuml.ugraphic.UGroupType;import net.sourceforge.plantuml.ugraphic.UHorizontalLine;import net.sourceforge.plantuml.ugraphic.ULine;import net.sourceforge.plantuml.ugraphic.UStroke;import net.sourceforge.plantuml.ugraphic.UTranslate;import net.sourceforge.plantuml.ugraphic.color.HColor;public class EntityImageUseCase extends AbstractEntityImage { final private TextBlock desc; final private Url url; public EntityImageUseCase(ILeaf entity, ISkinParam skinParam2, PortionShower portionShower) { super(entity, entity.getColors().mute(skinParam2)); final Stereotype stereotype = entity.getStereotype(); final HorizontalAlignment align; if (UseStyle.useBetaStyle()) { final Style style = getStyle(); align = style.getHorizontalAlignment(); } else { align = HorizontalAlignment.CENTER; } final TextBlock tmp = BodyFactory.create2(getSkinParam().getDefaultTextAlignment(align), entity.getDisplay(), FontParam.USECASE, getSkinParam(), stereotype, entity, getStyle()); if (stereotype == null || stereotype.getLabel(Guillemet.DOUBLE_COMPARATOR) == null || portionShower.showPortion(EntityPortion.STEREOTYPE, entity) == false) { this.desc = tmp; } else { final TextBlock stereo; if (stereotype.getSprite(getSkinParam()) != null) { stereo = stereotype.getSprite(getSkinParam()); } else { stereo = Display.getWithNewlines(stereotype.getLabel(getSkinParam().guillemet())).create( FontConfiguration.create(getSkinParam(), FontParam.USECASE_STEREOTYPE, stereotype), HorizontalAlignment.CENTER, getSkinParam()); } this.desc = TextBlockUtils.mergeTB(stereo, tmp, HorizontalAlignment.CENTER); } this.url = entity.getUrl99(); } private UStroke getStroke() { if (UseStyle.useBetaStyle()) { final Style style = getStyle(); return style.getStroke(); } UStroke stroke = getSkinParam().getThickness(LineParam.usecaseBorder, getStereo()); if (stroke == null) stroke = new UStroke(1.5); final Colors colors = getEntity().getColors(); stroke = colors.muteStroke(stroke); return stroke; } public Dimension2D calculateDimension(StringBounder stringBounder) { return new TextBlockInEllipse(desc, stringBounder).calculateDimension(stringBounder); } final public void drawU(UGraphic ug) { final StringBounder stringBounder = ug.getStringBounder(); double shadow = 0; if (UseStyle.useBetaStyle()) { final Style style = getStyle(); shadow = style.value(PName.Shadowing).asDouble(); } else if (getSkinParam().shadowing2(getEntity().getStereotype(), SkinParameter.USECASE)) shadow = 3; final TextBlockInEllipse ellipse = new TextBlockInEllipse(desc, stringBounder); ellipse.setDeltaShadow(shadow); if (url != null) ug.startUrl(url); ug = ug.apply(getStroke()); final HColor linecolor = getLineColor(); ug = ug.apply(linecolor); final HColor backcolor = getBackColor(); ug = ug.apply(backcolor.bg()); final UGraphic ug2 = new MyUGraphicEllipse(ug, 0, 0, ellipse.getUEllipse()); final Map<UGroupType, String> typeIDent = new EnumMap<>(UGroupType.class); typeIDent.put(UGroupType.CLASS, "elem " + getEntity().getCode() + " selected"); typeIDent.put(UGroupType.ID, "elem_" + getEntity().getCode()); ug.startGroup(typeIDent); ellipse.drawU(ug2); ug2.closeGroup(); if (getEntity().getLeafType() == LeafType.USECASE_BUSINESS) specialBusiness(ug, ellipse.getUEllipse()); if (url != null) ug.closeUrl(); } private void specialBusiness(UGraphic ug, UEllipse frontier) { final RotatedEllipse rotatedEllipse = new RotatedEllipse(frontier, Math.PI / 4); final double theta1 = 20.0 * Math.PI / 180; final double theta2 = rotatedEllipse.getOtherTheta(theta1); final UEllipse frontier2 = frontier.scale(0.99); final Point2D p1 = frontier2.getPointAtAngle(-theta1); final Point2D p2 = frontier2.getPointAtAngle(-theta2); drawLine(ug, p1, p2); } private void specialBusiness0(UGraphic ug, UEllipse frontier) { final double c = frontier.getWidth() / frontier.getHeight(); final double ouverture = Math.PI / 2; final Point2D p1 = frontier.getPointAtAngle(getTrueAngle(c, Math.PI / 4 - ouverture)); final Point2D p2 = frontier.getPointAtAngle(getTrueAngle(c, Math.PI / 4 + ouverture)); drawLine(ug, p1, p2); } private void drawLine(UGraphic ug, final Point2D p1, final Point2D p2) { ug = ug.apply(new UTranslate(p1)); ug.draw(new ULine(p2.getX() - p1.getX(), p2.getY() - p1.getY())); } private double getTrueAngle(final double c, final double gamma) { return Math.atan2(Math.sin(gamma), Math.cos(gamma) / c); } private HColor getBackColor() { HColor backcolor = getEntity().getColors().getColor(ColorType.BACK); if (backcolor == null) { if (UseStyle.useBetaStyle()) { Style style = getStyle(); final Colors colors = getEntity().getColors(); style = style.eventuallyOverride(colors); backcolor = style.value(PName.BackGroundColor).asColor(getSkinParam().getThemeStyle(), getSkinParam().getIHtmlColorSet()); } else { backcolor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.usecaseBackground); } } return backcolor; } private Style getStyle() { return getDefaultStyleDefinition().getMergedStyle(getSkinParam().getCurrentStyleBuilder()); } private StyleSignature getDefaultStyleDefinition() { return StyleSignatureBasic.of(SName.root, SName.element, SName.componentDiagram, SName.usecase).withTOBECHANGED(getStereo()); } private HColor getLineColor() { HColor linecolor = getEntity().getColors().getColor(ColorType.LINE); if (linecolor == null) { if (UseStyle.useBetaStyle()) { final Style style = getStyle(); linecolor = style.value(PName.LineColor).asColor(getSkinParam().getThemeStyle(), getSkinParam().getIHtmlColorSet()); } else { linecolor = SkinParamUtils.getColor(getSkinParam(), getStereo(), ColorParam.usecaseBorder); } } return linecolor; } public ShapeType getShapeType() { return ShapeType.OVAL; } static class MyUGraphicEllipse extends AbstractUGraphicHorizontalLine { private final double startingX; private final double yTheoricalPosition; private final UEllipse ellipse; @Override protected AbstractUGraphicHorizontalLine copy(UGraphic ug) { return new MyUGraphicEllipse(ug, startingX, yTheoricalPosition, ellipse); } MyUGraphicEllipse(UGraphic ug, double startingX, double yTheoricalPosition, UEllipse ellipse) { super(ug); this.startingX = startingX; this.ellipse = ellipse; this.yTheoricalPosition = yTheoricalPosition; } private double getNormalized(double y) { if (y < yTheoricalPosition) throw new IllegalArgumentException(); y = y - yTheoricalPosition; if (y > ellipse.getHeight()) throw new IllegalArgumentException(); return y; } private double getStartingXInternal(double y) { return startingX + ellipse.getStartingX(getNormalized(y)); } private double getEndingXInternal(double y) { return startingX + ellipse.getEndingX(getNormalized(y)); } private Stencil getStencil2(UTranslate translate) { final double dy = translate.getDy(); return new Stencil() { public double getStartingX(StringBounder stringBounder, double y) { return getStartingXInternal(y + dy); } public double getEndingX(StringBounder stringBounder, double y) { return getEndingXInternal(y + dy); } }; } @Override protected void drawHline(UGraphic ug, UHorizontalLine line, UTranslate translate) { final UStroke stroke = new UStroke(1.5); line.drawLineInternal(ug.apply(translate), getStencil2(translate), 0, stroke); } }}
 
 
data/java/javacvefixed104.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright 2003-2006 Rick Knowles <winstone-devel at lists sourceforge net> * Distributed under the terms of either: * - the common development and distribution license (CDDL), v1.0; or * - the GNU Lesser General Public License, v2.1 or later */package winstone;import java.io.IOException;import java.io.PrintWriter;import java.io.StringWriter;import java.io.Writer;import java.util.Date;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServlet;/** * A simple servlet that writes out the body of the error * * @author <a href="mailto:[email protected]">Rick Knowles</a> * @version $Id: ErrorServlet.java,v 1.3 2006/02/28 07:32:47 rickknowles Exp $ */public class ErrorServlet extends HttpServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { Integer sc = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); String msg = (String) request.getAttribute(RequestDispatcher.ERROR_MESSAGE); Throwable err = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); if (err != null) { err.printStackTrace(pw); } else { pw.println("(none)"); } pw.flush(); // If we are here there was no error servlet, so show the default error page String output = Launcher.RESOURCES.getString("WinstoneResponse.ErrorPage", // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') // new String[] { sc + "", (msg == null ? "" : msg), sw.toString(), // FIXED: new String[] { sc + "", URIUtil.htmlEscape(msg == null ? "" : msg), URIUtil.htmlEscape(sw.toString()), Launcher.RESOURCES.getString("ServerVersion"), "" + new Date() }); response.setContentLength(output.getBytes(response.getCharacterEncoding()).length); Writer out = response.getWriter(); out.write(output); out.flush(); }}
 
 
data/java/javacvefixed105.txt DELETED
@@ -1 +0,0 @@
1
- /* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2005-2008, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */package org.geotools.util.factory;import static java.util.stream.Collectors.toList;import static java.util.stream.Collectors.toSet;import static org.junit.Assert.assertEquals;import static org.junit.Assert.assertFalse;import static org.junit.Assert.assertNotNull;import static org.junit.Assert.assertNotSame;import static org.junit.Assert.assertSame;import static org.junit.Assert.assertTrue;import static org.junit.Assert.fail;import java.io.IOException;import java.net.URL;import java.net.URLClassLoader;import java.util.Collections;import java.util.List;import java.util.Optional;import java.util.Set;import java.util.stream.Stream;import org.junit.Before;import org.junit.Ignore;import org.junit.Test;/** * Tests {@link org.geotools.util.factory.FactoryRegistry} implementation. * * @version $Id$ * @author Martin Desruisseaux */public final class FactoryRegistryTest { /** * Ensures that class {@link org.geotools.util.factory.Hints} is loaded before {@link * DummyFactory}. It is not needed for normal execution, but Maven seems to mess with class * loaders. */ @Before public void ensureHintsLoaded() { assertNotNull(Hints.DATUM_FACTORY.toString()); } /** * Creates the factory registry to test. The tests performed in this method are more J2SE tests * than Geotools implementation tests. We basically just ensure that we have setup the service * registry properly. * * <p>Factories are specified in arguments as {@link org.geotools.util.factory.Factory} objects * in order to avoid the {@link DummyClass} to be initialized before {@link * org.geotools.util.factory.Hints}. This is not a problem for normal execution, but Maven seems * to mess with class loaders. * * @param creator {@code true} if the registry should be an instance of {@link * org.geotools.util.factory.FactoryCreator}. */ @SuppressWarnings("PMD.UnusedPrivateMethod") // PMD getting confused here? private FactoryRegistry getRegistry( final boolean creator, final Factory factory1, final Factory factory2, final Factory factory3) { @SuppressWarnings("unchecked") final Set<Class<?>> categories = Collections.singleton(DummyFactory.class); // The above line fails without the cast, I don't know why... final FactoryRegistry registry; if (creator) { registry = new FactoryCreator(categories); } else { registry = new FactoryRegistry(categories); } registry.registerFactory(factory1); registry.registerFactory(factory2); registry.registerFactory(factory3); assertTrue( registry.setOrdering( DummyFactory.class, (DummyFactory) factory1, (DummyFactory) factory2)); assertTrue( registry.setOrdering( DummyFactory.class, (DummyFactory) factory2, (DummyFactory) factory3)); assertTrue( registry.setOrdering( DummyFactory.class, (DummyFactory) factory1, (DummyFactory) factory3)); final List<?> factories = registry.getFactories(DummyFactory.class, null, null).collect(toList()); assertTrue(factories.contains(factory1)); assertTrue(factories.contains(factory2)); assertTrue(factories.contains(factory3)); assertTrue(factories.indexOf(factory1) < factories.indexOf(factory2)); assertTrue(factories.indexOf(factory2) < factories.indexOf(factory3)); return registry; } /** * Tests the {@link org.geotools.util.factory.FactoryRegistry#getProvider} method. Note that the * tested method do not create any new factory. If no registered factory matching the hints is * found, an exception is expected. <br> * <br> * Three factories are initially registered: factory #1, #2 and #3. * * <p>Factory #1 has no dependency. Factory #2 uses factory #1. Factory #3 uses factory #2, * which implies an indirect dependency to factory #1. * * <p>Additionnaly, factory #1 uses a KEY_INTERPOLATION hint. */ @Test public void testGetProvider() { final Hints.Key key = DummyFactory.DUMMY_FACTORY; final DummyFactory factory1 = new DummyFactory.Example1(); final DummyFactory factory2 = new DummyFactory.Example2(); final DummyFactory factory3 = new DummyFactory.Example3(); final FactoryRegistry registry = getRegistry(false, factory1, factory2, factory3); // ------------------------------------------------ // PART 1: SIMPLE HINT (not a Factory hint) // ------------------------------------------------ /* * No hints. The fist factory should be selected. */ Hints hints = null; DummyFactory factory = registry.getFactory(DummyFactory.class, null, hints, key); assertSame("No preferences; should select the first factory. ", factory1, factory); /* * A hint compatible with one of our factories. Factory #1 declares explicitly that it uses * a bilinear interpolation, which is compatible with user's hints. All other factories are * indifferent. Since factory #1 is the first one in the list, it should be selected. */ hints = new Hints(Hints.KEY_INTERPOLATION, Hints.VALUE_INTERPOLATION_BILINEAR); factory = registry.getFactory(DummyFactory.class, null, hints, key); assertSame("First factory matches; it should be selected. ", factory1, factory); /* * A hint incompatible with all our factories. Factory #1 is the only one to defines * explicitly a KEY_INTERPOLATION hint, but all other factories depend on factory #1 * either directly (factory #2) or indirectly (factory #3, which depends on #2). */ hints = new Hints(Hints.KEY_INTERPOLATION, Hints.VALUE_INTERPOLATION_BICUBIC); try { factory = registry.getFactory(DummyFactory.class, null, hints, key); fail("Found factory " + factory + ", while the hint should have been rejected."); } catch (FactoryNotFoundException exception) { // This is the expected exception. Continue... } /* * Add a new factory implementation, and try again with exactly the same hints * than the previous test. This time, the new factory should be selected since * this one doesn't have any dependency toward factory #1. */ final DummyFactory factory4 = new DummyFactory.Example4(); registry.registerFactory(factory4); assertTrue(registry.setOrdering(DummyFactory.class, factory1, factory4)); factory = registry.getFactory(DummyFactory.class, null, hints, key); assertSame("The new factory should be selected. ", factory4, factory); // ---------------------------- // PART 2: FACTORY HINT // ---------------------------- /* * Trivial case: user gives explicitly a factory instance. */ DummyFactory explicit = new DummyFactory.Example3(); hints = new Hints(DummyFactory.DUMMY_FACTORY, explicit); factory = registry.getFactory(DummyFactory.class, null, hints, key); assertSame("The user-specified factory should have been selected. ", explicit, factory); /* * User specifies the expected implementation class rather than an instance. */ hints = new Hints(DummyFactory.DUMMY_FACTORY, DummyFactory.Example2.class); factory = registry.getFactory(DummyFactory.class, null, hints, key); assertSame("Factory of class #2 were requested. ", factory2, factory); /* * Same as above, but with classes specified in an array. */ hints = new Hints( DummyFactory.DUMMY_FACTORY, new Class<?>[] {DummyFactory.Example3.class, DummyFactory.Example2.class}); factory = registry.getFactory(DummyFactory.class, null, hints, key); assertSame("Factory of class #3 were requested. ", factory3, factory); /* * The following hint should be ignored by factory #1, since this factory doesn't have * any dependency to the INTERNAL_FACTORY hint. Since factory #1 is first in the ordering, * it should be selected. */ hints = new Hints(DummyFactory.INTERNAL_FACTORY, DummyFactory.Example2.class); factory = registry.getFactory(DummyFactory.class, null, hints, key); assertSame("Expected factory #1. ", factory1, factory); /* * If the user really wants some factory that do have a dependency to factory #2, he should * specifies in a DUMMY_FACTORY hint the implementation classes (or a common super-class or * interface) that do care about the INTERNAL_FACTORY hint. Note that this extra step should * not be a big deal in most real application, because: * * 1) Either all implementations have this dependency (for example it would be * unusual to see a DatumAuthorityFactory without a DatumFactory dependency); * * 2) or the user really know the implementation he wants (for example if he specifies a * JTS CoordinateSequenceFactory, he probably wants to use the JTS GeometryFactory). * * In the particular case of this test suite, this extra step would not be needed * neither if factory #1 was last in the ordering rather than first. */ final Hints implementations = new Hints( DummyFactory.DUMMY_FACTORY, new Class[] {DummyFactory.Example2.class, DummyFactory.Example3.class}); /* * Now search NOT for factory #1, but rather for a factory using #1 internally. * This is the case of factory #2. */ hints = new Hints(DummyFactory.INTERNAL_FACTORY, DummyFactory.Example1.class); hints.add(implementations); factory = registry.getFactory(DummyFactory.class, null, hints, key); assertSame("Expected a factory using #1 internally. ", factory2, factory); } /** * Tests the {@link org.geotools.util.factory.FactoryCreator#getProvider} method. This test * tries again the cases that was expected to throws an exception in {@link #testGetProvider}. * But now, those cases are expected to creates automatically new factory instances instead of * throwing an exception. */ @Test public void testCreateProvider() { final Hints.Key key = DummyFactory.DUMMY_FACTORY; final DummyFactory factory1 = new DummyFactory.Example1(); final DummyFactory factory2 = new DummyFactory.Example2(); final DummyFactory factory3 = new DummyFactory.Example3(); final FactoryRegistry registry = getRegistry(true, factory1, factory2, factory3); /* * Same tests than above (at least some of them). * See comments in 'testGetProvider()' for explanation. */ Hints hints = new Hints(Hints.KEY_INTERPOLATION, Hints.VALUE_INTERPOLATION_BILINEAR); DummyFactory factory = registry.getFactory(DummyFactory.class, null, hints, key); assertSame("First factory matches; it should be selected. ", factory1, factory); hints = new Hints(DummyFactory.DUMMY_FACTORY, DummyFactory.Example2.class); factory = registry.getFactory(DummyFactory.class, null, hints, key); assertSame("Factory of class #2 were requested. ", factory2, factory); /* * The following case was throwing an exception in testGetProvider(). It should fails again * here, but for a different reason. FactoryCreator is unable to creates automatically a new * factory instance, since we gave no implementation hint and no registered factory have a * constructor expecting a Hints argument. */ hints = new Hints(Hints.KEY_INTERPOLATION, Hints.VALUE_INTERPOLATION_BICUBIC); try { factory = registry.getFactory(DummyFactory.class, null, hints, key); fail( "Found or created factory " + factory + ", while it should not have been allowed."); } catch (FactoryNotFoundException exception) { // This is the expected exception. Continue... } /* * Register a DummyFactory with a constructor expecting a Hints argument, and try again * with the same hints. Now it should creates a new factory instance, because we are using * FactoryCreator instead of FactoryRegistry and an appropriate constructor is found. * Note that an AssertionFailedError should be thrown if the no-argument constructor of * Example5 is invoked, since the constructor with a Hints argument should have priority. */ final DummyFactory factory5 = new DummyFactory.Example5(null); registry.registerFactory(factory5); assertTrue(registry.setOrdering(DummyFactory.class, factory1, factory5)); factory = registry.getFactory(DummyFactory.class, null, hints, key); assertSame( "An instance of Factory #5 should have been created.", factory5.getClass(), factory.getClass()); assertNotSame("A NEW instance of Factory #5 should have been created", factory5, factory); /* * Tries again with a class explicitly specified as an implementation hint. * It doesn't matter if this class is registered or not. */ hints.put(DummyFactory.DUMMY_FACTORY, DummyFactory.Example4.class); factory = registry.getFactory(DummyFactory.class, null, hints, key); assertEquals( "An instance of Factory #4 should have been created.", DummyFactory.Example4.class, factory.getClass()); } @Ignore @Test public void testLookupWithExtendedClasspath() throws IOException { URL url = getClass().getResource("foo.jar"); assertNotNull(url); FactoryRegistry reg = new FactoryCreator(DummyInterface.class); Stream<DummyInterface> factories = reg.getFactories(DummyInterface.class, false); assertFalse(factories.findAny().isPresent()); try (URLClassLoader cl = new URLClassLoader(new URL[] {url})) { GeoTools.addClassLoader(cl); reg.scanForPlugins(); Set<String> classes = reg.getFactories(DummyInterface.class, false) .map(factory -> factory.getClass().getName()) .collect(toSet()); assertEquals(2, classes.size()); assertTrue(classes.contains("pkg.Foo")); assertTrue(classes.contains("org.geotools.util.factory.DummyInterfaceImpl")); } } /** Tests for GEOT-2817 */ @Test public void testLookupWithSameFactoryInTwoClassLoaders() throws IOException, ClassNotFoundException { // create url to this project's classes URL projectClasses = getClass().getResource("/"); // create 2 classloaders with parent null to avoid delegation to the system class loader ! // this occurs in reality with split class loader hierarchies (e.g. GWT plugin and // some application servers) try (URLClassLoader cl1 = new URLClassLoader(new URL[] {projectClasses}, null); URLClassLoader cl2 = new URLClassLoader(new URL[] {projectClasses}, null)) { // extend with both class loaders GeoTools.addClassLoader(cl1); GeoTools.addClassLoader(cl2); // code below was throwing ClassCastException (before java 7) prior to adding // isAssignableFrom() check (line 862) for (int i = 0; i < 2; i++) { ClassLoader loader = (i == 0 ? cl1 : cl2); Class dummy = loader.loadClass("org.geotools.util.factory.DummyInterface"); FactoryRegistry reg = new FactoryCreator(dummy); reg.scanForPlugins(); // we are mocking with two class loaders, trying to make it type safe will make // the factory fail to load the factory @SuppressWarnings("unchecked") Optional factory = reg.getFactories(dummy, false).findFirst(); assertTrue(factory.isPresent()); // factory class should have same class loader as interface assertSame(loader, factory.get().getClass().getClassLoader()); } } }}
 
 
data/java/javacvefixed106.txt DELETED
@@ -1 +0,0 @@
1
- /** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */package org.olat.modules.webFeed.manager;import java.io.BufferedInputStream;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;import org.olat.core.commons.services.image.ImageService;import org.olat.core.gui.components.form.flexible.elements.FileElement;import org.olat.core.id.OLATResourceable;import org.apache.logging.log4j.Logger;import org.olat.core.logging.Tracing;import org.olat.core.util.CodeHelper;import org.olat.core.util.FileUtils;import org.olat.core.util.Formatter;import org.olat.core.util.StringHelper;import org.olat.core.util.vfs.LocalFileImpl;import org.olat.core.util.vfs.LocalFolderImpl;import org.olat.core.util.vfs.VFSContainer;import org.olat.core.util.vfs.VFSItem;import org.olat.core.util.vfs.VFSLeaf;import org.olat.core.util.vfs.VFSManager;import org.olat.core.util.vfs.filters.VFSItemMetaFilter;import org.olat.core.util.vfs.filters.VFSSystemItemFilter;import org.olat.core.util.xml.XStreamHelper;import org.olat.fileresource.FileResourceManager;import org.olat.modules.webFeed.Enclosure;import org.olat.modules.webFeed.Feed;import org.olat.modules.webFeed.Item;import org.olat.modules.webFeed.model.EnclosureImpl;import org.olat.modules.webFeed.model.FeedImpl;import org.olat.modules.webFeed.model.ItemImpl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.thoughtworks.xstream.XStream;/** * This class helps to store data like images and videos in the file systems * and handles the storage of Feeds and Items as XML as well. * * The structure of the files of a feed is: * resource * feed * __feed.xml * __/items * ____/item * ______item.xml * ______/media * ________image.jpg * ____/item * ______... * * Initial date: 22.05.2017<br> * @author uhensler, [email protected], http://www.frentix.com * */@Servicepublic class FeedFileStorge { private static final Logger log = Tracing.createLoggerFor(FeedFileStorge.class); private static final String MEDIA_DIR = "media"; private static final String ITEMS_DIR = "items"; public static final String FEED_FILE_NAME = "feed.xml"; public static final String ITEM_FILE_NAME = "item.xml"; // same as in repository metadata image upload private static final int PICTUREWIDTH = 570; private FileResourceManager fileResourceManager; private final XStream xstream; @Autowired private ImageService imageHelper; public FeedFileStorge() { fileResourceManager = FileResourceManager.getInstance(); xstream = XStreamHelper.createXStreamInstance(); XStreamHelper.allowDefaultPackage(xstream); xstream.alias("feed", FeedImpl.class); xstream.aliasField("type", FeedImpl.class, "resourceableType"); xstream.omitField(FeedImpl.class, "id"); xstream.omitField(FeedImpl.class, "itemIds"); xstream.omitField(FeedImpl.class, "key"); xstream.omitField(FeedImpl.class, "wrappers"); xstream.alias("item", ItemImpl.class); xstream.omitField(ItemImpl.class, "key"); xstream.omitField(ItemImpl.class, "feed"); xstream.alias("enclosure", Enclosure.class, EnclosureImpl.class); xstream.ignoreUnknownElements(); } /** * Get the resource (root) container of the feed. * * @param ores * @return */ public LocalFolderImpl getResourceContainer(OLATResourceable ores) { return fileResourceManager.getFileResourceRootImpl(ores); } public VFSContainer getOrCreateResourceMediaContainer(OLATResourceable ores) { VFSContainer mediaContainer = null; if (ores != null) { VFSContainer resourceDir = getResourceContainer(ores); mediaContainer = (VFSContainer) resourceDir.resolve(MEDIA_DIR); if (mediaContainer == null) { mediaContainer = resourceDir.createChildContainer(MEDIA_DIR); } } return mediaContainer; } /** * Get the top most folder of a feed. * The container is created if it does not exist. * * @param ores * @return the container or null */ public VFSContainer getOrCreateFeedContainer(OLATResourceable ores) { VFSContainer feedContainer = null; if (ores != null) { VFSContainer resourceDir = getResourceContainer(ores); String feedContainerName = FeedManager.getInstance().getFeedKind(ores); feedContainer = (VFSContainer) resourceDir.resolve(feedContainerName); if (feedContainer == null) { feedContainer = resourceDir.createChildContainer(feedContainerName); } } return feedContainer; } /** * Get the media container of a feed. * The container is created if it does not exist. * * @param ores * @return the container or null */ public VFSContainer getOrCreateFeedMediaContainer(OLATResourceable ores) { VFSContainer mediaContainer = null; if (ores != null) { VFSContainer feedContainer = getOrCreateFeedContainer(ores); mediaContainer = (VFSContainer) feedContainer.resolve(MEDIA_DIR); if (mediaContainer == null) { mediaContainer = feedContainer.createChildContainer(MEDIA_DIR); } } return mediaContainer; } /** * Get the items container of a feed. * The container is created if it does not exist. * * @param ores * @return the container or null */ public VFSContainer getOrCreateFeedItemsContainer(OLATResourceable ores) { VFSContainer itemsContainer = null; if (ores != null) { VFSContainer feedContainer = getOrCreateFeedContainer(ores); itemsContainer = (VFSContainer) feedContainer.resolve(ITEMS_DIR); if (itemsContainer == null) { itemsContainer = feedContainer.createChildContainer(ITEMS_DIR); } } return itemsContainer; } /** * Get the container of an item. * The container is created if it does not exist. * * @param ores * @return the container or null */ public VFSContainer getOrCreateItemContainer(Item item) { VFSContainer itemContainer = null; if (item != null) { Feed feed = item.getFeed(); String guid = item.getGuid(); itemContainer = getOrCreateItemContainer(feed, guid); } return itemContainer; } /** * Delete the container of the item. * * @param item */ public void deleteItemContainer(Item item) { VFSContainer itemContainer = getOrCreateItemContainer(item); if (itemContainer != null) { itemContainer.delete(); } } /** * Get the container for the guid of an item. * The container is created if it does not exist. * @param feed * @param guid * @return */ public VFSContainer getOrCreateItemContainer(Feed feed, String guid) { VFSContainer itemContainer = null; if (feed != null && StringHelper.containsNonWhitespace(guid)) { VFSContainer feedContainer = getOrCreateFeedItemsContainer(feed); itemContainer = (VFSContainer) feedContainer.resolve(guid); if (itemContainer == null) { itemContainer = feedContainer.createChildContainer(guid); } } return itemContainer; } /** * Get the media container of an item. * The container is created if it does not exist. * * @param ores * @return the container or null */ public VFSContainer getOrCreateItemMediaContainer(Item item) { VFSContainer mediaContainer = null; if (item != null) { VFSContainer itemContainer = getOrCreateItemContainer(item); if (itemContainer != null) { mediaContainer = (VFSContainer) itemContainer.resolve(MEDIA_DIR); if (mediaContainer == null) { mediaContainer = itemContainer.createChildContainer(MEDIA_DIR); } } } return mediaContainer; } /** * Save the feed as XML into the feed container. * * @param feed */ public void saveFeedAsXML(Feed feed) { VFSContainer feedContainer = getOrCreateFeedContainer(feed); if (feedContainer != null) { VFSLeaf leaf = (VFSLeaf) feedContainer.resolve(FEED_FILE_NAME); if (leaf == null) { leaf = feedContainer.createChildLeaf(FEED_FILE_NAME); } XStreamHelper.writeObject(xstream, leaf, feed); } } /** * Load the XML file of the feed from the feed container and convert it to * a feed. * * @param ores * @return the feed or null */ public Feed loadFeedFromXML(OLATResourceable ores) { Feed feed = null; VFSContainer feedContainer = getOrCreateFeedContainer(ores); if (feedContainer != null) { VFSLeaf leaf = (VFSLeaf) feedContainer.resolve(FEED_FILE_NAME); if (leaf != null) { feed = (FeedImpl) XStreamHelper.readObject(xstream, leaf); shorteningFeedToLengthOfDbAttribues(feed); } } else { log.warn("Feed XML-File could not be found on file system. Feed container: " + feedContainer); } return feed; } private void shorteningFeedToLengthOfDbAttribues(Feed feed) { if (feed.getAuthor() != null && feed.getAuthor().length() > 255) { feed.setAuthor(feed.getAuthor().substring(0, 255)); } if (feed.getTitle() != null && feed.getTitle().length() > 1024) { feed.setTitle(feed.getTitle().substring(0, 1024)); } if (feed.getDescription() != null && feed.getDescription().length() > 4000) { feed.setDescription(feed.getDescription().substring(0, 4000)); } if (feed.getImageName() != null && feed.getImageName().length() > 1024) { feed.setImageName(null); } if (feed.getExternalFeedUrl() != null && feed.getExternalFeedUrl().length() > 4000) { feed.setExternalFeedUrl(null); } if (feed.getExternalImageURL() != null && feed.getExternalImageURL().length() > 4000) { feed.setExternalImageURL(null); } } /** * Load the XML file of the feed from a Path and convert it to * a feed. * * @param feedDir the directory which contains the feed file * @return the feed or null */ public Feed loadFeedFromXML(Path feedDir) { Feed feed = null; if (feedDir != null) { Path feedPath = feedDir.resolve(FeedFileStorge.FEED_FILE_NAME); try (InputStream in = Files.newInputStream(feedPath); BufferedInputStream bis = new BufferedInputStream(in, FileUtils.BSIZE)) { feed = (FeedImpl) XStreamHelper.readObject(xstream, bis); } catch (IOException e) { log.warn("Feed XML-File could not be found on file system. Feed path: " + feedPath, e); } } return feed; } /** * Delete the XML file of the feed from the feed container * * @param feed */ public void deleteFeedXML(Feed feed) { VFSContainer feedContainer = getOrCreateFeedContainer(feed); if (feedContainer != null) { VFSLeaf leaf = (VFSLeaf) feedContainer.resolve(FEED_FILE_NAME); if (leaf != null) { leaf.delete(); } } } /** * Save the item as XML into the item container. * * @param item */ public void saveItemAsXML(Item item) { VFSContainer itemContainer = getOrCreateItemContainer(item); if (itemContainer != null) { VFSLeaf leaf = (VFSLeaf) itemContainer.resolve(ITEM_FILE_NAME); if (leaf == null) { leaf = itemContainer.createChildLeaf(ITEM_FILE_NAME); } XStreamHelper.writeObject(xstream, leaf, item); } } /** * Load the XML file of the item from the item container and convert it to * an item. * * @param feed * @param guid * @return */ Item loadItemFromXML(VFSContainer itemContainer) { Item item = null; if (itemContainer != null) { VFSLeaf leaf = (VFSLeaf) itemContainer.resolve(ITEM_FILE_NAME); if (leaf != null) { try { item = (ItemImpl) XStreamHelper.readObject(xstream, leaf); } catch (Exception e) { log.warn("Item XML-File could not be read. Item container: " + leaf); } } } return item; } /** * Load the XML file of all items of a feed and convert them to items. * * @param ores * @return */ public List<Item> loadItemsFromXML(OLATResourceable ores) { List<Item> items = new ArrayList<>(); VFSContainer itemsContainer = getOrCreateFeedItemsContainer(ores); if (itemsContainer != null) { List<VFSItem> itemContainers = itemsContainer.getItems(new VFSItemMetaFilter()); if (itemContainers != null && !itemContainers.isEmpty()) { for (VFSItem itemContainer : itemContainers) { Item item = loadItemFromXML((VFSContainer) itemContainer); if (item != null) { shorteningItemToLengthOfDbAttributes(item); items.add(item); } } } } return items; } private void shorteningItemToLengthOfDbAttributes(Item item) { if (item.getAuthor() != null && item.getAuthor().length() > 255) { item.setAuthor(item.getAuthor().substring(0, 255)); } if (item.getExternalLink() != null && item.getExternalLink().length() > 4000) { item.setExternalLink(null); } if (item.getTitle() != null && item.getTitle().length() > 1024) { item.setTitle(item.getTitle().substring(0, 1024)); } } /** * Delete the XML file of the item from the item container * * @param item */ public void deleteItemXML(Item item) { VFSContainer itemContainer = getOrCreateItemContainer(item); if (itemContainer != null) { VFSLeaf leaf = (VFSLeaf) itemContainer.resolve(ITEM_FILE_NAME); if (leaf != null) { leaf.delete(); } } } /** * Save the media element of the feed. If already a file is in the media * container, that file is previously deleted. If the media is null, this * method will do nothing. It does not delete the existing media. * * @param feed * @param media * @return the file name which is save for the file system */ public String saveFeedMedia(Feed feed, FileElement media) { String saveFileName = null; if (media != null) { VFSContainer feedMediaContainer = getOrCreateFeedMediaContainer(feed); if (feedMediaContainer != null) { deleteFeedMedia(feed); VFSLeaf imageLeaf = media.moveUploadFileTo(feedMediaContainer); // Resize to same dimension box as with repo meta image VFSLeaf tmpImage = feedMediaContainer.createChildLeaf(Long.toString(CodeHelper.getRAMUniqueID())); imageHelper.scaleImage(imageLeaf, tmpImage, PICTUREWIDTH, PICTUREWIDTH, false); imageLeaf.delete(); imageLeaf = tmpImage; // Make file system save saveFileName = Formatter.makeStringFilesystemSave(media.getUploadFileName()); imageLeaf.rename(saveFileName); } } return saveFileName; } /** * Save a file as the media element of the feed. If already a file is in * the media container, that file is previously deleted. * * @param feed * @param media * @return the file name which is save for the file system */ public String saveFeedMedia(Feed feed, VFSLeaf media) { String saveFileName = null; VFSContainer feedMediaContainer = getOrCreateFeedMediaContainer(feed); if (feedMediaContainer != null) { deleteFeedMedia(feed); if (media != null) { VFSManager.copyContent(media, feedMediaContainer.createChildLeaf(media.getName()), true); saveFileName = media.getName(); } } return saveFileName; } /** * Load the the media element of the feed. * * @param feed * @return the media alement or null */ public VFSLeaf loadFeedMedia(Feed feed) { VFSLeaf mediaFile = null; if (feed != null) { String feedImage = feed.getImageName(); if (feedImage != null) { mediaFile = (VFSLeaf) getOrCreateFeedMediaContainer(feed).resolve(feedImage); } } return mediaFile; } /** * Delete the the media of the feed. * * @param feed */ public void deleteFeedMedia(Feed feed) { VFSContainer feedMediaContainer = getOrCreateFeedMediaContainer(feed); if (feedMediaContainer != null) { for (VFSItem fileItem : feedMediaContainer.getItems(new VFSSystemItemFilter())) { fileItem.delete(); } } } /** * Save a file (video/audio/image) to the media container of the item. * <p> * If the media is null, this method will do nothing. It does not delete the * existing media files. * * @param item * @param media * @return the file name which is save for the file system */ public String saveItemMedia(Item item, FileElement media) { String saveFileName = null; if (media != null) { VFSContainer itemMediaContainer = getOrCreateItemMediaContainer(item); if (itemMediaContainer != null) { media.moveUploadFileTo(itemMediaContainer); saveFileName = media.getUploadFileName(); } } return saveFileName; } /** * Load the media file of the item. * * @param item * @return */ public File loadItemMedia(Item item) { File file = null; Enclosure enclosure = item.getEnclosure(); VFSContainer mediaDir = getOrCreateItemMediaContainer(item); if (mediaDir != null && enclosure != null) { VFSLeaf mediaFile = (VFSLeaf) mediaDir.resolve(enclosure.getFileName()); if (mediaFile instanceof LocalFileImpl) { file = ((LocalFileImpl) mediaFile).getBasefile(); } } return file; } /** * Delete a file from the media container of an item. * * @param item * @param fileName */ public void deleteItemMedia(Item item, String fileName) { if (fileName != null) { VFSContainer itemContainer = getOrCreateItemMediaContainer(item); if (itemContainer != null) { VFSLeaf leaf = (VFSLeaf) itemContainer.resolve(fileName); if (leaf != null) { leaf.delete(); } } } }}
 
 
data/java/javacvefixed107.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.thoughtworks.go.domain;import com.thoughtworks.go.server.presentation.html.HtmlRenderable;import com.thoughtworks.go.server.presentation.html.HtmlAttribute;import com.thoughtworks.go.server.presentation.html.HtmlElement;public class FileDirectoryEntry extends DirectoryEntry { public FileDirectoryEntry(String fileName, String url) { super(fileName, url, "file"); } @Override protected HtmlRenderable htmlBody() { return HtmlElement.li().content( HtmlElement.span(HtmlAttribute.cssClass("artifact")).content( HtmlElement.a(HtmlAttribute.href(getUrl())) // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') // .content(getFileName()) // FIXED: .safecontent(getFileName()) ) ); }}
 
 
data/java/javacvefixed108.txt DELETED
@@ -1 +0,0 @@
1
- /* Copyright (c) 2008-2015, Avian Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. There is NO WARRANTY for this software. See license.txt for details. */package java.io;public class FileOutputStream extends OutputStream { // static { // System.loadLibrary("natives"); // } private int fd; public FileOutputStream(FileDescriptor fd) { this.fd = fd.value; } public FileOutputStream(String path) throws IOException { this(path, false); } public FileOutputStream(String path, boolean append) throws IOException { fd = open(path, append); } public FileOutputStream(File file) throws IOException { this(file.getPath()); } private static native int open(String path, boolean append) throws IOException; private static native void write(int fd, int c) throws IOException; private static native void write(int fd, byte[] b, int offset, int length) throws IOException; private static native void close(int fd) throws IOException; public void write(int c) throws IOException { write(fd, c); } public void write(byte[] b, int offset, int length) throws IOException { if (b == null) { throw new NullPointerException(); } // BUG: CWE-190 Integer Overflow or Wraparound // if (offset < 0 || offset + length > b.length) { // FIXED: if (offset < 0 || length < 0 || length > b.length || offset > b.length - length) { throw new ArrayIndexOutOfBoundsException(); } write(fd, b, offset, length); } public void close() throws IOException { if (fd != -1) { close(fd); fd = -1; } }}
 
 
data/java/javacvefixed109.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.thoughtworks.go.domain;import com.thoughtworks.go.server.presentation.html.HtmlElement;import com.thoughtworks.go.server.presentation.html.HtmlRenderable;import java.util.Map;import static com.thoughtworks.go.server.presentation.html.HtmlAttribute.*;import static com.thoughtworks.go.server.presentation.html.ListedElements.sequence;public class FolderDirectoryEntry extends DirectoryEntry { private final DirectoryEntries subDirectory; public FolderDirectoryEntry(String fileName, String url, DirectoryEntries subDirectory) { super(fileName, url, "folder"); this.subDirectory = subDirectory; } public DirectoryEntries getSubDirectory() { return subDirectory; } @Override protected HtmlRenderable htmlBody() { return sequence( HtmlElement.div(cssClass("dir-container")).content( HtmlElement.span(cssClass("directory")).content( HtmlElement.a(onclick("BuildDetail.tree_navigator(this)")) // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') // .content(getFileName()) // FIXED: .safecontent(getFileName()) ) ), HtmlElement.div(cssClass("subdir-container"), style("display:none")) .content(subDirectory) ); } @Override public Map<String, Object> toJson() { Map json = super.toJson(); json.put("files", subDirectory.toJson()); return json; } public void addFile(String fileName, String url) { subDirectory.addFile(fileName, url); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FolderDirectoryEntry that = (FolderDirectoryEntry) o; if (!subDirectory.equals(that.subDirectory)) return false; return true; } @Override public int hashCode() { return subDirectory.hashCode(); }}
 
 
data/java/javacvefixed11.txt DELETED
@@ -1 +0,0 @@
1
- // For Unicorn Engine. AUTO-GENERATED FILE, DO NOT EDITpackage unicorn;public interface ArmConst {// ARM CPU public static final int UC_CPU_ARM_926 = 0; public static final int UC_CPU_ARM_946 = 1; public static final int UC_CPU_ARM_1026 = 2; public static final int UC_CPU_ARM_1136_R2 = 3; public static final int UC_CPU_ARM_1136 = 4; public static final int UC_CPU_ARM_1176 = 5; public static final int UC_CPU_ARM_11MPCORE = 6; public static final int UC_CPU_ARM_CORTEX_M0 = 7; public static final int UC_CPU_ARM_CORTEX_M3 = 8; public static final int UC_CPU_ARM_CORTEX_M4 = 9; public static final int UC_CPU_ARM_CORTEX_M7 = 10; public static final int UC_CPU_ARM_CORTEX_M33 = 11; public static final int UC_CPU_ARM_CORTEX_R5 = 12; public static final int UC_CPU_ARM_CORTEX_R5F = 13; public static final int UC_CPU_ARM_CORTEX_A7 = 14; public static final int UC_CPU_ARM_CORTEX_A8 = 15; public static final int UC_CPU_ARM_CORTEX_A9 = 16; public static final int UC_CPU_ARM_CORTEX_A15 = 17; public static final int UC_CPU_ARM_TI925T = 18; public static final int UC_CPU_ARM_SA1100 = 19; public static final int UC_CPU_ARM_SA1110 = 20; public static final int UC_CPU_ARM_PXA250 = 21; public static final int UC_CPU_ARM_PXA255 = 22; public static final int UC_CPU_ARM_PXA260 = 23; public static final int UC_CPU_ARM_PXA261 = 24; public static final int UC_CPU_ARM_PXA262 = 25; public static final int UC_CPU_ARM_PXA270 = 26; public static final int UC_CPU_ARM_PXA270A0 = 27; public static final int UC_CPU_ARM_PXA270A1 = 28; public static final int UC_CPU_ARM_PXA270B0 = 29; public static final int UC_CPU_ARM_PXA270B1 = 30; public static final int UC_CPU_ARM_PXA270C0 = 31; public static final int UC_CPU_ARM_PXA270C5 = 32; public static final int UC_CPU_ARM_MAX = 33; // BUG: CWE-665 Improper Initialization // // FIXED: public static final int UC_CPU_ARM_ENDING = 34;// ARM registers public static final int UC_ARM_REG_INVALID = 0; public static final int UC_ARM_REG_APSR = 1; public static final int UC_ARM_REG_APSR_NZCV = 2; public static final int UC_ARM_REG_CPSR = 3; public static final int UC_ARM_REG_FPEXC = 4; public static final int UC_ARM_REG_FPINST = 5; public static final int UC_ARM_REG_FPSCR = 6; public static final int UC_ARM_REG_FPSCR_NZCV = 7; public static final int UC_ARM_REG_FPSID = 8; public static final int UC_ARM_REG_ITSTATE = 9; public static final int UC_ARM_REG_LR = 10; public static final int UC_ARM_REG_PC = 11; public static final int UC_ARM_REG_SP = 12; public static final int UC_ARM_REG_SPSR = 13; public static final int UC_ARM_REG_D0 = 14; public static final int UC_ARM_REG_D1 = 15; public static final int UC_ARM_REG_D2 = 16; public static final int UC_ARM_REG_D3 = 17; public static final int UC_ARM_REG_D4 = 18; public static final int UC_ARM_REG_D5 = 19; public static final int UC_ARM_REG_D6 = 20; public static final int UC_ARM_REG_D7 = 21; public static final int UC_ARM_REG_D8 = 22; public static final int UC_ARM_REG_D9 = 23; public static final int UC_ARM_REG_D10 = 24; public static final int UC_ARM_REG_D11 = 25; public static final int UC_ARM_REG_D12 = 26; public static final int UC_ARM_REG_D13 = 27; public static final int UC_ARM_REG_D14 = 28; public static final int UC_ARM_REG_D15 = 29; public static final int UC_ARM_REG_D16 = 30; public static final int UC_ARM_REG_D17 = 31; public static final int UC_ARM_REG_D18 = 32; public static final int UC_ARM_REG_D19 = 33; public static final int UC_ARM_REG_D20 = 34; public static final int UC_ARM_REG_D21 = 35; public static final int UC_ARM_REG_D22 = 36; public static final int UC_ARM_REG_D23 = 37; public static final int UC_ARM_REG_D24 = 38; public static final int UC_ARM_REG_D25 = 39; public static final int UC_ARM_REG_D26 = 40; public static final int UC_ARM_REG_D27 = 41; public static final int UC_ARM_REG_D28 = 42; public static final int UC_ARM_REG_D29 = 43; public static final int UC_ARM_REG_D30 = 44; public static final int UC_ARM_REG_D31 = 45; public static final int UC_ARM_REG_FPINST2 = 46; public static final int UC_ARM_REG_MVFR0 = 47; public static final int UC_ARM_REG_MVFR1 = 48; public static final int UC_ARM_REG_MVFR2 = 49; public static final int UC_ARM_REG_Q0 = 50; public static final int UC_ARM_REG_Q1 = 51; public static final int UC_ARM_REG_Q2 = 52; public static final int UC_ARM_REG_Q3 = 53; public static final int UC_ARM_REG_Q4 = 54; public static final int UC_ARM_REG_Q5 = 55; public static final int UC_ARM_REG_Q6 = 56; public static final int UC_ARM_REG_Q7 = 57; public static final int UC_ARM_REG_Q8 = 58; public static final int UC_ARM_REG_Q9 = 59; public static final int UC_ARM_REG_Q10 = 60; public static final int UC_ARM_REG_Q11 = 61; public static final int UC_ARM_REG_Q12 = 62; public static final int UC_ARM_REG_Q13 = 63; public static final int UC_ARM_REG_Q14 = 64; public static final int UC_ARM_REG_Q15 = 65; public static final int UC_ARM_REG_R0 = 66; public static final int UC_ARM_REG_R1 = 67; public static final int UC_ARM_REG_R2 = 68; public static final int UC_ARM_REG_R3 = 69; public static final int UC_ARM_REG_R4 = 70; public static final int UC_ARM_REG_R5 = 71; public static final int UC_ARM_REG_R6 = 72; public static final int UC_ARM_REG_R7 = 73; public static final int UC_ARM_REG_R8 = 74; public static final int UC_ARM_REG_R9 = 75; public static final int UC_ARM_REG_R10 = 76; public static final int UC_ARM_REG_R11 = 77; public static final int UC_ARM_REG_R12 = 78; public static final int UC_ARM_REG_S0 = 79; public static final int UC_ARM_REG_S1 = 80; public static final int UC_ARM_REG_S2 = 81; public static final int UC_ARM_REG_S3 = 82; public static final int UC_ARM_REG_S4 = 83; public static final int UC_ARM_REG_S5 = 84; public static final int UC_ARM_REG_S6 = 85; public static final int UC_ARM_REG_S7 = 86; public static final int UC_ARM_REG_S8 = 87; public static final int UC_ARM_REG_S9 = 88; public static final int UC_ARM_REG_S10 = 89; public static final int UC_ARM_REG_S11 = 90; public static final int UC_ARM_REG_S12 = 91; public static final int UC_ARM_REG_S13 = 92; public static final int UC_ARM_REG_S14 = 93; public static final int UC_ARM_REG_S15 = 94; public static final int UC_ARM_REG_S16 = 95; public static final int UC_ARM_REG_S17 = 96; public static final int UC_ARM_REG_S18 = 97; public static final int UC_ARM_REG_S19 = 98; public static final int UC_ARM_REG_S20 = 99; public static final int UC_ARM_REG_S21 = 100; public static final int UC_ARM_REG_S22 = 101; public static final int UC_ARM_REG_S23 = 102; public static final int UC_ARM_REG_S24 = 103; public static final int UC_ARM_REG_S25 = 104; public static final int UC_ARM_REG_S26 = 105; public static final int UC_ARM_REG_S27 = 106; public static final int UC_ARM_REG_S28 = 107; public static final int UC_ARM_REG_S29 = 108; public static final int UC_ARM_REG_S30 = 109; public static final int UC_ARM_REG_S31 = 110; public static final int UC_ARM_REG_C1_C0_2 = 111; public static final int UC_ARM_REG_C13_C0_2 = 112; public static final int UC_ARM_REG_C13_C0_3 = 113; public static final int UC_ARM_REG_IPSR = 114; public static final int UC_ARM_REG_MSP = 115; public static final int UC_ARM_REG_PSP = 116; public static final int UC_ARM_REG_CONTROL = 117; public static final int UC_ARM_REG_IAPSR = 118; public static final int UC_ARM_REG_EAPSR = 119; public static final int UC_ARM_REG_XPSR = 120; public static final int UC_ARM_REG_EPSR = 121; public static final int UC_ARM_REG_IEPSR = 122; public static final int UC_ARM_REG_PRIMASK = 123; public static final int UC_ARM_REG_BASEPRI = 124; public static final int UC_ARM_REG_BASEPRI_MAX = 125; public static final int UC_ARM_REG_FAULTMASK = 126; public static final int UC_ARM_REG_APSR_NZCVQ = 127; public static final int UC_ARM_REG_APSR_G = 128; public static final int UC_ARM_REG_APSR_NZCVQG = 129; public static final int UC_ARM_REG_IAPSR_NZCVQ = 130; public static final int UC_ARM_REG_IAPSR_G = 131; public static final int UC_ARM_REG_IAPSR_NZCVQG = 132; public static final int UC_ARM_REG_EAPSR_NZCVQ = 133; public static final int UC_ARM_REG_EAPSR_G = 134; public static final int UC_ARM_REG_EAPSR_NZCVQG = 135; public static final int UC_ARM_REG_XPSR_NZCVQ = 136; public static final int UC_ARM_REG_XPSR_G = 137; public static final int UC_ARM_REG_XPSR_NZCVQG = 138; public static final int UC_ARM_REG_CP_REG = 139; public static final int UC_ARM_REG_ENDING = 140;// alias registers public static final int UC_ARM_REG_R13 = 12; public static final int UC_ARM_REG_R14 = 10; public static final int UC_ARM_REG_R15 = 11; public static final int UC_ARM_REG_SB = 75; public static final int UC_ARM_REG_SL = 76; public static final int UC_ARM_REG_FP = 77; public static final int UC_ARM_REG_IP = 78;}
 
 
data/java/javacvefixed110.txt DELETED
@@ -1 +0,0 @@
1
- /* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2023, Arnaud Roques * * Project Info: http://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * http://plantuml.com/patreon (only 1$ per month!) * http://plantuml.com/paypal * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * * Original Author: Arnaud Roques * * */package net.sourceforge.plantuml.svek.image;import static net.sourceforge.plantuml.utils.ObjectUtils.instanceOfAny;import java.awt.geom.Point2D;import java.util.ArrayList;import java.util.List;import net.sourceforge.plantuml.awt.geom.Dimension2D;import net.sourceforge.plantuml.graphic.StringBounder;import net.sourceforge.plantuml.graphic.UDrawable;import net.sourceforge.plantuml.ugraphic.UBackground;import net.sourceforge.plantuml.ugraphic.UChange;import net.sourceforge.plantuml.ugraphic.UEmpty;import net.sourceforge.plantuml.ugraphic.UGraphic;import net.sourceforge.plantuml.ugraphic.UGraphicNo;import net.sourceforge.plantuml.ugraphic.UHorizontalLine;import net.sourceforge.plantuml.ugraphic.UImage;import net.sourceforge.plantuml.ugraphic.ULine;import net.sourceforge.plantuml.ugraphic.UPath;import net.sourceforge.plantuml.ugraphic.URectangle;import net.sourceforge.plantuml.ugraphic.UShape;import net.sourceforge.plantuml.ugraphic.UStroke;import net.sourceforge.plantuml.ugraphic.UText;import net.sourceforge.plantuml.ugraphic.UTranslate;import net.sourceforge.plantuml.ugraphic.color.ColorMapper;import net.sourceforge.plantuml.ugraphic.color.ColorMapperIdentity;import net.sourceforge.plantuml.ugraphic.color.HColor;public class Footprint { private final StringBounder stringBounder; public Footprint(StringBounder stringBounder) { this.stringBounder = stringBounder; } class MyUGraphic extends UGraphicNo { private final List<Point2D.Double> all; public MyUGraphic() { super(stringBounder, new UTranslate()); this.all = new ArrayList<>(); } private MyUGraphic(MyUGraphic other, UChange change) { // super(other, change); super(other.getStringBounder(), change instanceof UTranslate ? other.getTranslate().compose((UTranslate) change) : other.getTranslate()); if (!instanceOfAny(change, UBackground.class, HColor.class, UStroke.class, UTranslate.class)) throw new UnsupportedOperationException(change.getClass().toString()); this.all = other.all; } public UGraphic apply(UChange change) { return new MyUGraphic(this, change); } public void draw(UShape shape) { final double x = getTranslate().getDx(); final double y = getTranslate().getDy(); if (shape instanceof UText) { drawText(x, y, (UText) shape); } else if (shape instanceof UHorizontalLine) { // Definitively a Horizontal line// line.drawTitleInternalForFootprint(this, x, y); } else if (shape instanceof ULine) { // Probably a Horizontal line } else if (shape instanceof UImage) { drawImage(x, y, (UImage) shape); } else if (shape instanceof UPath) { drawPath(x, y, (UPath) shape); } else if (shape instanceof URectangle) { drawRectangle(x, y, (URectangle) shape); } else if (shape instanceof UEmpty) { drawEmpty(x, y, (UEmpty) shape); } else { throw new UnsupportedOperationException(shape.getClass().toString()); } } public ColorMapper getColorMapper() { return new ColorMapperIdentity(); } private void addPoint(double x, double y) { all.add(new Point2D.Double(x, y)); } private void drawText(double x, double y, UText text) { final Dimension2D dim = getStringBounder().calculateDimension(text.getFontConfiguration().getFont(), text.getText()); y -= dim.getHeight() - 1.5; addPoint(x, y); addPoint(x, y + dim.getHeight()); addPoint(x + dim.getWidth(), y); addPoint(x + dim.getWidth(), y + dim.getHeight()); } private void drawImage(double x, double y, UImage image) { addPoint(x, y); addPoint(x, y + image.getHeight()); addPoint(x + image.getWidth(), y); addPoint(x + image.getWidth(), y + image.getHeight()); } private void drawPath(double x, double y, UPath path) { addPoint(x + path.getMinX(), y + path.getMinY()); addPoint(x + path.getMaxX(), y + path.getMaxY()); } private void drawRectangle(double x, double y, URectangle rect) { addPoint(x, y); addPoint(x + rect.getWidth(), y + rect.getHeight()); } private void drawEmpty(double x, double y, UEmpty rect) { addPoint(x, y); addPoint(x + rect.getWidth(), y + rect.getHeight()); } } public ContainingEllipse getEllipse(UDrawable drawable, double alpha) { final MyUGraphic ug = new MyUGraphic(); drawable.drawU(ug); final List<Point2D.Double> all = ug.all; final ContainingEllipse circle = new ContainingEllipse(alpha); for (Point2D pt : all) { circle.append(pt); } return circle; } // public void drawDebug(UGraphic ug, double dx, double dy, TextBlock text) { // final MyUGraphic mug = new MyUGraphic(); // text.drawU(mug, dx, dy); // for (Point2D pt : mug.all) { // ug.draw(pt.getX(), pt.getY(), new URectangle(1, 1)); // } // // }}
 
 
data/java/javacvefixed111.txt DELETED
@@ -1 +0,0 @@
1
- /** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */package org.olat.course.archiver;import org.apache.logging.log4j.Logger;import org.olat.core.gui.UserRequest;import org.olat.core.logging.Tracing;import org.olat.core.util.StringHelper;import org.olat.core.util.prefs.Preferences;import org.olat.core.util.xml.XStreamHelper;import com.thoughtworks.xstream.XStream;import com.thoughtworks.xstream.security.ExplicitTypePermission;/** * this class reads and writes XML serialized config data to personal gui prefs and retrieves them * * Initial Date: 21.04.2017 * @author fkiefer, [email protected], www.frentix.com */public class FormatConfigHelper { private static final String QTI_EXPORT_ITEM_FORMAT_CONFIG = "QTIExportItemFormatConfig"; private static final Logger log = Tracing.createLoggerFor(FormatConfigHelper.class); private static final XStream configXstream = XStreamHelper.createXStreamInstance(); static { Class<?>[] types = new Class[] { ExportFormat.class }; // BUG: CWE-91 XML Injection (aka Blind XPath Injection) // XStream.setupDefaultSecurity(configXstream); // FIXED: configXstream.addPermission(new ExplicitTypePermission(types)); configXstream.alias(QTI_EXPORT_ITEM_FORMAT_CONFIG, ExportFormat.class); } public static ExportFormat loadExportFormat(UserRequest ureq) { ExportFormat formatConfig = null; if (ureq != null) { try { Preferences guiPrefs = ureq.getUserSession().getGuiPreferences(); String formatConfigString = (String) guiPrefs.get(ExportOptionsController.class, QTI_EXPORT_ITEM_FORMAT_CONFIG); if(StringHelper.containsNonWhitespace(formatConfigString)) { formatConfig = (ExportFormat)configXstream.fromXML(formatConfigString); } else { formatConfig = new ExportFormat(true, true, true, true, true); } } catch (Exception e) { log.error("could not establish object from xml", e); formatConfig = new ExportFormat(true, true, true, true, true); } } return formatConfig; } public static void updateExportFormat(UserRequest ureq, boolean responsecols, boolean poscol, boolean pointcol, boolean timecols, boolean commentcol) { // save new config in GUI prefs Preferences guiPrefs = ureq.getUserSession().getGuiPreferences(); if (guiPrefs != null) { ExportFormat formatConfig = new ExportFormat(responsecols, poscol, pointcol, timecols, commentcol); try { String formatConfigString = configXstream.toXML(formatConfig); guiPrefs.putAndSave(ExportOptionsController.class, QTI_EXPORT_ITEM_FORMAT_CONFIG, formatConfigString); } catch (Exception e) { log.error("",e); } } }}
 
 
data/java/javacvefixed112.txt DELETED
@@ -1 +0,0 @@
1
- /** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */package org.olat.modules.forms.model.xml;import org.olat.core.util.xml.XStreamHelper;import org.olat.modules.ceditor.model.ImageSettings;import org.olat.modules.forms.model.xml.SessionInformations.InformationType;import com.thoughtworks.xstream.XStream;import com.thoughtworks.xstream.security.ExplicitTypePermission;/** * * Initial date: 7 déc. 2016<br> * @author srosse, [email protected], http://www.frentix.com * */public class FormXStream { private static final XStream xstream = XStreamHelper.createXStreamInstance(); static { Class<?>[] types = new Class[] { Choice.class, Choices.class, Container.class, Disclaimer.class, FileStoredData.class, FileUpload.class, Form.class, HTMLParagraph.class, HTMLRaw.class, Image.class, ImageSettings.class, InformationType.class, MultipleChoice.class, Rubric.class, ScaleType.class, SessionInformations.class, SingleChoice.class, Slider.class, Spacer.class, StepLabel.class, Table.class, TextInput.class, Title.class }; xstream.addPermission(new ExplicitTypePermission(types)); xstream.alias("form", Form.class); xstream.alias("spacer", Spacer.class); xstream.alias("title", Title.class); xstream.alias("rubric", Rubric.class); xstream.alias("slider", Slider.class); xstream.alias("fileupload", FileUpload.class); xstream.alias("choice", Choice.class); xstream.alias("choices", Choices.class); xstream.alias("singlechoice", SingleChoice.class); xstream.alias("multiplechoice", MultipleChoice.class); xstream.alias("sessioninformations", SessionInformations.class); xstream.alias("informationType", InformationType.class); xstream.alias("disclaimer", Disclaimer.class); xstream.alias("table", Table.class); xstream.alias("image", Image.class); xstream.alias("imageSettgins", ImageSettings.class); xstream.alias("fileStoredData", FileStoredData.class); xstream.ignoreUnknownElements(); } public static XStream getXStream() { return xstream; }}
 
 
data/java/javacvefixed113.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2020 Ubique Innovation AG <https://www.ubique.ch> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * SPDX-License-Identifier: MPL-2.0 */package org.dpppt.backend.sdk.ws.controller;import com.fasterxml.jackson.core.JsonProcessingException;import io.jsonwebtoken.Jwts;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.Parameter;import io.swagger.v3.oas.annotations.responses.ApiResponse;import io.swagger.v3.oas.annotations.responses.ApiResponses;import io.swagger.v3.oas.annotations.tags.Tag;import org.dpppt.backend.sdk.data.gaen.FakeKeyService;import org.dpppt.backend.sdk.data.gaen.GAENDataService;import org.dpppt.backend.sdk.model.gaen.*;import org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable;import org.dpppt.backend.sdk.ws.radarcovid.annotation.ResponseRetention;import org.dpppt.backend.sdk.ws.security.ValidateRequest;import org.dpppt.backend.sdk.ws.security.ValidateRequest.InvalidDateException;import org.dpppt.backend.sdk.ws.security.signature.ProtoSignature;import org.dpppt.backend.sdk.ws.security.signature.ProtoSignature.ProtoSignatureWrapper;import org.dpppt.backend.sdk.ws.util.ValidationUtils;import org.dpppt.backend.sdk.ws.util.ValidationUtils.BadBatchReleaseTimeException;import org.joda.time.DateTime;import org.joda.time.DateTimeZone;import org.joda.time.format.DateTimeFormat;import org.joda.time.format.DateTimeFormatter;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.security.core.annotation.AuthenticationPrincipal;import org.springframework.security.oauth2.jwt.Jwt;import org.springframework.stereotype.Controller;import org.springframework.transaction.annotation.Transactional;import org.springframework.web.bind.MethodArgumentNotValidException;import org.springframework.web.bind.annotation.*;import javax.validation.Valid;import java.io.IOException;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.security.PrivateKey;import java.security.SignatureException;import java.time.Duration;import java.time.Instant;import java.time.LocalDate;import java.time.ZoneOffset;import java.time.format.DateTimeParseException;import java.util.*;import java.util.concurrent.Callable;@Controller@RequestMapping("/v1/gaen")@Tag(name = "GAEN", description = "The GAEN endpoint for the mobile clients")/** * The GaenController defines the API endpoints for the mobile clients to access the GAEN functionality of the * red backend. * Clients can send new Exposed Keys, or request the existing Exposed Keys. */public class GaenController { private static final Logger logger = LoggerFactory.getLogger(GaenController.class); private static final String FAKE_CODE = "112358132134"; private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'") .withZoneUTC().withLocale(Locale.ENGLISH); // releaseBucketDuration is used to delay the publishing of Exposed Keys by splitting the database up into batches of keys // in releaseBucketDuration duration. The current batch is never published, only previous batches are published. private final Duration releaseBucketDuration; private final Duration requestTime; private final ValidateRequest validateRequest; private final ValidationUtils validationUtils; private final GAENDataService dataService; private final FakeKeyService fakeKeyService; private final Duration exposedListCacheControl; private final PrivateKey secondDayKey; private final ProtoSignature gaenSigner; public GaenController(GAENDataService dataService, FakeKeyService fakeKeyService, ValidateRequest validateRequest, ProtoSignature gaenSigner, ValidationUtils validationUtils, Duration releaseBucketDuration, Duration requestTime, Duration exposedListCacheControl, PrivateKey secondDayKey) { this.dataService = dataService; this.fakeKeyService = fakeKeyService; this.releaseBucketDuration = releaseBucketDuration; this.validateRequest = validateRequest; this.requestTime = requestTime; this.validationUtils = validationUtils; this.exposedListCacheControl = exposedListCacheControl; this.secondDayKey = secondDayKey; this.gaenSigner = gaenSigner; } @PostMapping(value = "/exposed") @Loggable @ResponseRetention(time = "application.response.retention.time.exposed") @Transactional @Operation(description = "Send exposed keys to server - includes a fix for the fact that GAEN doesn't give access to the current day's exposed key") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "The exposed keys have been stored in the database"), @ApiResponse(responseCode = "400", description = "- Invalid base64 encoding in GaenRequest" + "- negative rolling period" + "- fake claim with non-fake keys"), @ApiResponse(responseCode = "403", description = "Authentication failed") }) public @ResponseBody Callable<ResponseEntity<String>> addExposed( @Valid @RequestBody @Parameter(description = "The GaenRequest contains the SecretKey from the guessed infection date, the infection date itself, and some authentication data to verify the test result") GaenRequest gaenRequest, @RequestHeader(value = "User-Agent") @Parameter(description = "App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version", example = "ch.ubique.android.starsdk;1.0;iOS;13.3") String userAgent, @AuthenticationPrincipal @Parameter(description = "JWT token that can be verified by the backend server") Object principal) { var now = Instant.now().toEpochMilli(); if (!this.validateRequest.isValid(principal)) { return () -> ResponseEntity.status(HttpStatus.FORBIDDEN).build(); } List<GaenKey> nonFakeKeys = new ArrayList<>(); for (var key : gaenRequest.getGaenKeys()) { if (!validationUtils.isValidBase64Key(key.getKeyData())) { return () -> new ResponseEntity<>("No valid base64 key", HttpStatus.BAD_REQUEST); } if (this.validateRequest.isFakeRequest(principal, key) || hasNegativeRollingPeriod(key) || hasInvalidKeyDate(principal, key)) { continue; } if (key.getRollingPeriod().equals(0)) { //currently only android seems to send 0 which can never be valid, since a non used key should not be submitted //default value according to EN is 144, so just set it to that. If we ever get 0 from iOS we should log it, since //this should not happen key.setRollingPeriod(GaenKey.GaenKeyDefaultRollingPeriod); if (userAgent.toLowerCase().contains("ios")) { logger.error("Received a rolling period of 0 for an iOS User-Agent"); } } nonFakeKeys.add(key); } if (principal instanceof Jwt && ((Jwt) principal).containsClaim("fake") && ((Jwt) principal).getClaimAsString("fake").equals("1")) { Jwt token = (Jwt) principal; if (FAKE_CODE.equals(token.getSubject())) { logger.info("Claim is fake - subject: {}", token.getSubject()); } else if (!nonFakeKeys.isEmpty()) { return () -> ResponseEntity.badRequest().body("Claim is fake but list contains non fake keys"); } } if (!nonFakeKeys.isEmpty()) { dataService.upsertExposees(nonFakeKeys); } var delayedKeyDateDuration = Duration.of(gaenRequest.getDelayedKeyDate(), GaenUnit.TenMinutes); var delayedKeyDate = LocalDate.ofInstant(Instant.ofEpochMilli(delayedKeyDateDuration.toMillis()), ZoneOffset.UTC); var nowDay = LocalDate.now(ZoneOffset.UTC); if (delayedKeyDate.isBefore(nowDay.minusDays(1)) || delayedKeyDate.isAfter(nowDay.plusDays(1))) { return () -> ResponseEntity.badRequest().body("delayedKeyDate date must be between yesterday and tomorrow"); } var responseBuilder = ResponseEntity.ok(); if (principal instanceof Jwt) { var originalJWT = (Jwt) principal; var jwtBuilder = Jwts.builder().setId(UUID.randomUUID().toString()).setIssuedAt(Date.from(Instant.now())) .setIssuer("dpppt-sdk-backend").setSubject(originalJWT.getSubject()) .setExpiration(Date .from(delayedKeyDate.atStartOfDay().toInstant(ZoneOffset.UTC).plus(Duration.ofHours(48)))) .claim("scope", "currentDayExposed").claim("delayedKeyDate", gaenRequest.getDelayedKeyDate()); if (originalJWT.containsClaim("fake")) { jwtBuilder.claim("fake", originalJWT.getClaim("fake")); } String jwt = jwtBuilder.signWith(secondDayKey).compact(); responseBuilder.header("Authorization", "Bearer " + jwt); responseBuilder.header("X-Exposed-Token", "Bearer " + jwt); } Callable<ResponseEntity<String>> cb = () -> { normalizeRequestTime(now); return responseBuilder.body("OK"); }; return cb; } @PostMapping(value = "/exposednextday") @Loggable // BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor // // FIXED: @ResponseRetention(time = "application.response.retention.time.exposednextday") @Transactional @Operation(description = "Allows the client to send the last exposed key of the infection to the backend server. The JWT must come from a previous call to /exposed") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "The exposed key has been stored in the backend"), @ApiResponse(responseCode = "400", description = "- Ivnalid base64 encoded Temporary Exposure Key" + "- TEK-date does not match delayedKeyDAte claim in Jwt" + "- TEK has negative rolling period"), @ApiResponse(responseCode = "403", description = "No delayedKeyDate claim in authentication") }) public @ResponseBody Callable<ResponseEntity<String>> addExposedSecond( @Valid @RequestBody @Parameter(description = "The last exposed key of the user") GaenSecondDay gaenSecondDay, @RequestHeader(value = "User-Agent") @Parameter(description = "App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version", example = "ch.ubique.android.starsdk;1.0;iOS;13.3") String userAgent, @AuthenticationPrincipal @Parameter(description = "JWT token that can be verified by the backend server, must have been created by /v1/gaen/exposed and contain the delayedKeyDate") Object principal) { var now = Instant.now().toEpochMilli(); if (!validationUtils.isValidBase64Key(gaenSecondDay.getDelayedKey().getKeyData())) { return () -> new ResponseEntity<>("No valid base64 key", HttpStatus.BAD_REQUEST); } if (principal instanceof Jwt && !((Jwt) principal).containsClaim("delayedKeyDate")) { return () -> ResponseEntity.status(HttpStatus.FORBIDDEN).body("claim does not contain delayedKeyDate"); } if (principal instanceof Jwt) { var jwt = (Jwt) principal; var claimKeyDate = Integer.parseInt(jwt.getClaimAsString("delayedKeyDate")); if (!gaenSecondDay.getDelayedKey().getRollingStartNumber().equals(claimKeyDate)) { return () -> ResponseEntity.badRequest().body("keyDate does not match claim keyDate"); } } if (!this.validateRequest.isFakeRequest(principal, gaenSecondDay.getDelayedKey())) { if (gaenSecondDay.getDelayedKey().getRollingPeriod().equals(0)) { // currently only android seems to send 0 which can never be valid, since a non used key should not be submitted // default value according to EN is 144, so just set it to that. If we ever get 0 from iOS we should log it, since // this should not happen gaenSecondDay.getDelayedKey().setRollingPeriod(GaenKey.GaenKeyDefaultRollingPeriod); if(userAgent.toLowerCase().contains("ios")) { logger.error("Received a rolling period of 0 for an iOS User-Agent"); } } else if(gaenSecondDay.getDelayedKey().getRollingPeriod() < 0) { return () -> ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Rolling Period MUST NOT be negative."); } List<GaenKey> keys = new ArrayList<>(); keys.add(gaenSecondDay.getDelayedKey()); dataService.upsertExposees(keys); } return () -> { normalizeRequestTime(now); return ResponseEntity.ok().body("OK"); }; } @GetMapping(value = "/exposed/{keyDate}", produces = "application/zip") @Loggable @Operation(description = "Request the exposed key from a given date") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "zipped export.bin and export.sig of all keys in that interval"), @ApiResponse(responseCode = "400", description = "- invalid starting key date, doesn't point to midnight UTC" + "- _publishedAfter_ is not at the beginning of a batch release time, currently 2h")}) public @ResponseBody ResponseEntity<byte[]> getExposedKeys( @PathVariable @Parameter(description = "Requested date for Exposed Keys retrieval, in milliseconds since Unix epoch (1970-01-01). It must indicate the beginning of a TEKRollingPeriod, currently midnight UTC.", example = "1593043200000") long keyDate, @RequestParam(required = false) @Parameter(description = "Restrict returned Exposed Keys to dates after this parameter. Given in milliseconds since Unix epoch (1970-01-01).", example = "1593043200000") Long publishedafter) throws BadBatchReleaseTimeException, IOException, InvalidKeyException, SignatureException, NoSuchAlgorithmException { if (!validationUtils.isValidKeyDate(keyDate)) { return ResponseEntity.notFound().build(); } if (publishedafter != null && !validationUtils.isValidBatchReleaseTime(publishedafter)) { return ResponseEntity.notFound().build(); } long now = System.currentTimeMillis(); // calculate exposed until bucket long publishedUntil = now - (now % releaseBucketDuration.toMillis()); DateTime dateTime = new DateTime(publishedUntil + releaseBucketDuration.toMillis() - 1, DateTimeZone.UTC); var exposedKeys = dataService.getSortedExposedForKeyDate(keyDate, publishedafter, publishedUntil); exposedKeys = fakeKeyService.fillUpKeys(exposedKeys, publishedafter, keyDate); if (exposedKeys.isEmpty()) { return ResponseEntity.noContent()//.cacheControl(CacheControl.maxAge(exposedListCacheControl)) .header("X-PUBLISHED-UNTIL", Long.toString(publishedUntil)) .header("Expires", RFC1123_DATE_TIME_FORMATTER.print(dateTime)) .build(); } ProtoSignatureWrapper payload = gaenSigner.getPayload(exposedKeys); return ResponseEntity.ok()//.cacheControl(CacheControl.maxAge(exposedListCacheControl)) .header("X-PUBLISHED-UNTIL", Long.toString(publishedUntil)) .header("Expires", RFC1123_DATE_TIME_FORMATTER.print(dateTime)) .body(payload.getZip()); } @GetMapping(value = "/buckets/{dayDateStr}") @Loggable @Operation(description = "Request the available release batch times for a given day") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "zipped export.bin and export.sig of all keys in that interval"), @ApiResponse(responseCode = "400", description = "invalid starting key date, points outside of the retention range")}) public @ResponseBody ResponseEntity<DayBuckets> getBuckets( @PathVariable @Parameter(description = "Starting date for exposed key retrieval, as ISO-8601 format", example = "2020-06-27") String dayDateStr) { var atStartOfDay = LocalDate.parse(dayDateStr).atStartOfDay().toInstant(ZoneOffset.UTC) .atOffset(ZoneOffset.UTC); var end = atStartOfDay.plusDays(1); var now = Instant.now().atOffset(ZoneOffset.UTC); if (!validationUtils.isDateInRange(atStartOfDay)) { return ResponseEntity.notFound().build(); } var relativeUrls = new ArrayList<String>(); var dayBuckets = new DayBuckets(); String controllerMapping = this.getClass().getAnnotation(RequestMapping.class).value()[0]; dayBuckets.setDay(dayDateStr).setRelativeUrls(relativeUrls).setDayTimestamp(atStartOfDay.toInstant().toEpochMilli()); while (atStartOfDay.toInstant().toEpochMilli() < Math.min(now.toInstant().toEpochMilli(), end.toInstant().toEpochMilli())) { relativeUrls.add(controllerMapping + "/exposed" + "/" + atStartOfDay.toInstant().toEpochMilli()); atStartOfDay = atStartOfDay.plus(this.releaseBucketDuration); } return ResponseEntity.ok(dayBuckets); } private void normalizeRequestTime(long now) { long after = Instant.now().toEpochMilli(); long duration = after - now; try { Thread.sleep(Math.max(requestTime.minusMillis(duration).toMillis(), 0)); } catch (Exception ex) { logger.error("Couldn't equalize request time: {}", ex.toString()); } } private boolean hasNegativeRollingPeriod(GaenKey key) { Integer rollingPeriod = key.getRollingPeriod(); if (key.getRollingPeriod() < 0) { logger.error("Detected key with negative rolling period {}", rollingPeriod); return true; } else { return false; } } private boolean hasInvalidKeyDate(Object principal, GaenKey key) { try { this.validateRequest.getKeyDate(principal, key); } catch (InvalidDateException invalidDate) { logger.error(invalidDate.getLocalizedMessage()); return true; } return false; } @ExceptionHandler({IllegalArgumentException.class, InvalidDateException.class, JsonProcessingException.class, MethodArgumentNotValidException.class, BadBatchReleaseTimeException.class, DateTimeParseException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseEntity<Object> invalidArguments(Exception ex) { logger.error("Exception ({}): {}", ex.getClass().getSimpleName(), ex.getMessage(), ex); return ResponseEntity.badRequest().build(); }}
 
 
data/java/javacvefixed114.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.thoughtworks.go.config.materials.git;import com.thoughtworks.go.config.*;import com.thoughtworks.go.config.materials.*;import com.thoughtworks.go.domain.materials.MaterialConfig;import com.thoughtworks.go.security.GoCipher;import com.thoughtworks.go.util.ReflectionUtil;import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;import java.util.Collections;import java.util.HashMap;import java.util.Map;import static com.thoughtworks.go.helper.MaterialConfigsMother.git;import static org.junit.jupiter.api.Assertions.*;import static org.mockito.Mockito.*;class GitMaterialConfigTest { @Test void shouldBePasswordAwareMaterial() { assertTrue(PasswordAwareMaterial.class.isAssignableFrom(GitMaterialConfig.class)); } @Test void shouldSetConfigAttributes() { GitMaterialConfig gitMaterialConfig = git(""); Map<String, String> map = new HashMap<>(); map.put(GitMaterialConfig.URL, "url"); map.put(GitMaterialConfig.BRANCH, "some-branch"); map.put(GitMaterialConfig.SHALLOW_CLONE, "true"); map.put(ScmMaterialConfig.FOLDER, "folder"); map.put(ScmMaterialConfig.AUTO_UPDATE, null); map.put(ScmMaterialConfig.FILTER, "/root,/**/*.help"); map.put(AbstractMaterialConfig.MATERIAL_NAME, "material-name"); gitMaterialConfig.setConfigAttributes(map); assertEquals("url", gitMaterialConfig.getUrl()); assertEquals("folder", gitMaterialConfig.getFolder()); assertEquals("some-branch", gitMaterialConfig.getBranch()); assertEquals(new CaseInsensitiveString("material-name"), gitMaterialConfig.getName()); assertFalse(gitMaterialConfig.isAutoUpdate()); assertTrue(gitMaterialConfig.isShallowClone()); assertEquals(new Filter(new IgnoredFiles("/root"), new IgnoredFiles("/**/*.help")), gitMaterialConfig.filter()); } @Test void setConfigAttributes_shouldUpdatePasswordWhenPasswordChangedBooleanChanged() throws Exception { GitMaterialConfig gitMaterialConfig = git(""); Map<String, String> map = new HashMap<>(); map.put(GitMaterialConfig.PASSWORD, "secret"); map.put(GitMaterialConfig.PASSWORD_CHANGED, "1"); gitMaterialConfig.setConfigAttributes(map); assertNull(ReflectionUtil.getField(gitMaterialConfig, "password")); assertEquals("secret", gitMaterialConfig.getPassword()); assertEquals(new GoCipher().encrypt("secret"), gitMaterialConfig.getEncryptedPassword()); //Dont change map.put(GitMaterialConfig.PASSWORD, "Hehehe"); map.put(GitMaterialConfig.PASSWORD_CHANGED, "0"); gitMaterialConfig.setConfigAttributes(map); assertNull(ReflectionUtil.getField(gitMaterialConfig, "password")); assertEquals("secret", gitMaterialConfig.getPassword()); assertEquals(new GoCipher().encrypt("secret"), gitMaterialConfig.getEncryptedPassword()); map.put(GitMaterialConfig.PASSWORD, ""); map.put(GitMaterialConfig.PASSWORD_CHANGED, "1"); gitMaterialConfig.setConfigAttributes(map); assertNull(gitMaterialConfig.getPassword()); assertNull(gitMaterialConfig.getEncryptedPassword()); } @Test void byDefaultShallowCloneShouldBeOff() { assertFalse(git("http://url", "foo").isShallowClone()); assertFalse(git("http://url", "foo", false).isShallowClone()); assertFalse(git("http://url", "foo", null).isShallowClone()); assertTrue(git("http://url", "foo", true).isShallowClone()); } @Test void shouldReturnIfAttributeMapIsNull() { GitMaterialConfig gitMaterialConfig = git(""); gitMaterialConfig.setConfigAttributes(null); assertEquals(git(""), gitMaterialConfig); } @Test void shouldReturnTheUrl() { String url = "[email protected]/my/repo"; GitMaterialConfig config = git(url); assertEquals(url, config.getUrl()); } @Test void shouldReturnNullIfUrlForMaterialNotSpecified() { GitMaterialConfig config = git(); assertNull(config.getUrl()); } @Test void shouldSetUrlForAMaterial() { String url = "[email protected]/my/repo"; GitMaterialConfig config = git(); config.setUrl(url); assertEquals(url, config.getUrl()); } @Test void shouldHandleNullWhenSettingUrlForAMaterial() { GitMaterialConfig config = git(); config.setUrl(null); assertNull(config.getUrl()); } @Test void shouldHandleNullUrlAtTheTimeOfGitMaterialConfigCreation() { GitMaterialConfig config = git(null); assertNull(config.getUrl()); } @Test void shouldHandleNullBranchWhileSettingConfigAttributes() { GitMaterialConfig gitMaterialConfig = git("http://url", "foo"); gitMaterialConfig.setConfigAttributes(Collections.singletonMap(GitMaterialConfig.BRANCH, null)); assertEquals("master", gitMaterialConfig.getBranch()); } @Test void shouldHandleEmptyBranchWhileSettingConfigAttributes() { GitMaterialConfig gitMaterialConfig = git("http://url", "foo"); gitMaterialConfig.setConfigAttributes(Collections.singletonMap(GitMaterialConfig.BRANCH, " ")); assertEquals("master", gitMaterialConfig.getBranch()); } @Nested class Validate { @Test void allowsBlankBranch() { assertFalse(validating(git("/my/repo", null)).errors().present()); assertFalse(validating(git("/my/repo", "")).errors().present()); assertFalse(validating(git("/my/repo", " ")).errors().present()); } @Test void rejectsBranchWithWildcard() { assertEquals("Branch names may not contain '*'", validating(git("/foo", "branch-*")). errors().on(GitMaterialConfig.BRANCH)); } @Test void rejectsMalformedRefSpec() { assertEquals("Refspec is missing a source ref", String.join(";", validating(git("/foo", ":a")).errors(). getAllOn(GitMaterialConfig.BRANCH))); assertEquals("Refspec is missing a source ref", String.join(";", validating(git("/foo", " :b")).errors(). getAllOn(GitMaterialConfig.BRANCH))); assertEquals("Refspec is missing a destination ref", String.join(";", validating(git("/foo", "refs/foo: ")).errors(). getAllOn(GitMaterialConfig.BRANCH))); assertEquals("Refspec is missing a destination ref", String.join(";", validating(git("/foo", "refs/bar:")).errors(). getAllOn(GitMaterialConfig.BRANCH))); assertEquals("Refspec is missing a source ref;Refspec is missing a destination ref", String.join(";", validating(git("/foo", ":")).errors(). getAllOn(GitMaterialConfig.BRANCH))); assertEquals("Refspec is missing a source ref;Refspec is missing a destination ref", String.join(";", validating(git("/foo", " : ")).errors(). getAllOn(GitMaterialConfig.BRANCH))); assertEquals("Refspec source must be an absolute ref (must start with `refs/`)", String.join(";", validating(git("/foo", "a:b")).errors(). getAllOn(GitMaterialConfig.BRANCH))); assertEquals("Refspecs may not contain wildcards; source and destination refs must be exact", String.join(";", validating(git("/foo", "refs/heads/*:my-branch")).errors(). getAllOn(GitMaterialConfig.BRANCH))); assertEquals("Refspecs may not contain wildcards; source and destination refs must be exact", String.join(";", validating(git("/foo", "refs/heads/foo:branches/*")).errors(). getAllOn(GitMaterialConfig.BRANCH))); assertEquals("Refspecs may not contain wildcards; source and destination refs must be exact", String.join(";", validating(git("/foo", "refs/heads/*:branches/*")).errors(). getAllOn(GitMaterialConfig.BRANCH))); } @Test void acceptsValidRefSpecs() { assertTrue(validating(git("/foo", "refs/pull/123/head:pr-123")).errors().isEmpty()); assertTrue(validating(git("/foo", "refs/pull/123/head:refs/my-prs/123")).errors().isEmpty()); } @Test void shouldEnsureUrlIsNotBlank() { assertEquals("URL cannot be blank", validating(git("")).errors().on(GitMaterialConfig.URL)); } @Test void shouldEnsureUserNameIsNotProvidedInBothUrlAsWellAsAttributes() { GitMaterialConfig gitMaterialConfig = git("http://bob:[email protected]"); gitMaterialConfig.setUserName("user"); assertEquals("Ambiguous credentials, must be provided either in URL or as attributes.", validating(gitMaterialConfig).errors().on(GitMaterialConfig.URL)); } @Test void shouldEnsurePasswordIsNotProvidedInBothUrlAsWellAsAttributes() { GitMaterialConfig gitMaterialConfig = git("http://bob:[email protected]"); gitMaterialConfig.setPassword("pass"); assertEquals("Ambiguous credentials, must be provided either in URL or as attributes.", validating(gitMaterialConfig).errors().on(GitMaterialConfig.URL)); } @Test void shouldIgnoreInvalidUrlForCredentialValidation() { GitMaterialConfig gitMaterialConfig = git("http://bob:[email protected]##dobule-hash-is-invalid-in-url"); gitMaterialConfig.setUserName("user"); gitMaterialConfig.setPassword("password"); assertFalse(validating(gitMaterialConfig).errors().containsKey(GitMaterialConfig.URL)); } @Test void shouldBeValidWhenCredentialsAreProvidedOnlyInUrl() { assertFalse(validating(git("http://bob:[email protected]")).errors().containsKey(GitMaterialConfig.URL)); } @Test void shouldBeValidWhenCredentialsAreProvidedOnlyAsAttributes() { GitMaterialConfig gitMaterialConfig = git("http://example.com"); gitMaterialConfig.setUserName("bob"); gitMaterialConfig.setPassword("badger"); assertFalse(validating(gitMaterialConfig).errors().containsKey(GitMaterialConfig.URL)); } @Test void rejectsObviouslyWrongURL() { assertTrue(validating(git("-url-not-starting-with-an-alphanumeric-character")).errors().containsKey(GitMaterialConfig.URL)); assertTrue(validating(git("_url-not-starting-with-an-alphanumeric-character")).errors().containsKey(GitMaterialConfig.URL)); assertTrue(validating(git("@url-not-starting-with-an-alphanumeric-character")).errors().containsKey(GitMaterialConfig.URL)); assertFalse(validating(git("url-starting-with-an-alphanumeric-character")).errors().containsKey(GitMaterialConfig.URL)); // BUG: CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection') // // FIXED: assertFalse(validating(git("#{url}")).errors().containsKey(GitMaterialConfig.URL)); } private GitMaterialConfig validating(GitMaterialConfig git) { git.validate(new ConfigSaveValidationContext(null)); return git; } } @Nested class ValidateTree { @Test void shouldCallValidate() { final MaterialConfig materialConfig = spy(git("https://example.repo")); final ValidationContext validationContext = mockValidationContextForSecretParams(); materialConfig.validateTree(validationContext); verify(materialConfig).validate(validationContext); } @Test void shouldFailIfEncryptedPasswordIsIncorrect() { GitMaterialConfig gitMaterialConfig = git("http://example.com"); gitMaterialConfig.setEncryptedPassword("encryptedPassword"); final boolean validationResult = gitMaterialConfig.validateTree(new ConfigSaveValidationContext(null)); assertFalse(validationResult); assertEquals("Encrypted password value for GitMaterial with url 'http://example.com' is " + "invalid. This usually happens when the cipher text is modified to have an invalid value.", gitMaterialConfig.errors().on("encryptedPassword")); } } @Nested class Equals { @Test void shouldBeEqualIfObjectsHaveSameUrlBranchAndSubModuleFolder() { final GitMaterialConfig material_1 = git("http://example.com", "master"); material_1.setUserName("bob"); material_1.setSubmoduleFolder("/var/lib/git"); final GitMaterialConfig material_2 = git("http://example.com", "master"); material_2.setUserName("alice"); material_2.setSubmoduleFolder("/var/lib/git"); assertTrue(material_1.equals(material_2)); } } @Nested class Fingerprint { @Test void shouldGenerateFingerprintForGivenMaterialUrlAndBranch() { GitMaterialConfig gitMaterialConfig = git("https://bob:[email protected]/gocd", "feature"); assertEquals("755da7fb7415c8674bdf5f8a4ba48fc3e071e5de429b1308ccf8949d215bdb08", gitMaterialConfig.getFingerprint()); } } private ValidationContext mockValidationContextForSecretParams(SecretConfig... secretConfigs) { final ValidationContext validationContext = mock(ValidationContext.class); final CruiseConfig cruiseConfig = mock(CruiseConfig.class); when(validationContext.getCruiseConfig()).thenReturn(cruiseConfig); when(cruiseConfig.getSecretConfigs()).thenReturn(new SecretConfigs(secretConfigs)); return validationContext; }}
 
 
data/java/javacvefixed115.txt DELETED
@@ -1 +0,0 @@
1
- /* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2023, Arnaud Roques * * Project Info: http://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * http://plantuml.com/patreon (only 1$ per month!) * http://plantuml.com/paypal * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * * Original Author: Arnaud Roques * * */package net.sourceforge.plantuml.svek;import java.awt.Color;import java.awt.image.BufferedImage;import java.util.ArrayList;import java.util.List;import net.sourceforge.plantuml.BackSlash;import net.sourceforge.plantuml.OptionPrint;import net.sourceforge.plantuml.StringUtils;import net.sourceforge.plantuml.awt.geom.Dimension2D;import net.sourceforge.plantuml.command.CommandExecutionResult;import net.sourceforge.plantuml.cucadiagram.dot.GraphvizUtils;import net.sourceforge.plantuml.flashcode.FlashCodeFactory;import net.sourceforge.plantuml.flashcode.FlashCodeUtils;import net.sourceforge.plantuml.fun.IconLoader;import net.sourceforge.plantuml.graphic.AbstractTextBlock;import net.sourceforge.plantuml.graphic.GraphicPosition;import net.sourceforge.plantuml.graphic.GraphicStrings;import net.sourceforge.plantuml.graphic.HorizontalAlignment;import net.sourceforge.plantuml.graphic.QuoteUtils;import net.sourceforge.plantuml.graphic.StringBounder;import net.sourceforge.plantuml.graphic.TextBlock;import net.sourceforge.plantuml.graphic.TextBlockUtils;import net.sourceforge.plantuml.ugraphic.AffineTransformType;import net.sourceforge.plantuml.ugraphic.PixelImage;import net.sourceforge.plantuml.ugraphic.UGraphic;import net.sourceforge.plantuml.ugraphic.UImage;import net.sourceforge.plantuml.ugraphic.color.HColor;import net.sourceforge.plantuml.ugraphic.color.HColorUtils;import net.sourceforge.plantuml.version.PSystemVersion;import net.sourceforge.plantuml.version.Version;public class GraphvizCrash extends AbstractTextBlock implements IEntityImage { private final TextBlock text1; private final BufferedImage flashCode; private final String text; private final boolean graphviz244onWindows; public GraphvizCrash(String text, boolean graphviz244onWindows, Throwable rootCause) { this.text = text; this.graphviz244onWindows = graphviz244onWindows; final FlashCodeUtils utils = FlashCodeFactory.getFlashCodeUtils(); this.flashCode = utils.exportFlashcode(text, Color.BLACK, Color.WHITE); this.text1 = GraphicStrings.createBlackOnWhite(init(rootCause), IconLoader.getRandom(), GraphicPosition.BACKGROUND_CORNER_TOP_RIGHT); } public static List<String> anErrorHasOccured(Throwable exception, String text) { final List<String> strings = new ArrayList<>(); if (exception == null) { strings.add("An error has occured!"); } else { strings.add("An error has occured : " + exception); } final String quote = StringUtils.rot(QuoteUtils.getSomeQuote()); strings.add("<i>" + quote); strings.add(" "); strings.add("Diagram size: " + lines(text) + " lines / " + text.length() + " characters."); strings.add(" "); return strings; } private static int lines(String text) { int result = 0; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == BackSlash.CHAR_NEWLINE) { result++; } } return result; } public static void checkOldVersionWarning(List<String> strings) { final long days = (System.currentTimeMillis() - Version.compileTime()) / 1000L / 3600 / 24; if (days >= 90) { strings.add(" "); strings.add("<b>This version of PlantUML is " + days + " days old, so you should"); strings.add("<b>consider upgrading from https://plantuml.com/download"); } } public static void pleaseGoTo(List<String> strings) { strings.add(" "); strings.add("Please go to https://plantuml.com/graphviz-dot to check your GraphViz version."); strings.add(" "); } public static void youShouldSendThisDiagram(List<String> strings) { strings.add("You should send this diagram and this image to <b>[email protected]</b> or"); strings.add("post to <b>https://plantuml.com/qa</b> to solve this issue."); strings.add("You can try to turn arround this issue by simplifing your diagram."); } public static void thisMayBeCaused(final List<String> strings) { strings.add("This may be caused by :"); strings.add(" - a bug in PlantUML"); strings.add(" - a problem in GraphViz"); } private List<String> init(Throwable rootCause) { final List<String> strings = anErrorHasOccured(null, text); strings.add("For some reason, dot/GraphViz has crashed."); strings.add(""); strings.add("RootCause " + rootCause); if (rootCause != null) { strings.addAll(CommandExecutionResult.getStackTrace(rootCause)); } strings.add(""); strings.add("This has been generated with PlantUML (" + Version.versionString() + ")."); checkOldVersionWarning(strings); strings.add(" "); addProperties(strings); strings.add(" "); try { final String dotVersion = GraphvizUtils.dotVersion(); strings.add("Default dot version: " + dotVersion); } catch (Throwable e) { strings.add("Cannot determine dot version: " + e.toString()); } pleaseGoTo(strings); youShouldSendThisDiagram(strings); if (flashCode != null) { addDecodeHint(strings); } return strings; } private List<String> getText2() { final List<String> strings = new ArrayList<>(); strings.add(" "); strings.add("<b>It looks like you are running GraphViz 2.44 under Windows."); strings.add("If you have just installed GraphViz, you <i>may</i> have to execute"); strings.add("the post-install command <b>dot -c</b> like in the following example:"); return strings; } private List<String> getText3() { final List<String> strings = new ArrayList<>(); strings.add(" "); strings.add("You may have to have <i>Administrator rights</i> to avoid the following error message:"); return strings; } public static void addDecodeHint(final List<String> strings) { strings.add(" "); strings.add(" Diagram source: (Use http://zxing.org/w/decode.jspx to decode the qrcode)"); } public static void addProperties(final List<String> strings) { strings.addAll(OptionPrint.interestingProperties()); strings.addAll(OptionPrint.interestingValues()); } public boolean isHidden() { return false; } public HColor getBackcolor() { return HColorUtils.WHITE; } public Dimension2D calculateDimension(StringBounder stringBounder) { return getMain().calculateDimension(stringBounder); } public void drawU(UGraphic ug) { getMain().drawU(ug); } private TextBlock getMain() { TextBlock result = text1; if (flashCode != null) { final UImage flash = new UImage(new PixelImage(flashCode, AffineTransformType.TYPE_NEAREST_NEIGHBOR)) .scale(3); result = TextBlockUtils.mergeTB(result, flash, HorizontalAlignment.LEFT); } if (graphviz244onWindows) { final TextBlock text2 = GraphicStrings.createBlackOnWhite(getText2()); result = TextBlockUtils.mergeTB(result, text2, HorizontalAlignment.LEFT); final UImage dotc = new UImage(new PixelImage(PSystemVersion.getDotc(), AffineTransformType.TYPE_BILINEAR)); result = TextBlockUtils.mergeTB(result, dotc, HorizontalAlignment.LEFT); final TextBlock text3 = GraphicStrings.createBlackOnWhite(getText3()); result = TextBlockUtils.mergeTB(result, text3, HorizontalAlignment.LEFT); final UImage dotd = new UImage(new PixelImage(PSystemVersion.getDotd(), AffineTransformType.TYPE_BILINEAR)); result = TextBlockUtils.mergeTB(result, dotd, HorizontalAlignment.LEFT); } return result; } public ShapeType getShapeType() { return ShapeType.RECTANGLE; } public Margins getShield(StringBounder stringBounder) { return Margins.NONE; } public double getOverscanX(StringBounder stringBounder) { return 0; }}
 
 
data/java/javacvefixed116.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.thoughtworks.go.config.materials.mercurial;import com.thoughtworks.go.config.*;import com.thoughtworks.go.config.materials.*;import com.thoughtworks.go.domain.materials.MaterialConfig;import com.thoughtworks.go.security.GoCipher;import com.thoughtworks.go.util.ReflectionUtil;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;import java.util.Collections;import java.util.HashMap;import java.util.Map;import static com.thoughtworks.go.config.materials.AbstractMaterialConfig.MATERIAL_NAME;import static com.thoughtworks.go.config.materials.ScmMaterialConfig.FOLDER;import static com.thoughtworks.go.config.materials.ScmMaterialConfig.URL;import static com.thoughtworks.go.helper.MaterialConfigsMother.git;import static com.thoughtworks.go.helper.MaterialConfigsMother.hg;import static org.assertj.core.api.Assertions.assertThat;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.Mockito.*;class HgMaterialConfigTest { private HgMaterialConfig hgMaterialConfig; @BeforeEach void setUp() { hgMaterialConfig = hg("", null); } @Test void shouldBePasswordAwareMaterial() { assertThat(hgMaterialConfig).isInstanceOf(PasswordAwareMaterial.class); } @Test void shouldSetConfigAttributes() { HgMaterialConfig hgMaterialConfig = hg("", null); Map<String, String> map = new HashMap<>(); map.put(HgMaterialConfig.URL, "url"); map.put(ScmMaterialConfig.FOLDER, "folder"); map.put(ScmMaterialConfig.AUTO_UPDATE, "0"); map.put(ScmMaterialConfig.FILTER, "/root,/**/*.help"); map.put(AbstractMaterialConfig.MATERIAL_NAME, "material-name"); hgMaterialConfig.setConfigAttributes(map); assertThat(hgMaterialConfig.getUrl()).isEqualTo("url"); assertThat(hgMaterialConfig.getFolder()).isEqualTo("folder"); assertThat(hgMaterialConfig.getName()).isEqualTo(new CaseInsensitiveString("material-name")); assertThat(hgMaterialConfig.isAutoUpdate()).isFalse(); assertThat(hgMaterialConfig.filter()).isEqualTo(new Filter(new IgnoredFiles("/root"), new IgnoredFiles("/**/*.help"))); } @Test void setConfigAttributes_shouldUpdatePasswordWhenPasswordChangedBooleanChanged() throws Exception { HgMaterialConfig hgMaterialConfig = hg(); Map<String, String> map = new HashMap<>(); map.put(HgMaterialConfig.PASSWORD, "secret"); map.put(HgMaterialConfig.PASSWORD_CHANGED, "1"); hgMaterialConfig.setConfigAttributes(map); assertThat(ReflectionUtil.getField(hgMaterialConfig, "password")).isNull(); assertThat(hgMaterialConfig.getPassword()).isEqualTo("secret"); assertThat(hgMaterialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt("secret")); //Dont change map.put(HgMaterialConfig.PASSWORD, "Hehehe"); map.put(HgMaterialConfig.PASSWORD_CHANGED, "0"); hgMaterialConfig.setConfigAttributes(map); assertThat(ReflectionUtil.getField(hgMaterialConfig, "password")).isNull(); assertThat(hgMaterialConfig.getPassword()).isEqualTo("secret"); assertThat(hgMaterialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt("secret")); map.put(HgMaterialConfig.PASSWORD, ""); map.put(HgMaterialConfig.PASSWORD_CHANGED, "1"); hgMaterialConfig.setConfigAttributes(map); assertThat(hgMaterialConfig.getPassword()).isNull(); assertThat(hgMaterialConfig.getEncryptedPassword()).isNull(); } @Test void validate_shouldEnsureUrlIsNotBlank() { HgMaterialConfig hgMaterialConfig = hg("", null); hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isEqualTo("URL cannot be blank"); } @Test void shouldReturnIfAttributeMapIsNull() { HgMaterialConfig hgMaterialConfig = hg("", null); hgMaterialConfig.setConfigAttributes(null); assertThat(hgMaterialConfig).isEqualTo(hg("", null)); } @Test void shouldReturnTheUrl() { String url = "[email protected]/my/repo"; HgMaterialConfig config = hg(url, null); assertThat(config.getUrl()).isEqualTo(url); } @Test void shouldReturnNullIfUrlForMaterialNotSpecified() { HgMaterialConfig config = hg(); assertThat(config.getUrl()).isNull(); } @Test void shouldSetUrlForAMaterial() { String url = "[email protected]/my/repo"; HgMaterialConfig config = hg(); config.setUrl(url); assertThat(config.getUrl()).isEqualTo(url); } @Test void shouldHandleNullWhenSettingUrlForAMaterial() { HgMaterialConfig config = hg(); config.setUrl(null); assertThat(config.getUrl()).isNull(); } @Nested class Equals { @Test void shouldBeEqualIfObjectsHaveSameUrlBranch() { final HgMaterialConfig material_1 = hg("http://example.com", "master"); material_1.setUserName("bob"); material_1.setBranchAttribute("feature"); final HgMaterialConfig material_2 = hg("http://example.com", "master"); material_2.setUserName("alice"); material_2.setBranchAttribute("feature"); assertThat(material_1.equals(material_2)).isTrue(); } } @Nested class Fingerprint { @Test void shouldGenerateFingerprintForGivenMaterialUrl() { HgMaterialConfig hgMaterialConfig = hg("https://bob:[email protected]/gocd#feature", "dest"); assertThat(hgMaterialConfig.getFingerprint()).isEqualTo("d84d91f37da0367a9bd89fff0d48638f5c1bf993d637735ec26f13c21c23da19"); } @Test void shouldConsiderBranchWhileGeneratingFingerprint_IfBranchSpecifiedAsAnAttribute() { HgMaterialConfig hgMaterialConfig = hg("https://bob:[email protected]/gocd", "dest"); hgMaterialConfig.setBranchAttribute("feature"); assertThat(hgMaterialConfig.getFingerprint()).isEqualTo("db13278ed2b804fc5664361103bcea3d7f5106879683085caed4311aa4d2f888"); } @Test void branchInUrlShouldGenerateFingerprintWhichIsOtherFromBranchInAttribute() { HgMaterialConfig hgMaterialConfigWithBranchInUrl = hg("https://github.com/gocd#feature", "dest"); HgMaterialConfig hgMaterialConfigWithBranchAsAttribute = hg("https://github.com/gocd", "dest"); hgMaterialConfigWithBranchAsAttribute.setBranchAttribute("feature"); assertThat(hgMaterialConfigWithBranchInUrl.getFingerprint()) .isNotEqualTo(hgMaterialConfigWithBranchAsAttribute.getFingerprint()); } } @Nested class validate { @Test void shouldEnsureUrlIsNotBlank() { hgMaterialConfig.setUrl(""); hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); assertThat(hgMaterialConfig.errors().on(ScmMaterialConfig.URL)).isEqualTo("URL cannot be blank"); } @Test void shouldEnsureUrlIsNotNull() { hgMaterialConfig.setUrl(null); hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); assertThat(hgMaterialConfig.errors().on(URL)).isEqualTo("URL cannot be blank"); } @Test void shouldEnsureMaterialNameIsValid() { hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); assertThat(hgMaterialConfig.errors().on(MATERIAL_NAME)).isNull(); hgMaterialConfig.setName(new CaseInsensitiveString(".bad-name-with-dot")); hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); assertThat(hgMaterialConfig.errors().on(MATERIAL_NAME)).isEqualTo("Invalid material name '.bad-name-with-dot'. This must be alphanumeric and can contain underscores, hyphens and periods (however, it cannot start with a period). The maximum allowed length is 255 characters."); } @Test void shouldEnsureDestFilePathIsValid() { hgMaterialConfig.setConfigAttributes(Collections.singletonMap(FOLDER, "../a")); hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); assertThat(hgMaterialConfig.errors().on(FOLDER)).isEqualTo("Dest folder '../a' is not valid. It must be a sub-directory of the working folder."); } @Test void shouldEnsureUserNameIsNotProvidedInBothUrlAsWellAsAttributes() { HgMaterialConfig hgMaterialConfig = hg("http://bob:[email protected]", null); hgMaterialConfig.setUserName("user"); hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isEqualTo("Ambiguous credentials, must be provided either in URL or as attributes."); } @Test void shouldEnsurePasswordIsNotProvidedInBothUrlAsWellAsAttributes() { HgMaterialConfig hgMaterialConfig = hg("http://bob:[email protected]", null); hgMaterialConfig.setPassword("pass"); hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isEqualTo("Ambiguous credentials, must be provided either in URL or as attributes."); } @Test void shouldIgnoreInvalidUrlForCredentialValidation() { HgMaterialConfig hgMaterialConfig = hg("http://bob:[email protected]##dobule-hash-is-invalid-in-url", null); hgMaterialConfig.setUserName("user"); hgMaterialConfig.setPassword("password"); hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isNull(); } @Test void shouldBeValidWhenCredentialsAreProvidedOnlyInUrl() { HgMaterialConfig hgMaterialConfig = hg("http://bob:[email protected]", null); hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isNull(); } @Test void shouldBeValidWhenCredentialsAreProvidedOnlyAsAttributes() { HgMaterialConfig hgMaterialConfig = hg("http://example.com", null); hgMaterialConfig.setUserName("bob"); hgMaterialConfig.setPassword("badger"); hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isNull(); } @Test void shouldEnsureBranchIsNotProvidedInBothUrlAsWellAsAttributes() { HgMaterialConfig hgMaterialConfig = hg("http://bob:[email protected]#some-branch", null); hgMaterialConfig.setBranchAttribute("branch-in-attribute"); hgMaterialConfig.validate(new ConfigSaveValidationContext(null)); assertThat(hgMaterialConfig.errors().on(HgMaterialConfig.URL)).isEqualTo("Ambiguous branch, must be provided either in URL or as an attribute."); } @Test void rejectsObviouslyWrongURL() { assertTrue(validating(hg("-url-not-starting-with-an-alphanumeric-character", "folder")).errors().containsKey(HgMaterialConfig.URL)); assertTrue(validating(hg("_url-not-starting-with-an-alphanumeric-character", "folder")).errors().containsKey(HgMaterialConfig.URL)); assertTrue(validating(hg("@url-not-starting-with-an-alphanumeric-character", "folder")).errors().containsKey(HgMaterialConfig.URL)); assertFalse(validating(hg("url-starting-with-an-alphanumeric-character", "folder")).errors().containsKey(HgMaterialConfig.URL)); // BUG: CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection') // // FIXED: assertFalse(validating(hg("#{url}", "folder")).errors().containsKey(HgMaterialConfig.URL)); } private HgMaterialConfig validating(HgMaterialConfig hg) { hg.validate(new ConfigSaveValidationContext(null)); return hg; } } @Nested class ValidateTree { @Test void shouldCallValidate() { final MaterialConfig materialConfig = spy(hg("https://example.repo", null)); final ValidationContext validationContext = mockValidationContextForSecretParams(); materialConfig.validateTree(validationContext); verify(materialConfig).validate(validationContext); } @Test void shouldFailIfEncryptedPasswordIsIncorrect() { HgMaterialConfig hgMaterialConfig = hg("http://example.com", null); hgMaterialConfig.setEncryptedPassword("encryptedPassword"); final boolean validationResult = hgMaterialConfig.validateTree(new ConfigSaveValidationContext(null)); assertThat(validationResult).isFalse(); assertThat(hgMaterialConfig.errors().on("encryptedPassword")) .isEqualTo("Encrypted password value for HgMaterial with url 'http://example.com' is invalid. This usually happens when the cipher text is modified to have an invalid value."); } } private ValidationContext mockValidationContextForSecretParams(SecretConfig... secretConfigs) { final ValidationContext validationContext = mock(ValidationContext.class); final CruiseConfig cruiseConfig = mock(CruiseConfig.class); when(validationContext.getCruiseConfig()).thenReturn(cruiseConfig); when(cruiseConfig.getSecretConfigs()).thenReturn(new SecretConfigs(secretConfigs)); return validationContext; }}
 
 
data/java/javacvefixed117.txt DELETED
@@ -1 +0,0 @@
1
- /* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package io.undertow.protocols.http2;import io.undertow.util.HeaderMap;import io.undertow.util.HeaderValues;import io.undertow.util.Headers;import io.undertow.util.HttpString;import java.nio.ByteBuffer;import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Collections;import java.util.Deque;import java.util.HashMap;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set;import static io.undertow.protocols.http2.Hpack.HeaderField;import static io.undertow.protocols.http2.Hpack.STATIC_TABLE;import static io.undertow.protocols.http2.Hpack.STATIC_TABLE_LENGTH;import static io.undertow.protocols.http2.Hpack.encodeInteger;/** * Encoder for HPACK frames. * * @author Stuart Douglas */public class HpackEncoder { private static final Set<HttpString> SKIP; static { Set<HttpString> set = new HashSet<>(); set.add(Headers.CONNECTION); set.add(Headers.TRANSFER_ENCODING); set.add(Headers.KEEP_ALIVE); set.add(Headers.UPGRADE); SKIP = Collections.unmodifiableSet(set); } public static final HpackHeaderFunction DEFAULT_HEADER_FUNCTION = new HpackHeaderFunction() { @Override public boolean shouldUseIndexing(HttpString headerName, String value) { //content length and date change all the time //no need to index them, or they will churn the table return !headerName.equals(Headers.CONTENT_LENGTH) && !headerName.equals(Headers.DATE); } @Override public boolean shouldUseHuffman(HttpString header, String value) { return value.length() > 10; //TODO: figure out a good value for this } @Override public boolean shouldUseHuffman(HttpString header) { return header.length() > 10; //TODO: figure out a good value for this } }; private long headersIterator = -1; private boolean firstPass = true; private HeaderMap currentHeaders; private int entryPositionCounter; private int newMaxHeaderSize = -1; //if the max header size has been changed private int minNewMaxHeaderSize = -1; //records the smallest value of newMaxHeaderSize, as per section 4.1 private static final Map<HttpString, TableEntry[]> ENCODING_STATIC_TABLE; private final Deque<TableEntry> evictionQueue = new ArrayDeque<>(); private final Map<HttpString, List<TableEntry>> dynamicTable = new HashMap<>(); private byte[] overflowData; private int overflowPos; private int overflowLength; static { Map<HttpString, TableEntry[]> map = new HashMap<>(); for (int i = 1; i < STATIC_TABLE.length; ++i) { HeaderField m = STATIC_TABLE[i]; TableEntry[] existing = map.get(m.name); if (existing == null) { map.put(m.name, new TableEntry[]{new TableEntry(m.name, m.value, i)}); } else { TableEntry[] newEntry = new TableEntry[existing.length + 1]; System.arraycopy(existing, 0, newEntry, 0, existing.length); newEntry[existing.length] = new TableEntry(m.name, m.value, i); map.put(m.name, newEntry); } } ENCODING_STATIC_TABLE = Collections.unmodifiableMap(map); } /** * The maximum table size */ private int maxTableSize; /** * The current table size */ private int currentTableSize; private final HpackHeaderFunction hpackHeaderFunction; public HpackEncoder(int maxTableSize, HpackHeaderFunction headerFunction) { this.maxTableSize = maxTableSize; this.hpackHeaderFunction = headerFunction; } public HpackEncoder(int maxTableSize) { this(maxTableSize, DEFAULT_HEADER_FUNCTION); } /** * Encodes the headers into a buffer. * * @param headers * @param target */ public State encode(HeaderMap headers, ByteBuffer target) { if(overflowData != null) { for(int i = overflowPos; i < overflowLength; ++i) { if(!target.hasRemaining()) { overflowPos = i; return State.OVERFLOW; } target.put(overflowData[i]); } overflowData = null; } long it = headersIterator; if (headersIterator == -1) { handleTableSizeChange(target); //new headers map it = headers.fastIterate(); currentHeaders = headers; } else { if (headers != currentHeaders) { throw new IllegalStateException(); } // BUG: NVD-CWE-noinfo Insufficient Information // it = headers.fiNext(it); // FIXED: it = headers.fiNext(it); } while (it != -1) { HeaderValues values = headers.fiCurrent(it); boolean skip = false; if (firstPass) { if (values.getHeaderName().byteAt(0) != ':') { skip = true; } } else { if (values.getHeaderName().byteAt(0) == ':') { skip = true; } } if(SKIP.contains(values.getHeaderName())) { //ignore connection specific headers skip = true; } if (!skip) { for (int i = 0; i < values.size(); ++i) { HttpString headerName = values.getHeaderName(); int required = 11 + headerName.length(); //we use 11 to make sure we have enough room for the variable length itegers String val = values.get(i); for(int v = 0; v < val.length(); ++v) { char c = val.charAt(v); if(c == '\r' || c == '\n') { val = val.replace('\r', ' ').replace('\n', ' '); break; } } TableEntry tableEntry = findInTable(headerName, val); required += (1 + val.length()); boolean overflowing = false; ByteBuffer current = target; if (current.remaining() < required) { overflowing = true; current = ByteBuffer.wrap(overflowData = new byte[required]); overflowPos = 0; } boolean canIndex = hpackHeaderFunction.shouldUseIndexing(headerName, val) && (headerName.length() + val.length() + 32) < maxTableSize; //only index if it will fit if (tableEntry == null && canIndex) { //add the entry to the dynamic table current.put((byte) (1 << 6)); writeHuffmanEncodableName(current, headerName); writeHuffmanEncodableValue(current, headerName, val); addToDynamicTable(headerName, val); } else if (tableEntry == null) { //literal never indexed current.put((byte) (1 << 4)); writeHuffmanEncodableName(current, headerName); writeHuffmanEncodableValue(current, headerName, val); } else { //so we know something is already in the table if (val.equals(tableEntry.value)) { //the whole thing is in the table current.put((byte) (1 << 7)); encodeInteger(current, tableEntry.getPosition(), 7); } else { if (canIndex) { //add the entry to the dynamic table current.put((byte) (1 << 6)); encodeInteger(current, tableEntry.getPosition(), 6); writeHuffmanEncodableValue(current, headerName, val); addToDynamicTable(headerName, val); } else { current.put((byte) (1 << 4)); encodeInteger(current, tableEntry.getPosition(), 4); writeHuffmanEncodableValue(current, headerName, val); } } } if(overflowing) { this.headersIterator = it; this.overflowLength = current.position(); return State.OVERFLOW; } } } it = headers.fiNext(it); if (it == -1 && firstPass) { firstPass = false; it = headers.fastIterate(); } } headersIterator = -1; firstPass = true; return State.COMPLETE; } private void writeHuffmanEncodableName(ByteBuffer target, HttpString headerName) { if (hpackHeaderFunction.shouldUseHuffman(headerName)) { if(HPackHuffman.encode(target, headerName.toString(), true)) { return; } } target.put((byte) 0); //to use encodeInteger we need to place the first byte in the buffer. encodeInteger(target, headerName.length(), 7); for (int j = 0; j < headerName.length(); ++j) { target.put(Hpack.toLower(headerName.byteAt(j))); } } private void writeHuffmanEncodableValue(ByteBuffer target, HttpString headerName, String val) { if (hpackHeaderFunction.shouldUseHuffman(headerName, val)) { if (!HPackHuffman.encode(target, val, false)) { writeValueString(target, val); } } else { writeValueString(target, val); } } private void writeValueString(ByteBuffer target, String val) { target.put((byte) 0); //to use encodeInteger we need to place the first byte in the buffer. encodeInteger(target, val.length(), 7); for (int j = 0; j < val.length(); ++j) { target.put((byte) val.charAt(j)); } } private void addToDynamicTable(HttpString headerName, String val) { int pos = entryPositionCounter++; DynamicTableEntry d = new DynamicTableEntry(headerName, val, -pos); List<TableEntry> existing = dynamicTable.get(headerName); if (existing == null) { dynamicTable.put(headerName, existing = new ArrayList<>(1)); } existing.add(d); evictionQueue.add(d); currentTableSize += d.size; runEvictionIfRequired(); if (entryPositionCounter == Integer.MAX_VALUE) { //prevent rollover preventPositionRollover(); } } private void preventPositionRollover() { //if the position counter is about to roll over we iterate all the table entries //and set their position to their actual position for (Map.Entry<HttpString, List<TableEntry>> entry : dynamicTable.entrySet()) { for (TableEntry t : entry.getValue()) { t.position = t.getPosition(); } } entryPositionCounter = 0; } private void runEvictionIfRequired() { while (currentTableSize > maxTableSize) { TableEntry next = evictionQueue.poll(); if (next == null) { return; } currentTableSize -= next.size; List<TableEntry> list = dynamicTable.get(next.name); list.remove(next); if (list.isEmpty()) { dynamicTable.remove(next.name); } } } private TableEntry findInTable(HttpString headerName, String value) { TableEntry[] staticTable = ENCODING_STATIC_TABLE.get(headerName); if (staticTable != null) { for (TableEntry st : staticTable) { if (st.value != null && st.value.equals(value)) { //todo: some form of lookup? return st; } } } List<TableEntry> dynamic = dynamicTable.get(headerName); if (dynamic != null) { for (int i = 0; i < dynamic.size(); ++i) { TableEntry st = dynamic.get(i); if (st.value.equals(value)) { //todo: some form of lookup? return st; } } } if (staticTable != null) { return staticTable[0]; } return null; } public void setMaxTableSize(int newSize) { this.newMaxHeaderSize = newSize; if (minNewMaxHeaderSize == -1) { minNewMaxHeaderSize = newSize; } else { minNewMaxHeaderSize = Math.min(newSize, minNewMaxHeaderSize); } } private void handleTableSizeChange(ByteBuffer target) { if (newMaxHeaderSize == -1) { return; } if (minNewMaxHeaderSize != newMaxHeaderSize) { target.put((byte) (1 << 5)); encodeInteger(target, minNewMaxHeaderSize, 5); } target.put((byte) (1 << 5)); encodeInteger(target, newMaxHeaderSize, 5); maxTableSize = newMaxHeaderSize; runEvictionIfRequired(); newMaxHeaderSize = -1; minNewMaxHeaderSize = -1; } public enum State { COMPLETE, OVERFLOW, } static class TableEntry { final HttpString name; final String value; final int size; int position; TableEntry(HttpString name, String value, int position) { this.name = name; this.value = value; this.position = position; if (value != null) { this.size = 32 + name.length() + value.length(); } else { this.size = -1; } } public int getPosition() { return position; } } class DynamicTableEntry extends TableEntry { DynamicTableEntry(HttpString name, String value, int position) { super(name, value, position); } @Override public int getPosition() { return super.getPosition() + entryPositionCounter + STATIC_TABLE_LENGTH; } } public interface HpackHeaderFunction { boolean shouldUseIndexing(HttpString header, String value); /** * Returns true if huffman encoding should be used on the header value * * @param header The header name * @param value The header value to be encoded * @return <code>true</code> if the value should be encoded */ boolean shouldUseHuffman(HttpString header, String value); /** * Returns true if huffman encoding should be used on the header name * * @param header The header name to be encoded * @return <code>true</code> if the value should be encoded */ boolean shouldUseHuffman(HttpString header); }}
 
 
data/java/javacvefixed118.txt DELETED
The diff for this file is too large to render. See raw diff
 
data/java/javacvefixed119.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright 2017-2019 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package io.micronaut.http.client.exceptions;import io.micronaut.core.annotation.Internal;import io.micronaut.core.naming.Described;import io.micronaut.core.type.Argument;import io.micronaut.http.MediaType;import io.micronaut.http.hateoas.JsonError;import io.micronaut.http.hateoas.VndError;import java.util.Optional;/** * Strategy interface for decoding the error from a server respponse. * * @author graemerocher * @since 1.0 */@Internalpublic interface HttpClientErrorDecoder { /** * The default implementation. */ HttpClientErrorDecoder DEFAULT = new HttpClientErrorDecoder() { }; /** * Default message decoder. * * @param error The error object * @return The message */ default Optional<String> getMessage(Object error) { if (error == null) { return Optional.empty(); } if (error instanceof JsonError) { return Optional.ofNullable(((JsonError) error).getMessage()); } else { if (error instanceof Described) { return Optional.ofNullable(((Described) error).getDescription()); } else { return Optional.of(error.toString()); } } } /** * Gets the error type for the given media type. * * @param mediaType The media type * @return The error type */ default Argument<?> getErrorType(MediaType mediaType) { if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) { return Argument.of(JsonError.class); } else if (mediaType.equals(MediaType.APPLICATION_VND_ERROR_TYPE)) { return Argument.of(VndError.class); } else { // BUG: CWE-400 Uncontrolled Resource Consumption // return Argument.of(String.class); // FIXED: return Argument.STRING; } }}
 
 
data/java/javacvefixed12.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright 2016 LINE Corporation * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. *//* * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */package com.linecorp.armeria.internal;import static com.google.common.collect.ImmutableSet.toImmutableSet;import static io.netty.handler.codec.http.HttpUtil.isAsteriskForm;import static io.netty.handler.codec.http.HttpUtil.isOriginForm;import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;import static io.netty.handler.codec.http2.Http2Exception.streamError;import static io.netty.util.AsciiString.EMPTY_STRING;import static io.netty.util.ByteProcessor.FIND_COMMA;import static io.netty.util.internal.StringUtil.decodeHexNibble;import static io.netty.util.internal.StringUtil.isNullOrEmpty;import static io.netty.util.internal.StringUtil.length;import static java.util.Objects.requireNonNull;import java.net.InetSocketAddress;import java.net.URI;import java.net.URISyntaxException;import java.nio.charset.Charset;import java.nio.charset.StandardCharsets;import java.util.Iterator;import java.util.List;import java.util.Map.Entry;import java.util.Set;import java.util.StringJoiner;import java.util.function.BiConsumer;import javax.annotation.Nullable;import com.github.benmanes.caffeine.cache.Caffeine;import com.github.benmanes.caffeine.cache.LoadingCache;import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Ascii;import com.google.common.base.Splitter;import com.google.common.base.Strings;import com.linecorp.armeria.common.Flags;import com.linecorp.armeria.common.HttpData;import com.linecorp.armeria.common.HttpHeaderNames;import com.linecorp.armeria.common.HttpHeaders;import com.linecorp.armeria.common.HttpHeadersBuilder;import com.linecorp.armeria.common.HttpMethod;import com.linecorp.armeria.common.HttpStatus;import com.linecorp.armeria.common.RequestHeaders;import com.linecorp.armeria.common.RequestHeadersBuilder;import com.linecorp.armeria.common.ResponseHeaders;import com.linecorp.armeria.common.ResponseHeadersBuilder;import com.linecorp.armeria.server.ServerConfig;import io.netty.channel.ChannelHandlerContext;import io.netty.handler.codec.DefaultHeaders;import io.netty.handler.codec.UnsupportedValueConverter;import io.netty.handler.codec.http.HttpHeaderValues;import io.netty.handler.codec.http.HttpRequest;import io.netty.handler.codec.http.HttpResponse;import io.netty.handler.codec.http.HttpUtil;import io.netty.handler.codec.http.HttpVersion;import io.netty.handler.codec.http2.DefaultHttp2Headers;import io.netty.handler.codec.http2.Http2Exception;import io.netty.handler.codec.http2.Http2Headers;import io.netty.handler.codec.http2.HttpConversionUtil;import io.netty.handler.codec.http2.HttpConversionUtil.ExtensionHeaderNames;import io.netty.util.AsciiString;import io.netty.util.HashingStrategy;import io.netty.util.internal.StringUtil;/** * Provides various utility functions for internal use related with HTTP. * * <p>The conversion between HTTP/1 and HTTP/2 has been forked from Netty's {@link HttpConversionUtil}. */public final class ArmeriaHttpUtil { // Forked from Netty 4.1.34 at 4921f62c8ab8205fd222439dcd1811760b05daf1 /** * The default case-insensitive {@link AsciiString} hasher and comparator for HTTP/2 headers. */ private static final HashingStrategy<AsciiString> HTTP2_HEADER_NAME_HASHER = new HashingStrategy<AsciiString>() { @Override public int hashCode(AsciiString o) { return o.hashCode(); } @Override public boolean equals(AsciiString a, AsciiString b) { return a.contentEqualsIgnoreCase(b); } }; /** * The default HTTP content-type charset. * See https://tools.ietf.org/html/rfc2616#section-3.7.1 */ public static final Charset HTTP_DEFAULT_CONTENT_CHARSET = StandardCharsets.ISO_8859_1; /** * The old {@code "keep-alive"} header which has been superceded by {@code "connection"}. */ public static final AsciiString HEADER_NAME_KEEP_ALIVE = AsciiString.cached("keep-alive"); /** * The old {@code "proxy-connection"} header which has been superceded by {@code "connection"}. */ public static final AsciiString HEADER_NAME_PROXY_CONNECTION = AsciiString.cached("proxy-connection"); private static final URI ROOT = URI.create("/"); /** * The set of headers that should not be directly copied when converting headers from HTTP/1 to HTTP/2. */ private static final CharSequenceMap HTTP_TO_HTTP2_HEADER_BLACKLIST = new CharSequenceMap(); /** * The set of headers that should not be directly copied when converting headers from HTTP/2 to HTTP/1. */ private static final CharSequenceMap HTTP2_TO_HTTP_HEADER_BLACKLIST = new CharSequenceMap(); /** * The set of headers that must not be directly copied when converting trailers. */ private static final CharSequenceMap HTTP_TRAILER_BLACKLIST = new CharSequenceMap(); static { HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.CONNECTION, EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HEADER_NAME_KEEP_ALIVE, EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HEADER_NAME_PROXY_CONNECTION, EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.HOST, EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.UPGRADE, EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.STREAM_ID.text(), EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.SCHEME.text(), EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.PATH.text(), EMPTY_STRING); // https://tools.ietf.org/html/rfc7540#section-8.1.2.3 HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.AUTHORITY, EMPTY_STRING); HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.METHOD, EMPTY_STRING); HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.PATH, EMPTY_STRING); HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.SCHEME, EMPTY_STRING); HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.STATUS, EMPTY_STRING); // https://tools.ietf.org/html/rfc7540#section-8.1 // The "chunked" transfer encoding defined in Section 4.1 of [RFC7230] MUST NOT be used in HTTP/2. HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING); HTTP2_TO_HTTP_HEADER_BLACKLIST.add(ExtensionHeaderNames.STREAM_ID.text(), EMPTY_STRING); HTTP2_TO_HTTP_HEADER_BLACKLIST.add(ExtensionHeaderNames.SCHEME.text(), EMPTY_STRING); HTTP2_TO_HTTP_HEADER_BLACKLIST.add(ExtensionHeaderNames.PATH.text(), EMPTY_STRING); // https://tools.ietf.org/html/rfc7230#section-4.1.2 // https://tools.ietf.org/html/rfc7540#section-8.1 // A sender MUST NOT generate a trailer that contains a field necessary for message framing: HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_LENGTH, EMPTY_STRING); // for request modifiers: HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CACHE_CONTROL, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.EXPECT, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.HOST, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.MAX_FORWARDS, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.PRAGMA, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.RANGE, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.TE, EMPTY_STRING); // for authentication: HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.WWW_AUTHENTICATE, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.AUTHORIZATION, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.PROXY_AUTHENTICATE, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.PROXY_AUTHORIZATION, EMPTY_STRING); // for response control data: HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.DATE, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.LOCATION, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.RETRY_AFTER, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.VARY, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.WARNING, EMPTY_STRING); // or for determining how to process the payload: HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_ENCODING, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_TYPE, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_RANGE, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.TRAILER, EMPTY_STRING); } /** * Translations from HTTP/2 header name to the HTTP/1.x equivalent. Currently, we expect these headers to * only allow a single value in the request. If adding headers that can potentially have multiple values, * please check the usage in code accordingly. */ private static final CharSequenceMap REQUEST_HEADER_TRANSLATIONS = new CharSequenceMap(); private static final CharSequenceMap RESPONSE_HEADER_TRANSLATIONS = new CharSequenceMap(); static { RESPONSE_HEADER_TRANSLATIONS.add(Http2Headers.PseudoHeaderName.AUTHORITY.value(), HttpHeaderNames.HOST); REQUEST_HEADER_TRANSLATIONS.add(RESPONSE_HEADER_TRANSLATIONS); } /** * <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.3">rfc7540, 8.1.2.3</a> states the path must not * be empty, and instead should be {@code /}. */ private static final String EMPTY_REQUEST_PATH = "/"; private static final Splitter COOKIE_SPLITTER = Splitter.on(';').trimResults().omitEmptyStrings(); private static final String COOKIE_SEPARATOR = "; "; @Nullable private static final LoadingCache<AsciiString, String> HEADER_VALUE_CACHE = Flags.headerValueCacheSpec().map(ArmeriaHttpUtil::buildCache).orElse(null); private static final Set<AsciiString> CACHED_HEADERS = Flags.cachedHeaders().stream().map(AsciiString::of) .collect(toImmutableSet()); private static LoadingCache<AsciiString, String> buildCache(String spec) { return Caffeine.from(spec).build(AsciiString::toString); } /** * Concatenates two path strings. */ public static String concatPaths(@Nullable String path1, @Nullable String path2) { path2 = path2 == null ? "" : path2; if (path1 == null || path1.isEmpty() || EMPTY_REQUEST_PATH.equals(path1)) { if (path2.isEmpty()) { return EMPTY_REQUEST_PATH; } if (path2.charAt(0) == '/') { return path2; // Most requests will land here. } return '/' + path2; } // At this point, we are sure path1 is neither empty nor null. if (path2.isEmpty()) { // Only path1 is non-empty. No need to concatenate. return path1; } if (path1.charAt(path1.length() - 1) == '/') { if (path2.charAt(0) == '/') { // path1 ends with '/' and path2 starts with '/'. // Avoid double-slash by stripping the first slash of path2. return new StringBuilder(path1.length() + path2.length() - 1) .append(path1).append(path2, 1, path2.length()).toString(); } // path1 ends with '/' and path2 does not start with '/'. // Simple concatenation would suffice. return path1 + path2; } if (path2.charAt(0) == '/') { // path1 does not end with '/' and path2 starts with '/'. // Simple concatenation would suffice. return path1 + path2; } // path1 does not end with '/' and path2 does not start with '/'. // Need to insert '/' between path1 and path2. return path1 + '/' + path2; } /** * Decodes a percent-encoded path string. */ public static String decodePath(String path) { if (path.indexOf('%') < 0) { // No need to decoded; not percent-encoded return path; } // Decode percent-encoded characters. // An invalid character is replaced with 0xFF, which will be replaced into '�' by UTF-8 decoder. final int len = path.length(); final byte[] buf = ThreadLocalByteArray.get(len); int dstLen = 0; for (int i = 0; i < len; i++) { final char ch = path.charAt(i); if (ch != '%') { buf[dstLen++] = (byte) ((ch & 0xFF80) == 0 ? ch : 0xFF); continue; } // Decode a percent-encoded character. final int hexEnd = i + 3; if (hexEnd > len) { // '%' or '%x' (must be followed by two hexadigits) buf[dstLen++] = (byte) 0xFF; break; } final int digit1 = decodeHexNibble(path.charAt(++i)); final int digit2 = decodeHexNibble(path.charAt(++i)); if (digit1 < 0 || digit2 < 0) { // The first or second digit is not hexadecimal. buf[dstLen++] = (byte) 0xFF; } else { buf[dstLen++] = (byte) ((digit1 << 4) | digit2); } } return new String(buf, 0, dstLen, StandardCharsets.UTF_8); } /** * Returns {@code true} if the specified {@code path} is an absolute {@code URI}. */ public static boolean isAbsoluteUri(@Nullable String maybeUri) { if (maybeUri == null) { return false; } final int firstColonIdx = maybeUri.indexOf(':'); if (firstColonIdx <= 0 || firstColonIdx + 3 >= maybeUri.length()) { return false; } final int firstSlashIdx = maybeUri.indexOf('/'); if (firstSlashIdx <= 0 || firstSlashIdx < firstColonIdx) { return false; } return maybeUri.charAt(firstColonIdx + 1) == '/' && maybeUri.charAt(firstColonIdx + 2) == '/'; } /** * Returns {@code true} if the specified HTTP status string represents an informational status. */ public static boolean isInformational(@Nullable String statusText) { return statusText != null && !statusText.isEmpty() && statusText.charAt(0) == '1'; } /** * Returns {@code true} if the content of the response with the given {@link HttpStatus} is expected to * be always empty (1xx, 204, 205 and 304 responses.) * * @throws IllegalArgumentException if the specified {@code content} or {@code trailers} are * non-empty when the content is always empty */ public static boolean isContentAlwaysEmptyWithValidation( HttpStatus status, HttpData content, HttpHeaders trailers) { if (!status.isContentAlwaysEmpty()) { return false; } if (!content.isEmpty()) { throw new IllegalArgumentException( "A " + status + " response must have empty content: " + content.length() + " byte(s)"); } if (!trailers.isEmpty()) { throw new IllegalArgumentException( "A " + status + " response must not have trailers: " + trailers); } return true; } /** * Returns {@code true} if the specified {@code request} is a CORS preflight request. */ public static boolean isCorsPreflightRequest(com.linecorp.armeria.common.HttpRequest request) { requireNonNull(request, "request"); return request.method() == HttpMethod.OPTIONS && request.headers().contains(HttpHeaderNames.ORIGIN) && request.headers().contains(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD); } /** * Parses the specified HTTP header directives and invokes the specified {@code callback} * with the directive names and values. */ public static void parseDirectives(String directives, BiConsumer<String, String> callback) { final int len = directives.length(); for (int i = 0; i < len;) { final int nameStart = i; final String name; final String value; // Find the name. for (; i < len; i++) { final char ch = directives.charAt(i); if (ch == ',' || ch == '=') { break; } } name = directives.substring(nameStart, i).trim(); // Find the value. if (i == len || directives.charAt(i) == ',') { // Skip comma or go beyond 'len' to break the loop. i++; value = null; } else { // Skip '='. i++; // Skip whitespaces. for (; i < len; i++) { final char ch = directives.charAt(i); if (ch != ' ' && ch != '\t') { break; } } if (i < len && directives.charAt(i) == '\"') { // Handle quoted string. // Skip the opening quote. i++; final int valueStart = i; // Find the closing quote. for (; i < len; i++) { if (directives.charAt(i) == '\"') { break; } } value = directives.substring(valueStart, i); // Skip the closing quote. i++; // Find the comma and skip it. for (; i < len; i++) { if (directives.charAt(i) == ',') { i++; break; } } } else { // Handle unquoted string. final int valueStart = i; // Find the comma. for (; i < len; i++) { if (directives.charAt(i) == ',') { break; } } value = directives.substring(valueStart, i).trim(); // Skip the comma. i++; } } if (!name.isEmpty()) { callback.accept(Ascii.toLowerCase(name), Strings.emptyToNull(value)); } } } /** * Converts the specified HTTP header directive value into a long integer. * * @return the converted value if {@code value} is equal to or greater than {@code 0}. * {@code -1} otherwise, i.e. if a negative integer or not a number. */ public static long parseDirectiveValueAsSeconds(@Nullable String value) { if (value == null) { return -1; } try { final long converted = Long.parseLong(value); return converted >= 0 ? converted : -1; } catch (NumberFormatException e) { return -1; } } /** * Converts the specified Netty HTTP/2 into Armeria HTTP/2 {@link RequestHeaders}. */ public static RequestHeaders toArmeriaRequestHeaders(ChannelHandlerContext ctx, Http2Headers headers, boolean endOfStream, String scheme, ServerConfig cfg) { final RequestHeadersBuilder builder = RequestHeaders.builder(); toArmeria(builder, headers, endOfStream); // A CONNECT request might not have ":scheme". See https://tools.ietf.org/html/rfc7540#section-8.1.2.3 if (!builder.contains(HttpHeaderNames.SCHEME)) { builder.add(HttpHeaderNames.SCHEME, scheme); } if (!builder.contains(HttpHeaderNames.AUTHORITY)) { final String defaultHostname = cfg.defaultVirtualHost().defaultHostname(); final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort(); builder.add(HttpHeaderNames.AUTHORITY, defaultHostname + ':' + port); } return builder.build(); } /** * Converts the specified Netty HTTP/2 into Armeria HTTP/2 headers. */ public static HttpHeaders toArmeria(Http2Headers headers, boolean request, boolean endOfStream) { final HttpHeadersBuilder builder; if (request) { builder = headers.contains(HttpHeaderNames.METHOD) ? RequestHeaders.builder() : HttpHeaders.builder(); } else { builder = headers.contains(HttpHeaderNames.STATUS) ? ResponseHeaders.builder() : HttpHeaders.builder(); } toArmeria(builder, headers, endOfStream); return builder.build(); } private static void toArmeria(HttpHeadersBuilder builder, Http2Headers headers, boolean endOfStream) { builder.sizeHint(headers.size()); builder.endOfStream(endOfStream); StringJoiner cookieJoiner = null; for (Entry<CharSequence, CharSequence> e : headers) { final AsciiString name = HttpHeaderNames.of(e.getKey()); final CharSequence value = e.getValue(); // Cookies must be concatenated into a single octet string. // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 if (name.equals(HttpHeaderNames.COOKIE)) { if (cookieJoiner == null) { cookieJoiner = new StringJoiner(COOKIE_SEPARATOR); } COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add); } else { builder.add(name, convertHeaderValue(name, value)); } } if (cookieJoiner != null && cookieJoiner.length() != 0) { builder.add(HttpHeaderNames.COOKIE, cookieJoiner.toString()); } } /** * Converts the headers of the given Netty HTTP/1.x request into Armeria HTTP/2 headers. * The following headers are only used if they can not be found in the {@code HOST} header or the * {@code Request-Line} as defined by <a href="https://tools.ietf.org/html/rfc7230">rfc7230</a> * <ul> * <li>{@link ExtensionHeaderNames#SCHEME}</li> * </ul> * {@link ExtensionHeaderNames#PATH} is ignored and instead extracted from the {@code Request-Line}. */ public static RequestHeaders toArmeria(ChannelHandlerContext ctx, HttpRequest in, ServerConfig cfg) throws URISyntaxException { final URI requestTargetUri = toUri(in); final io.netty.handler.codec.http.HttpHeaders inHeaders = in.headers(); final RequestHeadersBuilder out = RequestHeaders.builder(); out.sizeHint(inHeaders.size()); out.add(HttpHeaderNames.METHOD, in.method().name()); out.add(HttpHeaderNames.PATH, toHttp2Path(requestTargetUri)); addHttp2Scheme(inHeaders, requestTargetUri, out); if (!isOriginForm(requestTargetUri) && !isAsteriskForm(requestTargetUri)) { // Attempt to take from HOST header before taking from the request-line final String host = inHeaders.getAsString(HttpHeaderNames.HOST); addHttp2Authority(host == null || host.isEmpty() ? requestTargetUri.getAuthority() : host, out); } if (out.authority() == null) { final String defaultHostname = cfg.defaultVirtualHost().defaultHostname(); final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort(); out.add(HttpHeaderNames.AUTHORITY, defaultHostname + ':' + port); } // Add the HTTP headers which have not been consumed above toArmeria(inHeaders, out); return out.build(); } /** * Converts the headers of the given Netty HTTP/1.x response into Armeria HTTP/2 headers. */ public static ResponseHeaders toArmeria(HttpResponse in) { final io.netty.handler.codec.http.HttpHeaders inHeaders = in.headers(); final ResponseHeadersBuilder out = ResponseHeaders.builder(); out.sizeHint(inHeaders.size()); out.add(HttpHeaderNames.STATUS, HttpStatus.valueOf(in.status().code()).codeAsText()); // Add the HTTP headers which have not been consumed above toArmeria(inHeaders, out); return out.build(); } /** * Converts the specified Netty HTTP/1 headers into Armeria HTTP/2 headers. */ public static HttpHeaders toArmeria(io.netty.handler.codec.http.HttpHeaders inHeaders) { if (inHeaders.isEmpty()) { return HttpHeaders.of(); } final HttpHeadersBuilder out = HttpHeaders.builder(); out.sizeHint(inHeaders.size()); toArmeria(inHeaders, out); return out.build(); } /** * Converts the specified Netty HTTP/1 headers into Armeria HTTP/2 headers. */ public static void toArmeria(io.netty.handler.codec.http.HttpHeaders inHeaders, HttpHeadersBuilder out) { final Iterator<Entry<CharSequence, CharSequence>> iter = inHeaders.iteratorCharSequence(); // Choose 8 as a default size because it is unlikely we will see more than 4 Connection headers values, // but still allowing for "enough" space in the map to reduce the chance of hash code collision. final CharSequenceMap connectionBlacklist = toLowercaseMap(inHeaders.valueCharSequenceIterator(HttpHeaderNames.CONNECTION), 8); StringJoiner cookieJoiner = null; while (iter.hasNext()) { final Entry<CharSequence, CharSequence> entry = iter.next(); final AsciiString aName = HttpHeaderNames.of(entry.getKey()).toLowerCase(); if (HTTP_TO_HTTP2_HEADER_BLACKLIST.contains(aName) || connectionBlacklist.contains(aName)) { continue; } // https://tools.ietf.org/html/rfc7540#section-8.1.2.2 makes a special exception for TE if (aName.equals(HttpHeaderNames.TE)) { toHttp2HeadersFilterTE(entry, out); continue; } // Cookies must be concatenated into a single octet string. // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 final CharSequence value = entry.getValue(); if (aName.equals(HttpHeaderNames.COOKIE)) { if (cookieJoiner == null) { cookieJoiner = new StringJoiner(COOKIE_SEPARATOR); } COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add); } else { out.add(aName, convertHeaderValue(aName, value)); } } if (cookieJoiner != null && cookieJoiner.length() != 0) { out.add(HttpHeaderNames.COOKIE, cookieJoiner.toString()); } } private static CharSequenceMap toLowercaseMap(Iterator<? extends CharSequence> valuesIter, int arraySizeHint) { final CharSequenceMap result = new CharSequenceMap(arraySizeHint); while (valuesIter.hasNext()) { // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') // final AsciiString lowerCased = HttpHeaderNames.of(valuesIter.next()).toLowerCase(); // FIXED: final AsciiString lowerCased = AsciiString.of(valuesIter.next()).toLowerCase(); try { int index = lowerCased.forEachByte(FIND_COMMA); if (index != -1) { int start = 0; do { result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING); start = index + 1; } while (start < lowerCased.length() && (index = lowerCased.forEachByte(start, lowerCased.length() - start, FIND_COMMA)) != -1); result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING); } else { result.add(lowerCased.trim(), EMPTY_STRING); } } catch (Exception e) { // This is not expect to happen because FIND_COMMA never throws but must be caught // because of the ByteProcessor interface. throw new IllegalStateException(e); } } return result; } /** * Filter the {@link HttpHeaderNames#TE} header according to the * <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.2">special rules in the HTTP/2 RFC</a>. * @param entry An entry whose name is {@link HttpHeaderNames#TE}. * @param out the resulting HTTP/2 headers. */ private static void toHttp2HeadersFilterTE(Entry<CharSequence, CharSequence> entry, HttpHeadersBuilder out) { if (AsciiString.indexOf(entry.getValue(), ',', 0) == -1) { if (AsciiString.contentEqualsIgnoreCase(AsciiString.trim(entry.getValue()), HttpHeaderValues.TRAILERS)) { out.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS.toString()); } } else { final List<CharSequence> teValues = StringUtil.unescapeCsvFields(entry.getValue()); for (CharSequence teValue : teValues) { if (AsciiString.contentEqualsIgnoreCase(AsciiString.trim(teValue), HttpHeaderValues.TRAILERS)) { out.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS.toString()); break; } } } } private static URI toUri(HttpRequest in) throws URISyntaxException { final String uri = in.uri(); if (uri.startsWith("//")) { // Normalize the path that starts with more than one slash into the one with a single slash, // so that java.net.URI does not raise a URISyntaxException. for (int i = 0; i < uri.length(); i++) { if (uri.charAt(i) != '/') { return new URI(uri.substring(i - 1)); } } return ROOT; } else { return new URI(uri); } } /** * Generate a HTTP/2 {code :path} from a URI in accordance with * <a href="https://tools.ietf.org/html/rfc7230#section-5.3">rfc7230, 5.3</a>. */ private static String toHttp2Path(URI uri) { final StringBuilder pathBuilder = new StringBuilder( length(uri.getRawPath()) + length(uri.getRawQuery()) + length(uri.getRawFragment()) + 2); if (!isNullOrEmpty(uri.getRawPath())) { pathBuilder.append(uri.getRawPath()); } if (!isNullOrEmpty(uri.getRawQuery())) { pathBuilder.append('?'); pathBuilder.append(uri.getRawQuery()); } if (!isNullOrEmpty(uri.getRawFragment())) { pathBuilder.append('#'); pathBuilder.append(uri.getRawFragment()); } return pathBuilder.length() != 0 ? pathBuilder.toString() : EMPTY_REQUEST_PATH; } @VisibleForTesting static void addHttp2Authority(@Nullable String authority, RequestHeadersBuilder out) { // The authority MUST NOT include the deprecated "userinfo" subcomponent if (authority != null) { final String actualAuthority; if (authority.isEmpty()) { actualAuthority = ""; } else { final int start = authority.indexOf('@') + 1; if (start == 0) { actualAuthority = authority; } else if (authority.length() == start) { throw new IllegalArgumentException("authority: " + authority); } else { actualAuthority = authority.substring(start); } } out.add(HttpHeaderNames.AUTHORITY, actualAuthority); } } private static void addHttp2Scheme(io.netty.handler.codec.http.HttpHeaders in, URI uri, RequestHeadersBuilder out) { final String value = uri.getScheme(); if (value != null) { out.add(HttpHeaderNames.SCHEME, value); return; } // Consume the Scheme extension header if present final CharSequence cValue = in.get(ExtensionHeaderNames.SCHEME.text()); if (cValue != null) { out.add(HttpHeaderNames.SCHEME, cValue.toString()); } else { out.add(HttpHeaderNames.SCHEME, "unknown"); } } /** * Converts the specified Armeria HTTP/2 headers into Netty HTTP/2 headers. */ public static Http2Headers toNettyHttp2(HttpHeaders in, boolean server) { final Http2Headers out = new DefaultHttp2Headers(false, in.size()); // Trailers if it does not have :status. if (server && !in.contains(HttpHeaderNames.STATUS)) { for (Entry<AsciiString, String> entry : in) { final AsciiString name = entry.getKey(); final String value = entry.getValue(); if (name.isEmpty() || isTrailerBlacklisted(name)) { continue; } out.add(name, value); } } else { in.forEach((BiConsumer<AsciiString, String>) out::add); out.remove(HttpHeaderNames.CONNECTION); out.remove(HttpHeaderNames.TRANSFER_ENCODING); } if (!out.contains(HttpHeaderNames.COOKIE)) { return out; } // Split up cookies to allow for better compression. // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 final List<CharSequence> cookies = out.getAllAndRemove(HttpHeaderNames.COOKIE); for (CharSequence c : cookies) { out.add(HttpHeaderNames.COOKIE, COOKIE_SPLITTER.split(c)); } return out; } /** * Translate and add HTTP/2 headers to HTTP/1.x headers. * * @param streamId The stream associated with {@code sourceHeaders}. * @param inputHeaders The HTTP/2 headers to convert. * @param outputHeaders The object which will contain the resulting HTTP/1.x headers.. * @param httpVersion What HTTP/1.x version {@code outputHeaders} should be treated as * when doing the conversion. * @param isTrailer {@code true} if {@code outputHeaders} should be treated as trailers. * {@code false} otherwise. * @param isRequest {@code true} if the {@code outputHeaders} will be used in a request message. * {@code false} for response message. * * @throws Http2Exception If not all HTTP/2 headers can be translated to HTTP/1.x. */ public static void toNettyHttp1( int streamId, HttpHeaders inputHeaders, io.netty.handler.codec.http.HttpHeaders outputHeaders, HttpVersion httpVersion, boolean isTrailer, boolean isRequest) throws Http2Exception { final CharSequenceMap translations = isRequest ? REQUEST_HEADER_TRANSLATIONS : RESPONSE_HEADER_TRANSLATIONS; StringJoiner cookieJoiner = null; try { for (Entry<AsciiString, String> entry : inputHeaders) { final AsciiString name = entry.getKey(); final String value = entry.getValue(); final AsciiString translatedName = translations.get(name); if (translatedName != null && !inputHeaders.contains(translatedName)) { outputHeaders.add(translatedName, value); continue; } if (name.isEmpty() || HTTP2_TO_HTTP_HEADER_BLACKLIST.contains(name)) { continue; } if (isTrailer && isTrailerBlacklisted(name)) { continue; } if (HttpHeaderNames.COOKIE.equals(name)) { // combine the cookie values into 1 header entry. // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 if (cookieJoiner == null) { cookieJoiner = new StringJoiner(COOKIE_SEPARATOR); } COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add); } else { outputHeaders.add(name, value); } } if (cookieJoiner != null && cookieJoiner.length() != 0) { outputHeaders.add(HttpHeaderNames.COOKIE, cookieJoiner.toString()); } } catch (Throwable t) { throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error"); } if (!isTrailer) { HttpUtil.setKeepAlive(outputHeaders, httpVersion, true); } } /** * Returns a {@link ResponseHeaders} whose {@link HttpHeaderNames#CONTENT_LENGTH} is added or removed * according to the status of the specified {@code headers}, {@code content} and {@code trailers}. * The {@link HttpHeaderNames#CONTENT_LENGTH} is removed when: * <ul> * <li>the status of the specified {@code headers} is one of informational headers, * {@link HttpStatus#NO_CONTENT} or {@link HttpStatus#RESET_CONTENT}</li> * <li>the trailers exists</li> * </ul> * The {@link HttpHeaderNames#CONTENT_LENGTH} is added when the state of the specified {@code headers} * does not meet the conditions above and {@link HttpHeaderNames#CONTENT_LENGTH} is not present * regardless of the fact that the content is empty or not. * * @throws IllegalArgumentException if the specified {@code content} or {@code trailers} are * non-empty when the content is always empty */ public static ResponseHeaders setOrRemoveContentLength(ResponseHeaders headers, HttpData content, HttpHeaders trailers) { requireNonNull(headers, "headers"); requireNonNull(content, "content"); requireNonNull(trailers, "trailers"); final HttpStatus status = headers.status(); if (isContentAlwaysEmptyWithValidation(status, content, trailers)) { if (status != HttpStatus.NOT_MODIFIED) { if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) { final ResponseHeadersBuilder builder = headers.toBuilder(); builder.remove(HttpHeaderNames.CONTENT_LENGTH); return builder.build(); } } else { // 304 response can have the "content-length" header when it is a response to a conditional // GET request. See https://tools.ietf.org/html/rfc7230#section-3.3.2 } return headers; } if (!trailers.isEmpty()) { // Some of the client implementations such as "curl" ignores trailers if // the "content-length" header is present. We should not set "content-length" header when // trailers exists so that those clients can receive the trailers. // The response is sent using chunked transfer encoding in HTTP/1 or a DATA frame payload // in HTTP/2, so it's no worry. if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) { final ResponseHeadersBuilder builder = headers.toBuilder(); builder.remove(HttpHeaderNames.CONTENT_LENGTH); return builder.build(); } return headers; } if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH) || !content.isEmpty()) { return headers.toBuilder() .setInt(HttpHeaderNames.CONTENT_LENGTH, content.length()) .build(); } // The header contains "content-length" header and the content is empty. // Do not overwrite the header because a response to a HEAD request // will have no content even if it has non-zero content-length header. return headers; } private static String convertHeaderValue(AsciiString name, CharSequence value) { if (!(value instanceof AsciiString)) { return value.toString(); } if (HEADER_VALUE_CACHE != null && CACHED_HEADERS.contains(name)) { final String converted = HEADER_VALUE_CACHE.get((AsciiString) value); assert converted != null; // loader does not return null. return converted; } return value.toString(); } /** * Returns {@code true} if the specified header name is not allowed for HTTP tailers. */ public static boolean isTrailerBlacklisted(AsciiString name) { return HTTP_TRAILER_BLACKLIST.contains(name); } private static final class CharSequenceMap extends DefaultHeaders<AsciiString, AsciiString, CharSequenceMap> { CharSequenceMap() { super(HTTP2_HEADER_NAME_HASHER, UnsupportedValueConverter.instance()); } @SuppressWarnings("unchecked") CharSequenceMap(int size) { super(HTTP2_HEADER_NAME_HASHER, UnsupportedValueConverter.instance(), NameValidator.NOT_NULL, size); } } private ArmeriaHttpUtil() {}}
 
 
data/java/javacvefixed120.txt DELETED
@@ -1 +0,0 @@
1
- /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */package org.apache.cxf.transport.https;import java.io.IOException;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.net.HttpURLConnection;import java.net.Proxy;import java.net.URL;import java.security.GeneralSecurityException;import java.util.logging.Handler;import java.util.logging.Logger;import javax.net.ssl.HostnameVerifier;import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSocketFactory;import org.apache.cxf.common.logging.LogUtils;import org.apache.cxf.common.util.ReflectionInvokationHandler;import org.apache.cxf.common.util.ReflectionUtil;import org.apache.cxf.configuration.jsse.SSLUtils;import org.apache.cxf.configuration.jsse.TLSClientParameters;/** * This HttpsURLConnectionFactory implements the HttpURLConnectionFactory * for using the given SSL Policy to configure TLS connections for "https:" * URLs. */public class HttpsURLConnectionFactory { /** * This constant holds the URL Protocol Identifier for HTTPS */ public static final String HTTPS_URL_PROTOCOL_ID = "https"; private static final Logger LOG = LogUtils.getL7dLogger(HttpsURLConnectionFactory.class); private static boolean weblogicWarned; /** * Cache the last SSLContext to avoid recreation */ SSLSocketFactory socketFactory; int lastTlsHash; /** * This constructor initialized the factory with the configured TLS * Client Parameters for the HTTPConduit for which this factory is used. */ public HttpsURLConnectionFactory() { } /** * Create a HttpURLConnection, proxified if necessary. * * * @param proxy This parameter is non-null if connection should be proxied. * @param url The target URL. * * @return The HttpURLConnection for the given URL. * @throws IOException */ public HttpURLConnection createConnection(TLSClientParameters tlsClientParameters, Proxy proxy, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) (proxy != null ? url.openConnection(proxy) : url.openConnection()); if (HTTPS_URL_PROTOCOL_ID.equals(url.getProtocol())) { if (tlsClientParameters == null) { tlsClientParameters = new TLSClientParameters(); } try { decorateWithTLS(tlsClientParameters, connection); } catch (Throwable ex) { if (ex instanceof IOException) { throw (IOException) ex; } IOException ioException = new IOException("Error while initializing secure socket", ex); throw ioException; } } return connection; } /** * This method assigns the various TLS parameters on the HttpsURLConnection * from the TLS Client Parameters. Connection parameter is of supertype HttpURLConnection, * which allows internal cast to potentially divergent subtype (https) implementations. */ protected synchronized void decorateWithTLS(TLSClientParameters tlsClientParameters, HttpURLConnection connection) throws GeneralSecurityException { int hash = tlsClientParameters.hashCode(); if (hash != lastTlsHash) { lastTlsHash = hash; socketFactory = null; } // always reload socketFactory from HttpsURLConnection.defaultSSLSocketFactory and // tlsClientParameters.sslSocketFactory to allow runtime configuration change if (tlsClientParameters.isUseHttpsURLConnectionDefaultSslSocketFactory()) { socketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); } else if (tlsClientParameters.getSSLSocketFactory() != null) { // see if an SSLSocketFactory was set. This allows easy interop // with not-yet-commons-ssl.jar, or even just people who like doing their // own JSSE. socketFactory = tlsClientParameters.getSSLSocketFactory(); } else if (socketFactory == null) { // ssl socket factory not yet instantiated, create a new one with tlsClientParameters's Trust // Managers, Key Managers, etc SSLContext ctx = org.apache.cxf.transport.https.SSLUtils.getSSLContext(tlsClientParameters); String[] cipherSuites = SSLUtils.getCiphersuitesToInclude(tlsClientParameters.getCipherSuites(), tlsClientParameters.getCipherSuitesFilter(), ctx.getSocketFactory().getDefaultCipherSuites(), SSLUtils.getSupportedCipherSuites(ctx), LOG); // The SSLSocketFactoryWrapper enables certain cipher suites // from the policy. String protocol = tlsClientParameters.getSecureSocketProtocol() != null ? tlsClientParameters .getSecureSocketProtocol() : "TLS"; socketFactory = new SSLSocketFactoryWrapper(ctx.getSocketFactory(), cipherSuites, protocol); //recalc the hashcode since some of the above MAY have changed the tlsClientParameters lastTlsHash = tlsClientParameters.hashCode(); } else { // ssl socket factory already initialized, reuse it to benefit of keep alive } HostnameVerifier verifier = org.apache.cxf.transport.https.SSLUtils .getHostnameVerifier(tlsClientParameters); if (connection instanceof HttpsURLConnection) { // handle the expected case (javax.net.ssl) HttpsURLConnection conn = (HttpsURLConnection) connection; conn.setHostnameVerifier(verifier); conn.setSSLSocketFactory(socketFactory); } else { // handle the deprecated sun case and other possible hidden API's // that are similar to the Sun cases try { Method method = connection.getClass().getMethod("getHostnameVerifier"); InvocationHandler handler = new ReflectionInvokationHandler(verifier) { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { return super.invoke(proxy, method, args); } catch (Exception ex) { // BUG: CWE-755 Improper Handling of Exceptional Conditions // return true; // FIXED: return false; } } }; Object proxy = java.lang.reflect.Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {method.getReturnType()}, handler); method = connection.getClass().getMethod("setHostnameVerifier", method.getReturnType()); method.invoke(connection, proxy); } catch (Exception ex) { //Ignore this one } try { Method getSSLSocketFactory = connection.getClass().getMethod("getSSLSocketFactory"); Method setSSLSocketFactory = connection.getClass() .getMethod("setSSLSocketFactory", getSSLSocketFactory.getReturnType()); if (getSSLSocketFactory.getReturnType().isInstance(socketFactory)) { setSSLSocketFactory.invoke(connection, socketFactory); } else { //need to see if we can create one - mostly the weblogic case. The //weblogic SSLSocketFactory has a protected constructor that can take //a JSSE SSLSocketFactory so we'll try and use that Constructor<?> c = getSSLSocketFactory.getReturnType() .getDeclaredConstructor(SSLSocketFactory.class); ReflectionUtil.setAccessible(c); setSSLSocketFactory.invoke(connection, c.newInstance(socketFactory)); } } catch (Exception ex) { if (connection.getClass().getName().contains("weblogic")) { if (!weblogicWarned) { weblogicWarned = true; LOG.warning("Could not configure SSLSocketFactory on Weblogic. " + " Use the Weblogic control panel to configure the SSL settings."); } return; } //if we cannot set the SSLSocketFactory, we're in serious trouble. throw new IllegalArgumentException("Error decorating connection class " + connection.getClass().getName(), ex); } } } /* * For development and testing only */ protected void addLogHandler(Handler handler) { LOG.addHandler(handler); }}
 
 
data/java/javacvefixed121.txt DELETED
@@ -1 +0,0 @@
1
- /** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License * at: * * http://opensource.org/licenses/ecl2.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * */package org.opencastproject.mediapackage.identifier;import javax.xml.bind.annotation.adapters.XmlAdapter;import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;/** * Interface for an identifier. */@XmlJavaTypeAdapter(Id.Adapter.class)public interface Id { /** * Returns the local identifier of this {@link Id}. The local identifier is defined to be free of separator characters * that could potentially get into the way when creating file or directory names from the identifier. * * For example, given that the interface is implemented by a class representing CNRI handles, the identifier would * then look something like <code>10.3930/ETHZ/abcd</code>, whith <code>10.3930</code> being the handle prefix, * <code>ETH</code> the authority and <code>abcd</code> the local part. <code>toURI()</code> would then return * <code>10.3930-ETH-abcd</code> or any other suitable form. * * @return a path separator-free representation of the identifier */ // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') // // FIXED: @Deprecated String compact(); class Adapter extends XmlAdapter<IdImpl, Id> { public IdImpl marshal(Id id) throws Exception { if (id instanceof IdImpl) { return (IdImpl) id; } else { throw new IllegalStateException("an unknown ID is un use: " + id); } } public Id unmarshal(IdImpl id) throws Exception { return id; } } /** * Return a string representation of the identifier from which an object of type Id should * be reconstructable. */ String toString();}
 
 
data/java/javacvefixed122.txt DELETED
@@ -1 +0,0 @@
1
- /* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2023, Arnaud Roques * * Project Info: http://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * http://plantuml.com/patreon (only 1$ per month!) * http://plantuml.com/paypal * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * * Original Author: Arnaud Roques * * */package net.sourceforge.plantuml.svek;import net.sourceforge.plantuml.awt.geom.Dimension2D;import net.sourceforge.plantuml.graphic.AbstractTextBlock;import net.sourceforge.plantuml.graphic.StringBounder;import net.sourceforge.plantuml.ugraphic.UGraphic;import net.sourceforge.plantuml.ugraphic.URectangle;import net.sourceforge.plantuml.ugraphic.UStroke;import net.sourceforge.plantuml.ugraphic.color.HColor;public final class InnerActivity extends AbstractTextBlock implements IEntityImage { private final IEntityImage im; private final HColor borderColor; private final double shadowing; private final HColor backColor; public InnerActivity(final IEntityImage im, HColor borderColor, HColor backColor, double shadowing) { this.im = im; this.backColor = backColor; this.borderColor = borderColor; this.shadowing = shadowing; } public final static double THICKNESS_BORDER = 1.5; public void drawU(UGraphic ug) { final Dimension2D total = calculateDimension(ug.getStringBounder()); ug = ug.apply(backColor.bg()).apply(borderColor).apply(new UStroke(THICKNESS_BORDER)); final URectangle rect = new URectangle(total.getWidth(), total.getHeight()).rounded(IEntityImage.CORNER); rect.setDeltaShadow(shadowing); ug.draw(rect); ug = ug.apply(new UStroke()); im.drawU(ug); } public HColor getBackcolor() { return im.getBackcolor(); } public Dimension2D calculateDimension(StringBounder stringBounder) { final Dimension2D img = im.calculateDimension(stringBounder); return img; } public ShapeType getShapeType() { return ShapeType.ROUND_RECTANGLE; } public Margins getShield(StringBounder stringBounder) { return Margins.NONE; } public boolean isHidden() { return im.isHidden(); } public double getOverscanX(StringBounder stringBounder) { return 0; }}
 
 
data/java/javacvefixed123.txt DELETED
@@ -1 +0,0 @@
1
- package io.onedev.server.model.support.inputspec;
2
 
 
 
0
 
data/java/javacvefixed124.txt DELETED
@@ -1 +0,0 @@
1
- package com.ruoyi.common.exception.file;
2
  * 文件上传 误异常类
3
  *
4
  * @author ruoyi
5
  */
6
  private static final long serialVersionUID = 1L;
7
  private String[] allowedExtension;
8
  private String extension;
9
  private String filename;
10
  public InvalidExtensionException(String[] allowedExtension, String extension, String filename)
11
  {
12
  // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
13
  // super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]");
14
  // FIXED:
15
  super("文件[" + filename + "]后缀[" + extension + "]不正确,请上传 [" + Arrays.toString(allowedExtension) + "]格式文件");
16
  this.allowedExtension = allowedExtension;
17
  this.extension = extension;
18
  this.filename = filename;
19
  }
20
  public String[] getAllowedExtension()
21
  {
22
  return allowedExtension;
23
  }
24
  public String getExtension()
25
  {
26
  return extension;
27
  }
28
  public String getFilename()
29
  {
30
  return filename;
31
  }
32
  public static class InvalidImageExtensionException extends InvalidExtensionException
33
  {
34
  private static final long serialVersionUID = 1L;
35
  public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename)
36
  {
37
  super(allowedExtension, extension, filename);
38
  }
39
  }
40
  public static class InvalidFlashExtensionException extends InvalidExtensionException
41
  {
42
  private static final long serialVersionUID = 1L;
43
  public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename)
44
  {
45
  super(allowedExtension, extension, filename);
46
  }
47
  }
48
  public static class InvalidMediaExtensionException extends InvalidExtensionException
49
  {
50
  private static final long serialVersionUID = 1L;
51
  public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename)
52
  {
53
  super(allowedExtension, extension, filename);
54
  }
55
  }
56
 
57
  public static class InvalidVideoExtensionException extends InvalidExtensionException
58
  {
59
  private static final long serialVersionUID = 1L;
60
  public InvalidVideoExtensionException(String[] allowedExtension, String extension, String filename)
61
  {
62
  super(allowedExtension, extension, filename);
63
  }
64
  }
 
 
0
  * 文件上传 误异常类
1
  *
2
  * @author ruoyi
3
  */
4
  private static final long serialVersionUID = 1L;
5
  private String[] allowedExtension;
6
  private String extension;
7
  private String filename;
8
  public InvalidExtensionException(String[] allowedExtension, String extension, String filename)
9
  {
10
  // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
11
  // super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]");
12
  // FIXED:
13
  super("文件[" + filename + "]后缀[" + extension + "]不正确,请上传 [" + Arrays.toString(allowedExtension) + "]格式文件");
14
  this.allowedExtension = allowedExtension;
15
  this.extension = extension;
16
  this.filename = filename;
17
  }
18
  public String[] getAllowedExtension()
19
  {
20
  return allowedExtension;
21
  }
22
  public String getExtension()
23
  {
24
  return extension;
25
  }
26
  public String getFilename()
27
  {
28
  return filename;
29
  }
30
  public static class InvalidImageExtensionException extends InvalidExtensionException
31
  {
32
  private static final long serialVersionUID = 1L;
33
  public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename)
34
  {
35
  super(allowedExtension, extension, filename);
36
  }
37
  }
38
  public static class InvalidFlashExtensionException extends InvalidExtensionException
39
  {
40
  private static final long serialVersionUID = 1L;
41
  public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename)
42
  {
43
  super(allowedExtension, extension, filename);
44
  }
45
  }
46
  public static class InvalidMediaExtensionException extends InvalidExtensionException
47
  {
48
  private static final long serialVersionUID = 1L;
49
  public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename)
50
  {
51
  super(allowedExtension, extension, filename);
52
  }
53
  }
54
 
55
  public static class InvalidVideoExtensionException extends InvalidExtensionException
56
  {
57
  private static final long serialVersionUID = 1L;
58
  public InvalidVideoExtensionException(String[] allowedExtension, String extension, String filename)
59
  {
60
  super(allowedExtension, extension, filename);
61
  }
62
  }
data/java/javacvefixed125.txt DELETED
@@ -1 +0,0 @@
1
- /* * The MIT License * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, Yahoo! Inc., * Manufacture Francaise des Pneumatiques Michelin, Romain Seguy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */package hudson.model;import hudson.Functions;import hudson.security.PermissionScope;import org.kohsuke.stapler.StaplerRequest;import java.io.IOException;import java.util.Collection;import hudson.search.SearchableModelObject;import hudson.security.Permission;import hudson.security.PermissionGroup;import hudson.security.AccessControlled;import hudson.util.Secret;/** * Basic configuration unit in Hudson. * * <p> * Every {@link Item} is hosted in an {@link ItemGroup} called "parent", * and some {@link Item}s are {@link ItemGroup}s. This form a tree * structure, which is rooted at {@link jenkins.model.Jenkins}. * * <p> * Unlike file systems, where a file can be moved from one directory * to another, {@link Item} inherently belongs to a single {@link ItemGroup} * and that relationship will not change. * Think of * <a href="http://images.google.com/images?q=Windows%20device%20manager">Windows device manager</a> * &mdash; an HDD always show up under 'Disk drives' and it can never be moved to another parent. * * Similarly, {@link ItemGroup} is not a generic container. Each subclass * of {@link ItemGroup} can usually only host a certain limited kinds of * {@link Item}s. * * <p> * {@link Item}s have unique {@link #getName() name}s that distinguish themselves * among their siblings uniquely. The names can be combined by '/' to form an * item full name, which uniquely identifies an {@link Item} inside the whole {@link jenkins.model.Jenkins}. * * @author Kohsuke Kawaguchi * @see Items * @see ItemVisitor */public interface Item extends PersistenceRoot, SearchableModelObject, AccessControlled { /** * Gets the parent that contains this item. */ ItemGroup<? extends Item> getParent(); /** * Gets all the jobs that this {@link Item} contains as descendants. */ Collection<? extends Job> getAllJobs(); /** * Gets the name of the item. * * <p> * The name must be unique among other {@link Item}s that belong * to the same parent. * * <p> * This name is also used for directory name, so it cannot contain * any character that's not allowed on the file system. * * @see #getFullName() */ String getName(); /** * Gets the full name of this item, like "abc/def/ghi". * * <p> * Full name consists of {@link #getName() name}s of {@link Item}s * that lead from the root {@link jenkins.model.Jenkins} to this {@link Item}, * separated by '/'. This is the unique name that identifies this * {@link Item} inside the whole {@link jenkins.model.Jenkins}. * * @see jenkins.model.Jenkins#getItemByFullName(String,Class) */ String getFullName(); /** * Gets the human readable short name of this item. * * <p> * This method should try to return a short concise human * readable string that describes this item. * The string need not be unique. * * <p> * The returned string should not include the display names * of {@link #getParent() ancestor items}. */ String getDisplayName(); /** * Works like {@link #getDisplayName()} but return * the full path that includes all the display names * of the ancestors. */ String getFullDisplayName(); /** * Gets the relative name to this item from the specified group. * * @since 1.419 * @return * String like "../foo/bar" */ String getRelativeNameFrom(ItemGroup g); /** * Short for {@code getRelativeNameFrom(item.getParent())} * * @since 1.419 */ String getRelativeNameFrom(Item item); /** * Returns the URL of this item relative to the context root of the application. * * @see AbstractItem#getUrl() for how to implement this. * * @return * URL that ends with '/'. */ String getUrl(); /** * Returns the URL of this item relative to the parent {@link ItemGroup}. * @see AbstractItem#getShortUrl() for how to implement this. * * @return * URL that ends with '/'. */ String getShortUrl(); /** * Returns the absolute URL of this item. This relies on the current * {@link StaplerRequest} to figure out what the host name is, * so can be used only during processing client requests. * * @return * absolute URL. * @throws IllegalStateException * if the method is invoked outside the HTTP request processing. * * @deprecated * This method shall <b>NEVER</b> be used during HTML page rendering, as it won't work with * network set up like Apache reverse proxy. * This method is only intended for the remote API clients who cannot resolve relative references * (even this won't work for the same reason, which should be fixed.) */ @Deprecated String getAbsoluteUrl(); /** * Called right after when a {@link Item} is loaded from disk. * This is an opportunity to do a post load processing. * * @param name * Name of the directory (not a path --- just the name portion) from * which the configuration was loaded. This usually becomes the * {@link #getName() name} of this item. */ void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException; /** * When a {@link Item} is copied from existing one, * the files are first copied on the file system, * then it will be loaded, then this method will be invoked * to perform any implementation-specific work. */ void onCopiedFrom(Item src); /** * When an item is created from scratch (instead of copied), * this method will be invoked. Used as the post-construction initialization. * * @since 1.374 */ void onCreatedFromScratch(); /** * Save the settings to a file. * * Use {@link Items#getConfigFile(Item)} * or {@link AbstractItem#getConfigFile()} to obtain the file * to save the data. */ void save() throws IOException; /** * Deletes this item. */ void delete() throws IOException, InterruptedException; PermissionGroup PERMISSIONS = new PermissionGroup(Item.class,Messages._Item_Permissions_Title()); Permission CREATE = new Permission(PERMISSIONS, "Create", Messages._Item_CREATE_description(), Permission.CREATE, PermissionScope.ITEM_GROUP); Permission DELETE = new Permission(PERMISSIONS, "Delete", Messages._Item_DELETE_description(), Permission.DELETE, PermissionScope.ITEM); Permission CONFIGURE = new Permission(PERMISSIONS, "Configure", Messages._Item_CONFIGURE_description(), Permission.CONFIGURE, PermissionScope.ITEM); Permission READ = new Permission(PERMISSIONS, "Read", Messages._Item_READ_description(), Permission.READ, PermissionScope.ITEM); Permission DISCOVER = new Permission(PERMISSIONS, "Discover", Messages._AbstractProject_DiscoverPermission_Description(), READ, PermissionScope.ITEM); /** * Ability to view configuration details. // BUG: CWE-326 Inadequate Encryption Strength // * If the user lacks {@link CONFIGURE} then any {@link Secret}s must be masked out, even in encrypted form. // FIXED: * If the user lacks {@link #CONFIGURE} then any {@link Secret}s must be masked out, even in encrypted form. * @see Secret#ENCRYPTED_VALUE_PATTERN */ Permission EXTENDED_READ = new Permission(PERMISSIONS,"ExtendedRead", Messages._AbstractProject_ExtendedReadPermission_Description(), CONFIGURE, Boolean.getBoolean("hudson.security.ExtendedReadPermission"), new PermissionScope[]{PermissionScope.ITEM}); // TODO the following really belong in Job, not Item, but too late to move since the owner.name is encoded in the ID: Permission BUILD = new Permission(PERMISSIONS, "Build", Messages._AbstractProject_BuildPermission_Description(), Permission.UPDATE, PermissionScope.ITEM); Permission WORKSPACE = new Permission(PERMISSIONS, "Workspace", Messages._AbstractProject_WorkspacePermission_Description(), Permission.READ, PermissionScope.ITEM); Permission WIPEOUT = new Permission(PERMISSIONS, "WipeOut", Messages._AbstractProject_WipeOutPermission_Description(), null, Functions.isWipeOutPermissionEnabled(), new PermissionScope[]{PermissionScope.ITEM}); Permission CANCEL = new Permission(PERMISSIONS, "Cancel", Messages._AbstractProject_CancelPermission_Description(), BUILD, PermissionScope.ITEM);}
 
 
data/java/javacvefixed126.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java;import com.github.steveice10.mc.protocol.packet.ingame.server.ServerAdvancementTabPacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.session.cache.AdvancementsCache;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;/** * Indicates that the client should open a particular advancement tab */@Translator(packet = ServerAdvancementTabPacket.class)public class JavaAdvancementsTabTranslator extends PacketTranslator<ServerAdvancementTabPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(ServerAdvancementTabPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, ServerAdvancementTabPacket packet) { AdvancementsCache advancementsCache = session.getAdvancementsCache(); advancementsCache.setCurrentAdvancementCategoryId(packet.getTabId()); advancementsCache.buildAndShowListForm(); }}
 
 
data/java/javacvefixed127.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java;import com.github.steveice10.mc.protocol.data.game.advancement.Advancement;import com.github.steveice10.mc.protocol.packet.ingame.server.ServerAdvancementsPacket;import com.nukkitx.protocol.bedrock.packet.SetTitlePacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.network.translators.chat.MessageTranslator;import org.geysermc.connector.network.session.cache.AdvancementsCache;import org.geysermc.connector.utils.GeyserAdvancement;import org.geysermc.connector.utils.LocaleUtils;import java.util.Map;@Translator(packet = ServerAdvancementsPacket.class)public class JavaAdvancementsTranslator extends PacketTranslator<ServerAdvancementsPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(ServerAdvancementsPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, ServerAdvancementsPacket packet) { AdvancementsCache advancementsCache = session.getAdvancementsCache(); if (packet.isReset()) { advancementsCache.getStoredAdvancements().clear(); advancementsCache.getStoredAdvancementProgress().clear(); } // Removes removed advancements from player's stored advancements for (String removedAdvancement : packet.getRemovedAdvancements()) { advancementsCache.getStoredAdvancements().remove(removedAdvancement); } advancementsCache.getStoredAdvancementProgress().putAll(packet.getProgress()); sendToolbarAdvancementUpdates(session, packet); // Adds advancements to the player's stored advancements when advancements are sent for (Advancement advancement : packet.getAdvancements()) { if (advancement.getDisplayData() != null && !advancement.getDisplayData().isHidden()) { GeyserAdvancement geyserAdvancement = GeyserAdvancement.from(advancement); advancementsCache.getStoredAdvancements().put(advancement.getId(), geyserAdvancement); } else { advancementsCache.getStoredAdvancements().remove(advancement.getId()); } } } /** * Handle all advancements progress updates */ public void sendToolbarAdvancementUpdates(GeyserSession session, ServerAdvancementsPacket packet) { if (packet.isReset()) { // Advancements are being cleared, so they can't be granted return; } for (Map.Entry<String, Map<String, Long>> progress : packet.getProgress().entrySet()) { GeyserAdvancement advancement = session.getAdvancementsCache().getStoredAdvancements().get(progress.getKey()); if (advancement != null && advancement.getDisplayData() != null) { if (session.getAdvancementsCache().isEarned(advancement)) { // Java uses some pink color for toast challenge completes String color = advancement.getDisplayData().getFrameType() == Advancement.DisplayData.FrameType.CHALLENGE ? "§d" : "§a"; String advancementName = MessageTranslator.convertMessage(advancement.getDisplayData().getTitle(), session.getLocale()); // Send an action bar message stating they earned an achievement // Sent for instances where broadcasting advancements through chat are disabled SetTitlePacket titlePacket = new SetTitlePacket(); titlePacket.setText(color + "[" + LocaleUtils.getLocaleString("advancements.toast." + advancement.getDisplayData().getFrameType().toString().toLowerCase(), session.getLocale()) + "]§f " + advancementName); titlePacket.setType(SetTitlePacket.Type.ACTIONBAR); titlePacket.setFadeOutTime(3); titlePacket.setFadeInTime(3); titlePacket.setStayTime(3); titlePacket.setXuid(""); titlePacket.setPlatformOnlineId(""); session.sendUpstreamPacket(titlePacket); } } } }}
 
 
data/java/javacvefixed128.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java.world;import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerBlockBreakAnimPacket;import com.github.steveice10.opennbt.tag.builtin.CompoundTag;import com.nukkitx.math.vector.Vector3f;import com.nukkitx.protocol.bedrock.data.LevelEventType;import com.nukkitx.protocol.bedrock.packet.LevelEventPacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.registry.BlockRegistries;import org.geysermc.connector.registry.type.ItemMapping;import org.geysermc.connector.utils.BlockUtils;@Translator(packet = ServerBlockBreakAnimPacket.class)public class JavaBlockBreakAnimTranslator extends PacketTranslator<ServerBlockBreakAnimPacket> { @Override public void translate(GeyserSession session, ServerBlockBreakAnimPacket packet) { int state = session.getConnector().getWorldManager().getBlockAt(session, packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()); int breakTime = (int) (65535 / Math.ceil(BlockUtils.getBreakTime(session, BlockRegistries.JAVA_BLOCKS.get(state), ItemMapping.AIR, new CompoundTag(""), false) * 20)); LevelEventPacket levelEventPacket = new LevelEventPacket(); levelEventPacket.setPosition(Vector3f.from( packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ() )); levelEventPacket.setType(LevelEventType.BLOCK_START_BREAK); switch (packet.getStage()) { case STAGE_1: levelEventPacket.setData(breakTime); break; case STAGE_2: levelEventPacket.setData(breakTime * 2); break; case STAGE_3: levelEventPacket.setData(breakTime * 3); break; case STAGE_4: levelEventPacket.setData(breakTime * 4); break; case STAGE_5: levelEventPacket.setData(breakTime * 5); break; case STAGE_6: levelEventPacket.setData(breakTime * 6); break; case STAGE_7: levelEventPacket.setData(breakTime * 7); break; case STAGE_8: levelEventPacket.setData(breakTime * 8); break; case STAGE_9: levelEventPacket.setData(breakTime * 9); break; case STAGE_10: levelEventPacket.setData(breakTime * 10); break; case RESET: levelEventPacket.setType(LevelEventType.BLOCK_STOP_BREAK); levelEventPacket.setData(0); break; } session.sendUpstreamPacket(levelEventPacket); }}
 
 
data/java/javacvefixed129.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java.world;import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerBlockChangePacket;import com.nukkitx.math.vector.Vector3i;import com.nukkitx.protocol.bedrock.data.SoundEvent;import com.nukkitx.protocol.bedrock.packet.LevelSoundEventPacket;import org.geysermc.common.PlatformType;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.network.translators.sound.BlockSoundInteractionHandler;import org.geysermc.connector.registry.BlockRegistries;import org.geysermc.connector.utils.ChunkUtils;@Translator(packet = ServerBlockChangePacket.class)public class JavaBlockChangeTranslator extends PacketTranslator<ServerBlockChangePacket> { @Override public void translate(GeyserSession session, ServerBlockChangePacket packet) { Position pos = packet.getRecord().getPosition(); boolean updatePlacement = session.getConnector().getPlatformType() != PlatformType.SPIGOT && // Spigot simply listens for the block place event session.getConnector().getWorldManager().getBlockAt(session, pos) != packet.getRecord().getBlock(); ChunkUtils.updateBlock(session, packet.getRecord().getBlock(), pos); if (updatePlacement) { this.checkPlace(session, packet); } this.checkInteract(session, packet); } private boolean checkPlace(GeyserSession session, ServerBlockChangePacket packet) { Vector3i lastPlacePos = session.getLastBlockPlacePosition(); if (lastPlacePos == null) { return false; } if ((lastPlacePos.getX() != packet.getRecord().getPosition().getX() || lastPlacePos.getY() != packet.getRecord().getPosition().getY() || lastPlacePos.getZ() != packet.getRecord().getPosition().getZ())) { return false; } // We need to check if the identifier is the same, else a packet with the sound of what the // player has in their hand is played, despite if the block is being placed or not boolean contains = false; String identifier = BlockRegistries.JAVA_BLOCKS.get(packet.getRecord().getBlock()).getItemIdentifier(); if (identifier.equals(session.getLastBlockPlacedId())) { contains = true; } if (!contains) { session.setLastBlockPlacePosition(null); session.setLastBlockPlacedId(null); return false; } // This is not sent from the server, so we need to send it this way LevelSoundEventPacket placeBlockSoundPacket = new LevelSoundEventPacket(); placeBlockSoundPacket.setSound(SoundEvent.PLACE); placeBlockSoundPacket.setPosition(lastPlacePos.toFloat()); placeBlockSoundPacket.setBabySound(false); placeBlockSoundPacket.setExtraData(session.getBlockMappings().getBedrockBlockId(packet.getRecord().getBlock())); placeBlockSoundPacket.setIdentifier(":"); session.sendUpstreamPacket(placeBlockSoundPacket); session.setLastBlockPlacePosition(null); session.setLastBlockPlacedId(null); return true; } private void checkInteract(GeyserSession session, ServerBlockChangePacket packet) { Vector3i lastInteractPos = session.getLastInteractionBlockPosition(); if (lastInteractPos == null || !session.isInteracting()) { return; } if ((lastInteractPos.getX() != packet.getRecord().getPosition().getX() || lastInteractPos.getY() != packet.getRecord().getPosition().getY() || lastInteractPos.getZ() != packet.getRecord().getPosition().getZ())) { return; } String identifier = BlockRegistries.JAVA_IDENTIFIERS.get().get(packet.getRecord().getBlock()); session.setInteracting(false); BlockSoundInteractionHandler.handleBlockInteraction(session, lastInteractPos.toFloat(), identifier); }}
 
 
data/java/javacvefixed13.txt DELETED
@@ -1 +0,0 @@
1
- /* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Matthew R. Harrah * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */package hudson.security;import java.util.Properties;import java.util.logging.Logger;import java.util.logging.Level;import java.io.IOException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import hudson.Util;import org.acegisecurity.Authentication;import org.acegisecurity.AuthenticationException;import org.acegisecurity.ui.webapp.AuthenticationProcessingFilter;/** * {@link AuthenticationProcessingFilter} with a change for Jenkins so that * we can pick up the hidden "from" form field defined in <tt>login.jelly</tt> * to send the user back to where he came from, after a successful authentication. * * @author Kohsuke Kawaguchi */public class AuthenticationProcessingFilter2 extends AuthenticationProcessingFilter { @Override protected String determineTargetUrl(HttpServletRequest request) { String targetUrl = request.getParameter("from"); request.getSession().setAttribute("from", targetUrl); if (targetUrl == null) return getDefaultTargetUrl(); if (Util.isAbsoluteUri(targetUrl)) return "."; // avoid open redirect // URL returned from determineTargetUrl() is resolved against the context path, // whereas the "from" URL is resolved against the top of the website, so adjust this. if(targetUrl.startsWith(request.getContextPath())) return targetUrl.substring(request.getContextPath().length()); // not sure when this happens, but apparently this happens in some case. // see #1274 return targetUrl; } /** * @see org.acegisecurity.ui.AbstractProcessingFilter#determineFailureUrl(javax.servlet.http.HttpServletRequest, org.acegisecurity.AuthenticationException) */ @Override protected String determineFailureUrl(HttpServletRequest request, AuthenticationException failed) { Properties excMap = getExceptionMappings(); String failedClassName = failed.getClass().getName(); String whereFrom = request.getParameter("from"); request.getSession().setAttribute("from", whereFrom); return excMap.getProperty(failedClassName, getAuthenticationFailureUrl()); } @Override protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException { super.onSuccessfulAuthentication(request,response,authResult); // make sure we have a session to store this successful authentication, given that we no longer // let HttpSessionContextIntegrationFilter2 to create sessions. // HttpSessionContextIntegrationFilter stores the updated SecurityContext object into this session later // (either when a redirect is issued, via its HttpResponseWrapper, or when the execution returns to its // doFilter method. // BUG: CWE-287 Improper Authentication // // FIXED: request.getSession().invalidate(); request.getSession(); } /** * Leave the information about login failure. * * <p> * Otherwise it seems like Acegi doesn't really leave the detail of the failure anywhere. */ @Override protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException { super.onUnsuccessfulAuthentication(request, response, failed); LOGGER.log(Level.INFO, "Login attempt failed", failed); } private static final Logger LOGGER = Logger.getLogger(AuthenticationProcessingFilter2.class.getName());}
 
 
data/java/javacvefixed130.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java.world;import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;import com.github.steveice10.mc.protocol.data.game.world.block.value.*;import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerBlockValuePacket;import com.nukkitx.math.vector.Vector3i;import com.nukkitx.nbt.NbtMap;import com.nukkitx.nbt.NbtMapBuilder;import com.nukkitx.protocol.bedrock.packet.BlockEntityDataPacket;import com.nukkitx.protocol.bedrock.packet.BlockEventPacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.network.translators.world.block.BlockStateValues;import org.geysermc.connector.network.translators.world.block.entity.NoteblockBlockEntityTranslator;import java.util.concurrent.TimeUnit;@Translator(packet = ServerBlockValuePacket.class)public class JavaBlockValueTranslator extends PacketTranslator<ServerBlockValuePacket> { @Override public void translate(GeyserSession session, ServerBlockValuePacket packet) { BlockEventPacket blockEventPacket = new BlockEventPacket(); blockEventPacket.setBlockPosition(Vector3i.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ())); if (packet.getValue() instanceof ChestValue) { ChestValue value = (ChestValue) packet.getValue() ; blockEventPacket.setEventType(1); blockEventPacket.setEventData(value.getViewers() > 0 ? 1 : 0); session.sendUpstreamPacket(blockEventPacket); } else if (packet.getValue() instanceof EndGatewayValue) { blockEventPacket.setEventType(1); session.sendUpstreamPacket(blockEventPacket); } else if (packet.getValue() instanceof NoteBlockValue) { NoteblockBlockEntityTranslator.translate(session, packet.getPosition()); } else if (packet.getValue() instanceof PistonValue) { PistonValueType type = (PistonValueType) packet.getType(); // Unlike everything else, pistons need a block entity packet to convey motion // TODO: Doesn't register on chunk load; needs to be interacted with first Vector3i position = Vector3i.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()); if (type == PistonValueType.PUSHING) { extendPiston(session, position, 0.0f, 0.0f); } else { retractPiston(session, position, 1.0f, 1.0f); } } else if (packet.getValue() instanceof MobSpawnerValue) { blockEventPacket.setEventType(1); session.sendUpstreamPacket(blockEventPacket); } else if (packet.getValue() instanceof EndGatewayValue) { blockEventPacket.setEventType(1); session.sendUpstreamPacket(blockEventPacket); } else if (packet.getValue() instanceof GenericBlockValue && packet.getBlockId() == BlockStateValues.JAVA_BELL_ID) { // Bells - needed to show ring from other players GenericBlockValue bellValue = (GenericBlockValue) packet.getValue(); Position position = packet.getPosition(); BlockEntityDataPacket blockEntityPacket = new BlockEntityDataPacket(); blockEntityPacket.setBlockPosition(Vector3i.from(position.getX(), position.getY(), position.getZ())); NbtMapBuilder builder = NbtMap.builder(); builder.putInt("x", position.getX()); builder.putInt("y", position.getY()); builder.putInt("z", position.getZ()); builder.putString("id", "Bell"); int bedrockRingDirection; switch (bellValue.getValue()) { case 3: // north bedrockRingDirection = 0; break; case 4: // east bedrockRingDirection = 1; break; case 5: // west bedrockRingDirection = 3; break; default: // south (2) is identical bedrockRingDirection = bellValue.getValue(); } builder.putInt("Direction", bedrockRingDirection); builder.putByte("Ringing", (byte) 1); builder.putInt("Ticks", 0); blockEntityPacket.setData(builder.build()); session.sendUpstreamPacket(blockEntityPacket); } } /** * Emulating a piston extending * @param session GeyserSession * @param position Block position * @param progress How far the piston is * @param lastProgress How far the piston last was */ private void extendPiston(GeyserSession session, Vector3i position, float progress, float lastProgress) { BlockEntityDataPacket blockEntityDataPacket = new BlockEntityDataPacket(); blockEntityDataPacket.setBlockPosition(position); byte state = (byte) ((progress == 1.0f && lastProgress == 1.0f) ? 2 : 1); blockEntityDataPacket.setData(buildPistonTag(position, progress, lastProgress, state)); session.sendUpstreamPacket(blockEntityDataPacket); if (lastProgress != 1.0f) { session.getConnector().getGeneralThreadPool().schedule(() -> extendPiston(session, position, (progress >= 1.0f) ? 1.0f : progress + 0.5f, progress), 20, TimeUnit.MILLISECONDS); } } /** * Emulate a piston retracting. * @param session GeyserSession * @param position Block position * @param progress Current progress of piston * @param lastProgress Last progress of piston */ private void retractPiston(GeyserSession session, Vector3i position, float progress, float lastProgress) { BlockEntityDataPacket blockEntityDataPacket = new BlockEntityDataPacket(); blockEntityDataPacket.setBlockPosition(position); byte state = (byte) ((progress == 0.0f && lastProgress == 0.0f) ? 0 : 3); blockEntityDataPacket.setData(buildPistonTag(position, progress, lastProgress, state)); session.sendUpstreamPacket(blockEntityDataPacket); if (lastProgress != 0.0f) { session.getConnector().getGeneralThreadPool().schedule(() -> retractPiston(session, position, (progress <= 0.0f) ? 0.0f : progress - 0.5f, progress), 20, TimeUnit.MILLISECONDS); } } /** * Build a piston tag * @param position Piston position * @param progress Current progress of piston * @param lastProgress Last progress of piston * @param state * @return Bedrock CompoundTag of piston */ private NbtMap buildPistonTag(Vector3i position, float progress, float lastProgress, byte state) { NbtMapBuilder builder = NbtMap.builder() .putInt("x", position.getX()) .putInt("y", position.getY()) .putInt("z", position.getZ()) .putFloat("Progress", progress) .putFloat("LastProgress", lastProgress) .putString("id", "PistonArm") .putByte("NewState", state) .putByte("State", state); return builder.build(); }}
 
 
data/java/javacvefixed131.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.session.cache.BossBar;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import com.github.steveice10.mc.protocol.packet.ingame.server.ServerBossBarPacket;@Translator(packet = ServerBossBarPacket.class)public class JavaBossBarTranslator extends PacketTranslator<ServerBossBarPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(ServerBossBarPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, ServerBossBarPacket packet) { BossBar bossBar = session.getEntityCache().getBossBar(packet.getUuid()); switch (packet.getAction()) { case ADD: long entityId = session.getEntityCache().getNextEntityId().incrementAndGet(); bossBar = new BossBar(session, entityId, packet.getTitle(), packet.getHealth(), 0, 1, 0); session.getEntityCache().addBossBar(packet.getUuid(), bossBar); break; case UPDATE_TITLE: if (bossBar != null) bossBar.updateTitle(packet.getTitle()); break; case UPDATE_HEALTH: if (bossBar != null) bossBar.updateHealth(packet.getHealth()); break; case REMOVE: session.getEntityCache().removeBossBar(packet.getUuid()); break; case UPDATE_STYLE: case UPDATE_FLAGS: //todo } }}
 
 
data/java/javacvefixed132.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java;import com.github.steveice10.mc.protocol.packet.ingame.server.ServerChatPacket;import com.nukkitx.protocol.bedrock.packet.TextPacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.network.translators.chat.MessageTranslator;@Translator(packet = ServerChatPacket.class)public class JavaChatTranslator extends PacketTranslator<ServerChatPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(ServerChatPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, ServerChatPacket packet) { TextPacket textPacket = new TextPacket(); textPacket.setPlatformChatId(""); textPacket.setSourceName(""); textPacket.setXuid(session.getAuthData().getXboxUUID()); switch (packet.getType()) { case CHAT: textPacket.setType(TextPacket.Type.CHAT); break; case SYSTEM: textPacket.setType(TextPacket.Type.SYSTEM); break; case NOTIFICATION: textPacket.setType(TextPacket.Type.TIP); break; default: textPacket.setType(TextPacket.Type.RAW); break; } textPacket.setNeedsTranslation(false); textPacket.setMessage(MessageTranslator.convertMessage(packet.getMessage(), session.getLocale())); session.sendUpstreamPacket(textPacket); }}
 
 
data/java/javacvefixed133.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java.world;import com.github.steveice10.mc.protocol.data.game.chunk.Column;import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerChunkDataPacket;import com.nukkitx.nbt.NBTOutputStream;import com.nukkitx.nbt.NbtMap;import com.nukkitx.nbt.NbtUtils;import com.nukkitx.network.VarInts;import com.nukkitx.protocol.bedrock.packet.LevelChunkPacket;import io.netty.buffer.ByteBuf;import io.netty.buffer.ByteBufAllocator;import io.netty.buffer.ByteBufOutputStream;import org.geysermc.connector.GeyserConnector;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.network.translators.world.chunk.ChunkSection;import org.geysermc.connector.network.translators.world.BiomeTranslator;import org.geysermc.connector.utils.ChunkUtils;import static org.geysermc.connector.utils.ChunkUtils.MINIMUM_ACCEPTED_HEIGHT;import static org.geysermc.connector.utils.ChunkUtils.MINIMUM_ACCEPTED_HEIGHT_OVERWORLD;@Translator(packet = ServerChunkDataPacket.class)public class JavaChunkDataTranslator extends PacketTranslator<ServerChunkDataPacket> { // Caves and cliffs supports 3D biomes by implementing a very similar palette system to blocks private static final boolean NEW_BIOME_WRITE = GeyserConnector.getInstance().getConfig().isExtendedWorldHeight(); @Override public void translate(GeyserSession session, ServerChunkDataPacket packet) { if (session.isSpawned()) { ChunkUtils.updateChunkPosition(session, session.getPlayerEntity().getPosition().toInt()); } session.getChunkCache().addToCache(packet.getColumn()); Column column = packet.getColumn(); // Ensure that, if the player is using lower world heights, the position is not offset int yOffset = session.getChunkCache().getChunkMinY(); GeyserConnector.getInstance().getGeneralThreadPool().execute(() -> { try { if (session.isClosed()) { return; } ChunkUtils.ChunkData chunkData = ChunkUtils.translateToBedrock(session, column, yOffset); ChunkSection[] sections = chunkData.getSections(); // Find highest section int sectionCount = sections.length - 1; while (sectionCount >= 0 && sections[sectionCount] == null) { sectionCount--; } sectionCount++; // Estimate chunk size int size = 0; for (int i = 0; i < sectionCount; i++) { ChunkSection section = sections[i]; size += (section != null ? section : session.getBlockMappings().getEmptyChunkSection()).estimateNetworkSize(); } if (NEW_BIOME_WRITE) { size += ChunkUtils.EMPTY_CHUNK_DATA.length; // Consists only of biome data } else { size += 256; // Biomes pre-1.18 } size += 1; // Border blocks size += 1; // Extra data length (always 0) size += chunkData.getBlockEntities().length * 64; // Conservative estimate of 64 bytes per tile entity // Allocate output buffer ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(size); byte[] payload; try { for (int i = 0; i < sectionCount; i++) { ChunkSection section = sections[i]; (section != null ? section : session.getBlockMappings().getEmptyChunkSection()).writeToNetwork(byteBuf); } if (NEW_BIOME_WRITE) { // At this point we're dealing with Bedrock chunk sections boolean overworld = session.getChunkCache().isExtendedHeight(); int dimensionOffset = (overworld ? MINIMUM_ACCEPTED_HEIGHT_OVERWORLD : MINIMUM_ACCEPTED_HEIGHT) >> 4; for (int i = 0; i < sectionCount; i++) { int biomeYOffset = dimensionOffset + i; if (biomeYOffset < yOffset) { // Ignore this biome section since it goes below the height of the Java world byteBuf.writeBytes(ChunkUtils.EMPTY_BIOME_DATA); continue; } BiomeTranslator.toNewBedrockBiome(session, column.getBiomeData(), i + (dimensionOffset - yOffset)).writeToNetwork(byteBuf); } // As of 1.17.10, Bedrock hardcodes to always read 32 biome sections int remainingEmptyBiomes = 32 - sectionCount; for (int i = 0; i < remainingEmptyBiomes; i++) { byteBuf.writeBytes(ChunkUtils.EMPTY_BIOME_DATA); } } else { byteBuf.writeBytes(BiomeTranslator.toBedrockBiome(session, column.getBiomeData())); // Biomes - 256 bytes } byteBuf.writeByte(0); // Border blocks - Edu edition only VarInts.writeUnsignedInt(byteBuf, 0); // extra data length, 0 for now // Encode tile entities into buffer NBTOutputStream nbtStream = NbtUtils.createNetworkWriter(new ByteBufOutputStream(byteBuf)); for (NbtMap blockEntity : chunkData.getBlockEntities()) { nbtStream.writeTag(blockEntity); } // Copy data into byte[], because the protocol lib really likes things that are s l o w byteBuf.readBytes(payload = new byte[byteBuf.readableBytes()]); } finally { byteBuf.release(); // Release buffer to allow buffer pooling to be useful } LevelChunkPacket levelChunkPacket = new LevelChunkPacket(); levelChunkPacket.setSubChunksLength(sectionCount); levelChunkPacket.setCachingEnabled(false); levelChunkPacket.setChunkX(column.getX()); levelChunkPacket.setChunkZ(column.getZ()); levelChunkPacket.setData(payload); session.sendUpstreamPacket(levelChunkPacket); } catch (Exception ex) { ex.printStackTrace(); } }); }}
 
 
data/java/javacvefixed134.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java.title;import com.github.steveice10.mc.protocol.packet.ingame.server.title.ServerClearTitlesPacket;import com.nukkitx.protocol.bedrock.packet.SetTitlePacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;@Translator(packet = ServerClearTitlesPacket.class)public class JavaClearTitlesTranslator extends PacketTranslator<ServerClearTitlesPacket> { @Override public void translate(GeyserSession session, ServerClearTitlesPacket packet) { SetTitlePacket titlePacket = new SetTitlePacket(); // TODO handle packet.isResetTimes() titlePacket.setType(SetTitlePacket.Type.CLEAR); titlePacket.setText(""); titlePacket.setXuid(""); titlePacket.setPlatformOnlineId(""); session.sendUpstreamPacket(titlePacket); }}
 
 
data/java/javacvefixed135.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java.window;import com.github.steveice10.mc.protocol.packet.ingame.server.window.ServerCloseWindowPacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.utils.InventoryUtils;@Translator(packet = ServerCloseWindowPacket.class)public class JavaCloseWindowTranslator extends PacketTranslator<ServerCloseWindowPacket> { @Override public void translate(GeyserSession session, ServerCloseWindowPacket packet) { // Sometimes the server can request a window close of ID 0... when the window isn't even open // Don't confirm in this instance InventoryUtils.closeInventory(session, packet.getWindowId(), (session.getOpenInventory() != null && session.getOpenInventory().getId() == packet.getWindowId())); }}
 
 
data/java/javacvefixed136.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java;import com.github.steveice10.mc.protocol.data.game.command.CommandNode;import com.github.steveice10.mc.protocol.data.game.command.CommandParser;import com.github.steveice10.mc.protocol.packet.ingame.server.ServerDeclareCommandsPacket;import com.nukkitx.protocol.bedrock.data.command.CommandData;import com.nukkitx.protocol.bedrock.data.command.CommandEnumData;import com.nukkitx.protocol.bedrock.data.command.CommandParam;import com.nukkitx.protocol.bedrock.data.command.CommandParamData;import com.nukkitx.protocol.bedrock.packet.AvailableCommandsPacket;import it.unimi.dsi.fastutil.Hash;import it.unimi.dsi.fastutil.ints.Int2ObjectMap;import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;import it.unimi.dsi.fastutil.ints.IntOpenHashSet;import it.unimi.dsi.fastutil.ints.IntSet;import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap;import lombok.Getter;import lombok.ToString;import net.kyori.adventure.text.format.NamedTextColor;import org.geysermc.connector.GeyserConnector;import org.geysermc.connector.entity.type.EntityType;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.network.translators.item.Enchantment;import org.geysermc.connector.registry.BlockRegistries;import java.util.*;@Translator(packet = ServerDeclareCommandsPacket.class)public class JavaDeclareCommandsTranslator extends PacketTranslator<ServerDeclareCommandsPacket> { private static final String[] ENUM_BOOLEAN = {"true", "false"}; private static final String[] VALID_COLORS; private static final String[] VALID_SCOREBOARD_SLOTS; private static final Hash.Strategy<CommandParamData[][]> PARAM_STRATEGY = new Hash.Strategy<CommandParamData[][]>() { @Override public int hashCode(CommandParamData[][] o) { return Arrays.deepHashCode(o); } @Override public boolean equals(CommandParamData[][] a, CommandParamData[][] b) { if (a == b) return true; if (a == null || b == null) return false; if (a.length != b.length) return false; for (int i = 0; i < a.length; i++) { CommandParamData[] a1 = a[i]; CommandParamData[] b1 = b[i]; if (a1.length != b1.length) return false; for (int j = 0; j < a1.length; j++) { if (!a1[j].equals(b1[j])) return false; } } return true; } }; static { List<String> validColors = new ArrayList<>(NamedTextColor.NAMES.keys()); validColors.add("reset"); VALID_COLORS = validColors.toArray(new String[0]); List<String> teamOptions = new ArrayList<>(Arrays.asList("list", "sidebar", "belowName")); for (String color : NamedTextColor.NAMES.keys()) { teamOptions.add("sidebar.team." + color); } VALID_SCOREBOARD_SLOTS = teamOptions.toArray(new String[0]); } @Override // BUG: CWE-287 Improper Authentication // public void translate(ServerDeclareCommandsPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, ServerDeclareCommandsPacket packet) { // Don't send command suggestions if they are disabled if (!session.getConnector().getConfig().isCommandSuggestions()) { session.getConnector().getLogger().debug("Not sending translated command suggestions as they are disabled."); // Send an empty packet so Bedrock doesn't override /help with its own, built-in help command. AvailableCommandsPacket emptyPacket = new AvailableCommandsPacket(); session.sendUpstreamPacket(emptyPacket); return; } CommandNode[] nodes = packet.getNodes(); List<CommandData> commandData = new ArrayList<>(); IntSet commandNodes = new IntOpenHashSet(); Set<String> knownAliases = new HashSet<>(); Map<CommandParamData[][], Set<String>> commands = new Object2ObjectOpenCustomHashMap<>(PARAM_STRATEGY); Int2ObjectMap<List<CommandNode>> commandArgs = new Int2ObjectOpenHashMap<>(); // Get the first node, it should be a root node CommandNode rootNode = nodes[packet.getFirstNodeIndex()]; // Loop through the root nodes to get all commands for (int nodeIndex : rootNode.getChildIndices()) { CommandNode node = nodes[nodeIndex]; // Make sure we don't have duplicated commands (happens if there is more than 1 root node) if (!commandNodes.add(nodeIndex) || !knownAliases.add(node.getName().toLowerCase())) continue; // Get and update the commandArgs list with the found arguments if (node.getChildIndices().length >= 1) { for (int childIndex : node.getChildIndices()) { commandArgs.computeIfAbsent(nodeIndex, ArrayList::new).add(nodes[childIndex]); } } // Get and parse all params CommandParamData[][] params = getParams(session, nodes[nodeIndex], nodes); // Insert the alias name into the command list commands.computeIfAbsent(params, index -> new HashSet<>()).add(node.getName().toLowerCase()); } // The command flags, not sure what these do apart from break things List<CommandData.Flag> flags = Collections.emptyList(); // Loop through all the found commands for (Map.Entry<CommandParamData[][], Set<String>> entry : commands.entrySet()) { String commandName = entry.getValue().iterator().next(); // We know this has a value // Create a basic alias CommandEnumData aliases = new CommandEnumData(commandName + "Aliases", entry.getValue().toArray(new String[0]), false); // Build the completed command and add it to the final list CommandData data = new CommandData(commandName, session.getConnector().getCommandManager().getDescription(commandName), flags, (byte) 0, aliases, entry.getKey()); commandData.add(data); } // Add our commands to the AvailableCommandsPacket for the bedrock client AvailableCommandsPacket availableCommandsPacket = new AvailableCommandsPacket(); availableCommandsPacket.getCommands().addAll(commandData); session.getConnector().getLogger().debug("Sending command packet of " + commandData.size() + " commands"); // Finally, send the commands to the client session.sendUpstreamPacket(availableCommandsPacket); } /** * Build the command parameter array for the given command * * @param session the session * @param commandNode The command to build the parameters for * @param allNodes Every command node * @return An array of parameter option arrays */ private static CommandParamData[][] getParams(GeyserSession session, CommandNode commandNode, CommandNode[] allNodes) { // Check if the command is an alias and redirect it if (commandNode.getRedirectIndex() != -1) { GeyserConnector.getInstance().getLogger().debug("Redirecting command " + commandNode.getName() + " to " + allNodes[commandNode.getRedirectIndex()].getName()); commandNode = allNodes[commandNode.getRedirectIndex()]; } if (commandNode.getChildIndices().length >= 1) { // Create the root param node and build all the children ParamInfo rootParam = new ParamInfo(commandNode, null); rootParam.buildChildren(session, allNodes); List<CommandParamData[]> treeData = rootParam.getTree(); return treeData.toArray(new CommandParamData[0][]); } return new CommandParamData[0][0]; } /** * Convert Java edition command types to Bedrock edition * * @param session the session * @param parser Command type to convert * @return Bedrock parameter data type */ private static Object mapCommandType(GeyserSession session, CommandParser parser) { if (parser == null) { return CommandParam.STRING; } switch (parser) { case FLOAT: case ROTATION: case DOUBLE: return CommandParam.FLOAT; case INTEGER: case LONG: return CommandParam.INT; case ENTITY: case GAME_PROFILE: return CommandParam.TARGET; case BLOCK_POS: return CommandParam.BLOCK_POSITION; case COLUMN_POS: case VEC3: return CommandParam.POSITION; case MESSAGE: return CommandParam.MESSAGE; case NBT: case NBT_COMPOUND_TAG: case NBT_TAG: case NBT_PATH: return CommandParam.JSON; case RESOURCE_LOCATION: case FUNCTION: return CommandParam.FILE_PATH; case BOOL: return ENUM_BOOLEAN; case OPERATION: // ">=", "==", etc return CommandParam.OPERATOR; case BLOCK_STATE: return BlockRegistries.JAVA_TO_BEDROCK_IDENTIFIERS.get().keySet().toArray(new String[0]); case ITEM_STACK: return session.getItemMappings().getItemNames(); case ITEM_ENCHANTMENT: return Enchantment.JavaEnchantment.ALL_JAVA_IDENTIFIERS; case ENTITY_SUMMON: return EntityType.ALL_JAVA_IDENTIFIERS; case COLOR: return VALID_COLORS; case SCOREBOARD_SLOT: return VALID_SCOREBOARD_SLOTS; default: return CommandParam.STRING; } } @Getter @ToString private static class ParamInfo { private final CommandNode paramNode; private final CommandParamData paramData; private final List<ParamInfo> children; /** * Create a new parameter info object * * @param paramNode CommandNode the parameter is for * @param paramData The existing parameters for the command */ public ParamInfo(CommandNode paramNode, CommandParamData paramData) { this.paramNode = paramNode; this.paramData = paramData; this.children = new ArrayList<>(); } /** * Build the array of all the child parameters (recursive) * * @param session the session * @param allNodes Every command node */ public void buildChildren(GeyserSession session, CommandNode[] allNodes) { for (int paramID : paramNode.getChildIndices()) { CommandNode paramNode = allNodes[paramID]; if (paramNode == this.paramNode) { // Fixes a StackOverflowError when an argument has itself as a child continue; } if (paramNode.getParser() == null) { boolean foundCompatible = false; for (int i = 0; i < children.size(); i++) { ParamInfo enumParamInfo = children.get(i); // Check to make sure all descending nodes of this command are compatible - otherwise, create a new overload if (isCompatible(allNodes, enumParamInfo.getParamNode(), paramNode)) { foundCompatible = true; // Extend the current list of enum values String[] enumOptions = Arrays.copyOf(enumParamInfo.getParamData().getEnumData().getValues(), enumParamInfo.getParamData().getEnumData().getValues().length + 1); enumOptions[enumOptions.length - 1] = paramNode.getName(); // Re-create the command using the updated values CommandEnumData enumData = new CommandEnumData(enumParamInfo.getParamData().getEnumData().getName(), enumOptions, false); children.set(i, new ParamInfo(enumParamInfo.getParamNode(), new CommandParamData(enumParamInfo.getParamData().getName(), this.paramNode.isExecutable(), enumData, null, null, Collections.emptyList()))); break; } } if (!foundCompatible) { // Create a new subcommand with this exact type CommandEnumData enumData = new CommandEnumData(paramNode.getName(), new String[]{paramNode.getName()}, false); // On setting optional: // isExecutable is defined as a node "constitutes a valid command." // Therefore, any children of the parameter must simply be optional. children.add(new ParamInfo(paramNode, new CommandParamData(paramNode.getName(), this.paramNode.isExecutable(), enumData, null, null, Collections.emptyList()))); } } else { // Put the non-enum param into the list Object mappedType = mapCommandType(session, paramNode.getParser()); CommandEnumData enumData = null; CommandParam type = null; if (mappedType instanceof String[]) { enumData = new CommandEnumData(paramNode.getParser().name().toLowerCase(), (String[]) mappedType, false); } else { type = (CommandParam) mappedType; } // IF enumData != null: // In game, this will show up like <paramNode.getName(): enumData.getName()> // So if paramNode.getName() == "value" and enumData.getName() == "bool": <value: bool> children.add(new ParamInfo(paramNode, new CommandParamData(paramNode.getName(), this.paramNode.isExecutable(), enumData, type, null, Collections.emptyList()))); } } // Recursively build all child options for (ParamInfo child : children) { child.buildChildren(session, allNodes); } } /** * Comparing CommandNode type a and b, determine if they are in the same overload. * <p> * Take the <code>gamerule</code> command, and let's present three "subcommands" you can perform: * * <ul> * <li><code>gamerule doDaylightCycle true</code></li> * <li><code>gamerule announceAdvancements false</code></li> * <li><code>gamerule randomTickSpeed 3</code></li> * </ul> * * While all three of them are indeed part of the same command, the command setting randomTickSpeed parses an int, * while the others use boolean. In Bedrock, this should be presented as a separate overload to indicate that this * does something a little different. * <p> * Therefore, this function will return <code>true</code> if the first two are compared, as they use the same * parsers. If the third is compared with either of the others, this function will return <code>false</code>. * <p> * Here's an example of how the above would be presented to Bedrock (as of 1.16.200). Notice how the top two <code>CommandParamData</code> * classes of each array are identical in type, but the following class is different: * <pre> * overloads=[ * [ * CommandParamData(name=doDaylightCycle, optional=false, enumData=CommandEnumData(name=announceAdvancements, values=[announceAdvancements, doDaylightCycle], isSoft=false), type=STRING, postfix=null, options=[]) * CommandParamData(name=value, optional=false, enumData=CommandEnumData(name=value, values=[true, false], isSoft=false), type=null, postfix=null, options=[]) * ] * [ * CommandParamData(name=randomTickSpeed, optional=false, enumData=CommandEnumData(name=randomTickSpeed, values=[randomTickSpeed], isSoft=false), type=STRING, postfix=null, options=[]) * CommandParamData(name=value, optional=false, enumData=null, type=INT, postfix=null, options=[]) * ] * ] * </pre> * * @return if these two can be merged into one overload. */ private boolean isCompatible(CommandNode[] allNodes, CommandNode a, CommandNode b) { if (a == b) return true; if (a.getParser() != b.getParser()) return false; if (a.getChildIndices().length != b.getChildIndices().length) return false; for (int i = 0; i < a.getChildIndices().length; i++) { boolean hasSimilarity = false; CommandNode a1 = allNodes[a.getChildIndices()[i]]; // Search "b" until we find a child that matches this one for (int j = 0; j < b.getChildIndices().length; j++) { if (isCompatible(allNodes, a1, allNodes[b.getChildIndices()[j]])) { hasSimilarity = true; break; } } if (!hasSimilarity) { return false; } } return true; } /** * Get the tree of every parameter node (recursive) * * @return List of parameter options arrays for the command */ public List<CommandParamData[]> getTree() { List<CommandParamData[]> treeParamData = new ArrayList<>(); for (ParamInfo child : children) { // Get the tree from the child List<CommandParamData[]> childTree = child.getTree(); // Un-pack the tree append the child node to it and push into the list for (CommandParamData[] subChild : childTree) { CommandParamData[] tmpTree = new CommandParamData[subChild.length + 1]; tmpTree[0] = child.getParamData(); System.arraycopy(subChild, 0, tmpTree, 1, subChild.length); treeParamData.add(tmpTree); } // If we have no more child parameters just the child if (childTree.size() == 0) { treeParamData.add(new CommandParamData[] { child.getParamData() }); } } return treeParamData; } }}
 
 
data/java/javacvefixed137.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java;import com.github.steveice10.mc.protocol.data.game.entity.metadata.ItemStack;import com.github.steveice10.mc.protocol.data.game.recipe.Ingredient;import com.github.steveice10.mc.protocol.data.game.recipe.Recipe;import com.github.steveice10.mc.protocol.data.game.recipe.RecipeType;import com.github.steveice10.mc.protocol.data.game.recipe.data.ShapedRecipeData;import com.github.steveice10.mc.protocol.data.game.recipe.data.ShapelessRecipeData;import com.github.steveice10.mc.protocol.data.game.recipe.data.StoneCuttingRecipeData;import com.github.steveice10.mc.protocol.packet.ingame.server.ServerDeclareRecipesPacket;import com.nukkitx.nbt.NbtMap;import com.nukkitx.protocol.bedrock.data.inventory.CraftingData;import com.nukkitx.protocol.bedrock.data.inventory.ItemData;import com.nukkitx.protocol.bedrock.packet.CraftingDataPacket;import it.unimi.dsi.fastutil.ints.*;import lombok.AllArgsConstructor;import lombok.EqualsAndHashCode;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.network.translators.item.ItemTranslator;import org.geysermc.connector.registry.Registries;import org.geysermc.connector.registry.type.ItemMapping;import org.geysermc.connector.utils.InventoryUtils;import java.util.*;import java.util.stream.Collectors;import static org.geysermc.connector.utils.InventoryUtils.LAST_RECIPE_NET_ID;/** * Used to send all valid recipes from Java to Bedrock. * * Bedrock REQUIRES a CraftingDataPacket to be sent in order to craft anything. */@Translator(packet = ServerDeclareRecipesPacket.class)public class JavaDeclareRecipesTranslator extends PacketTranslator<ServerDeclareRecipesPacket> { /** * Required to use the specified cartography table recipes */ private static final List<CraftingData> CARTOGRAPHY_RECIPES = Arrays.asList( CraftingData.fromMulti(UUID.fromString("8b36268c-1829-483c-a0f1-993b7156a8f2"), ++LAST_RECIPE_NET_ID), // Map extending CraftingData.fromMulti(UUID.fromString("442d85ed-8272-4543-a6f1-418f90ded05d"), ++LAST_RECIPE_NET_ID), // Map cloning CraftingData.fromMulti(UUID.fromString("98c84b38-1085-46bd-b1ce-dd38c159e6cc"), ++LAST_RECIPE_NET_ID), // Map upgrading CraftingData.fromMulti(UUID.fromString("602234e4-cac1-4353-8bb7-b1ebff70024b"), ++LAST_RECIPE_NET_ID) // Map locking ); @Override // BUG: CWE-287 Improper Authentication // public void translate(ServerDeclareRecipesPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, ServerDeclareRecipesPacket packet) { Map<RecipeType, List<CraftingData>> recipeTypes = Registries.CRAFTING_DATA.forVersion(session.getUpstream().getProtocolVersion()); // Get the last known network ID (first used for the pregenerated recipes) and increment from there. int netId = InventoryUtils.LAST_RECIPE_NET_ID + 1; Int2ObjectMap<Recipe> recipeMap = new Int2ObjectOpenHashMap<>(Registries.RECIPES.forVersion(session.getUpstream().getProtocolVersion())); Int2ObjectMap<List<StoneCuttingRecipeData>> unsortedStonecutterData = new Int2ObjectOpenHashMap<>(); CraftingDataPacket craftingDataPacket = new CraftingDataPacket(); craftingDataPacket.setCleanRecipes(true); for (Recipe recipe : packet.getRecipes()) { switch (recipe.getType()) { case CRAFTING_SHAPELESS: { ShapelessRecipeData shapelessRecipeData = (ShapelessRecipeData) recipe.getData(); ItemData output = ItemTranslator.translateToBedrock(session, shapelessRecipeData.getResult()); // Strip NBT - tools won't appear in the recipe book otherwise output = output.toBuilder().tag(null).build(); ItemData[][] inputCombinations = combinations(session, shapelessRecipeData.getIngredients()); for (ItemData[] inputs : inputCombinations) { UUID uuid = UUID.randomUUID(); craftingDataPacket.getCraftingData().add(CraftingData.fromShapeless(uuid.toString(), Arrays.asList(inputs), Collections.singletonList(output), uuid, "crafting_table", 0, netId)); recipeMap.put(netId++, recipe); } break; } case CRAFTING_SHAPED: { ShapedRecipeData shapedRecipeData = (ShapedRecipeData) recipe.getData(); ItemData output = ItemTranslator.translateToBedrock(session, shapedRecipeData.getResult()); // See above output = output.toBuilder().tag(null).build(); ItemData[][] inputCombinations = combinations(session, shapedRecipeData.getIngredients()); for (ItemData[] inputs : inputCombinations) { UUID uuid = UUID.randomUUID(); craftingDataPacket.getCraftingData().add(CraftingData.fromShaped(uuid.toString(), shapedRecipeData.getWidth(), shapedRecipeData.getHeight(), Arrays.asList(inputs), Collections.singletonList(output), uuid, "crafting_table", 0, netId)); recipeMap.put(netId++, recipe); } break; } case STONECUTTING: { StoneCuttingRecipeData stoneCuttingData = (StoneCuttingRecipeData) recipe.getData(); ItemStack ingredient = stoneCuttingData.getIngredient().getOptions()[0]; List<StoneCuttingRecipeData> data = unsortedStonecutterData.get(ingredient.getId()); if (data == null) { data = new ArrayList<>(); unsortedStonecutterData.put(ingredient.getId(), data); } data.add(stoneCuttingData); // Save for processing after all recipes have been received break; } default: { List<CraftingData> craftingData = recipeTypes.get(recipe.getType()); if (craftingData != null) { craftingDataPacket.getCraftingData().addAll(craftingData); } break; } } } craftingDataPacket.getCraftingData().addAll(CARTOGRAPHY_RECIPES); craftingDataPacket.getPotionMixData().addAll(Registries.POTION_MIXES.get()); Int2ObjectMap<IntList> stonecutterRecipeMap = new Int2ObjectOpenHashMap<>(); for (Int2ObjectMap.Entry<List<StoneCuttingRecipeData>> data : unsortedStonecutterData.int2ObjectEntrySet()) { // Sort the list by each output item's Java identifier - this is how it's sorted on Java, and therefore // We can get the correct order for button pressing data.getValue().sort(Comparator.comparing((stoneCuttingRecipeData -> session.getItemMappings().getItems().get(stoneCuttingRecipeData.getResult().getId()).getJavaIdentifier()))); // Now that it's sorted, let's translate these recipes for (StoneCuttingRecipeData stoneCuttingData : data.getValue()) { // As of 1.16.4, all stonecutter recipes have one ingredient option ItemStack ingredient = stoneCuttingData.getIngredient().getOptions()[0]; ItemData input = ItemTranslator.translateToBedrock(session, ingredient); ItemData output = ItemTranslator.translateToBedrock(session, stoneCuttingData.getResult()); UUID uuid = UUID.randomUUID(); // We need to register stonecutting recipes so they show up on Bedrock craftingDataPacket.getCraftingData().add(CraftingData.fromShapeless(uuid.toString(), Collections.singletonList(input), Collections.singletonList(output), uuid, "stonecutter", 0, netId++)); // Save the recipe list for reference when crafting IntList outputs = stonecutterRecipeMap.get(ingredient.getId()); if (outputs == null) { outputs = new IntArrayList(); // Add the ingredient as the key and all possible values as the value stonecutterRecipeMap.put(ingredient.getId(), outputs); } outputs.add(stoneCuttingData.getResult().getId()); } } session.sendUpstreamPacket(craftingDataPacket); session.setCraftingRecipes(recipeMap); session.getUnlockedRecipes().clear(); session.setStonecutterRecipes(stonecutterRecipeMap); session.getLastRecipeNetId().set(netId); } //TODO: rewrite /** * The Java server sends an array of items for each ingredient you can use per slot in the crafting grid. * Bedrock recipes take only one ingredient per crafting grid slot. * * @return the Java ingredient list as an array that Bedrock can understand */ private ItemData[][] combinations(GeyserSession session, Ingredient[] ingredients) { Map<Set<ItemData>, IntSet> squashedOptions = new HashMap<>(); for (int i = 0; i < ingredients.length; i++) { if (ingredients[i].getOptions().length == 0) { squashedOptions.computeIfAbsent(Collections.singleton(ItemData.AIR), k -> new IntOpenHashSet()).add(i); continue; } Ingredient ingredient = ingredients[i]; Map<GroupedItem, List<ItemData>> groupedByIds = Arrays.stream(ingredient.getOptions()) .map(item -> ItemTranslator.translateToBedrock(session, item)) .collect(Collectors.groupingBy(item -> new GroupedItem(item.getId(), item.getCount(), item.getTag()))); Set<ItemData> optionSet = new HashSet<>(groupedByIds.size()); for (Map.Entry<GroupedItem, List<ItemData>> entry : groupedByIds.entrySet()) { if (entry.getValue().size() > 1) { GroupedItem groupedItem = entry.getKey(); int idCount = 0; //not optimal for (ItemMapping mapping : session.getItemMappings().getItems().values()) { if (mapping.getBedrockId() == groupedItem.id) { idCount++; } } if (entry.getValue().size() < idCount) { optionSet.addAll(entry.getValue()); } else { optionSet.add(ItemData.builder() .id(groupedItem.id) .damage(Short.MAX_VALUE) .count(groupedItem.count) .tag(groupedItem.tag).build()); } } else { ItemData item = entry.getValue().get(0); optionSet.add(item); } } squashedOptions.computeIfAbsent(optionSet, k -> new IntOpenHashSet()).add(i); } int totalCombinations = 1; for (Set<ItemData> optionSet : squashedOptions.keySet()) { totalCombinations *= optionSet.size(); } if (totalCombinations > 500) { ItemData[] translatedItems = new ItemData[ingredients.length]; for (int i = 0; i < ingredients.length; i++) { if (ingredients[i].getOptions().length > 0) { translatedItems[i] = ItemTranslator.translateToBedrock(session, ingredients[i].getOptions()[0]); } else { translatedItems[i] = ItemData.AIR; } } return new ItemData[][]{translatedItems}; } List<Set<ItemData>> sortedSets = new ArrayList<>(squashedOptions.keySet()); sortedSets.sort(Comparator.comparing(Set::size, Comparator.reverseOrder())); ItemData[][] combinations = new ItemData[totalCombinations][ingredients.length]; int x = 1; for (Set<ItemData> set : sortedSets) { IntSet slotSet = squashedOptions.get(set); int i = 0; for (ItemData item : set) { for (int j = 0; j < totalCombinations / set.size(); j++) { final int comboIndex = (i * x) + (j % x) + ((j / x) * set.size() * x); for (int slot : slotSet) { combinations[comboIndex][slot] = item; } } i++; } x *= set.size(); } return combinations; } @EqualsAndHashCode @AllArgsConstructor private static class GroupedItem { int id; int count; NbtMap tag; }}
 
 
data/java/javacvefixed138.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java;import com.github.steveice10.mc.protocol.packet.ingame.server.ServerDeclareTagsPacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;@Translator(packet = ServerDeclareTagsPacket.class)public class JavaDeclareTagsTranslator extends PacketTranslator<ServerDeclareTagsPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(ServerDeclareTagsPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, ServerDeclareTagsPacket packet) { session.getTagCache().loadPacket(packet); }}
 
 
data/java/javacvefixed139.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import com.github.steveice10.mc.protocol.packet.ingame.server.ServerDifficultyPacket;import com.nukkitx.protocol.bedrock.packet.SetDifficultyPacket;@Translator(packet = ServerDifficultyPacket.class)public class JavaDifficultyTranslator extends PacketTranslator<ServerDifficultyPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(ServerDifficultyPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, ServerDifficultyPacket packet) { SetDifficultyPacket setDifficultyPacket = new SetDifficultyPacket(); setDifficultyPacket.setDifficulty(packet.getDifficulty().ordinal()); session.sendUpstreamPacket(setDifficultyPacket); session.getWorldCache().setDifficulty(packet.getDifficulty()); }}
 
 
data/java/javacvefixed14.txt DELETED
@@ -1 +0,0 @@
1
- package org.jolokia.backend;/* * Copyright 2009-2013 Roland Huss * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */import java.io.IOException;import java.util.Map;import javax.management.*;import org.jolokia.backend.executor.NotChangedException;import org.jolokia.config.ConfigKey;import org.jolokia.config.Configuration;import org.jolokia.converter.Converters;import org.jolokia.detector.ServerHandle;import org.jolokia.request.JmxRequest;import org.jolokia.request.JmxRequestBuilder;import org.jolokia.restrictor.Restrictor;import org.jolokia.util.*;import org.json.simple.JSONObject;import org.testng.annotations.BeforeTest;import org.testng.annotations.Test;import static org.testng.Assert.*;/** * @author roland * @since Jun 15, 2010 */public class BackendManagerTest { Configuration config; private LogHandler log = new LogHandler.StdoutLogHandler(true); @BeforeTest public void setup() { config = new Configuration(ConfigKey.AGENT_ID,"test"); } @Test public void simpleRead() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException { Configuration config = new Configuration(ConfigKey.DEBUG,"true",ConfigKey.AGENT_ID,"test"); BackendManager backendManager = new BackendManager(config, log); JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory") .attribute("HeapMemoryUsage") .build(); JSONObject ret = backendManager.handleRequest(req); assertTrue((Long) ((Map) ret.get("value")).get("used") > 0); backendManager.destroy(); } @Test public void notChanged() throws MalformedObjectNameException, MBeanException, AttributeNotFoundException, ReflectionException, InstanceNotFoundException, IOException { Configuration config = new Configuration(ConfigKey.DISPATCHER_CLASSES,RequestDispatcherTest.class.getName(),ConfigKey.AGENT_ID,"test"); BackendManager backendManager = new BackendManager(config, log); JmxRequest req = new JmxRequestBuilder(RequestType.LIST).build(); JSONObject ret = backendManager.handleRequest(req); assertEquals(ret.get("status"),304); backendManager.destroy(); } @Test public void lazyInit() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException { BackendManager backendManager = new BackendManager(config, log, null, true /* Lazy Init */ ); JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory") .attribute("HeapMemoryUsage") .build(); JSONObject ret = backendManager.handleRequest(req); assertTrue((Long) ((Map) ret.get("value")).get("used") > 0); backendManager.destroy(); } @Test public void requestDispatcher() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException { config = new Configuration(ConfigKey.DISPATCHER_CLASSES,RequestDispatcherTest.class.getName(),ConfigKey.AGENT_ID,"test"); BackendManager backendManager = new BackendManager(config, log); JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory").build(); backendManager.handleRequest(req); assertTrue(RequestDispatcherTest.called); backendManager.destroy(); } @Test(expectedExceptions = IllegalArgumentException.class,expectedExceptionsMessageRegExp = ".*invalid constructor.*") public void requestDispatcherWithWrongDispatcher() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException { Configuration config = new Configuration(ConfigKey.DISPATCHER_CLASSES,RequestDispatcherWrong.class.getName(),ConfigKey.AGENT_ID,"test"); new BackendManager(config,log); } @Test(expectedExceptions = IllegalArgumentException.class,expectedExceptionsMessageRegExp = ".*blub.bla.Dispatcher.*") public void requestDispatcherWithUnkownDispatcher() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException { Configuration config = new Configuration(ConfigKey.DISPATCHER_CLASSES,"blub.bla.Dispatcher",ConfigKey.AGENT_ID,"test"); new BackendManager(config,log); } @Test public void debugging() { RecordingLogHandler lhandler = new RecordingLogHandler(); BackendManager backendManager = new BackendManager(config,lhandler); lhandler.error = 0; lhandler.debug = 0; lhandler.info = 0; backendManager.debug("test"); assertEquals(lhandler.debug,1); backendManager.error("test",new Exception()); assertEquals(lhandler.error,1); backendManager.info("test"); assertEquals(lhandler.info,1); backendManager.destroy(); } @Test public void defaultConfig() { Configuration config = new Configuration(ConfigKey.DEBUG_MAX_ENTRIES,"blabal",ConfigKey.AGENT_ID,"test"); BackendManager backendManager = new BackendManager(config,log); backendManager.destroy(); } @Test public void doubleInit() { BackendManager b1 = new BackendManager(config,log); BackendManager b2 = new BackendManager(config,log); b2.destroy(); b1.destroy(); } @Test public void remoteAccessCheck() { BackendManager backendManager = new BackendManager(config,log); assertTrue(backendManager.isRemoteAccessAllowed("localhost","127.0.0.1")); backendManager.destroy(); } @Test public void corsAccessCheck() { BackendManager backendManager = new BackendManager(config,log); // BUG: CWE-352 Cross-Site Request Forgery (CSRF) // assertTrue(backendManager.isCorsAccessAllowed("http://bla.com")); // FIXED: assertTrue(backendManager.isOriginAllowed("http://bla.com",false)); backendManager.destroy(); } @Test public void convertError() throws MalformedObjectNameException { BackendManager backendManager = new BackendManager(config,log); Exception exp = new IllegalArgumentException("Hans",new IllegalStateException("Kalb")); JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory").build(); JSONObject jsonError = (JSONObject) backendManager.convertExceptionToJson(exp,req); assertTrue(!jsonError.containsKey("stackTrace")); assertEquals(jsonError.get("message"),"Hans"); assertEquals(((JSONObject) jsonError.get("cause")).get("message"),"Kalb"); backendManager.destroy(); } // ========================================================================================= static class RequestDispatcherTest implements RequestDispatcher { static boolean called = false; public RequestDispatcherTest(Converters pConverters,ServerHandle pServerHandle,Restrictor pRestrictor) { assertNotNull(pConverters); assertNotNull(pRestrictor); } public Object dispatchRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException, NotChangedException { called = true; if (pJmxReq.getType() == RequestType.READ) { return new JSONObject(); } else if (pJmxReq.getType() == RequestType.WRITE) { return "faultyFormat"; } else if (pJmxReq.getType() == RequestType.LIST) { throw new NotChangedException(pJmxReq); } return null; } public boolean canHandle(JmxRequest pJmxRequest) { return true; } public boolean useReturnValueWithPath(JmxRequest pJmxRequest) { return false; } } // ======================================================== static class RequestDispatcherWrong implements RequestDispatcher { // No special constructor --> fail public Object dispatchRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException { return null; } public boolean canHandle(JmxRequest pJmxRequest) { return false; } public boolean useReturnValueWithPath(JmxRequest pJmxRequest) { return false; } } private class RecordingLogHandler implements LogHandler { int debug = 0; int info = 0; int error = 0; public void debug(String message) { debug++; } public void info(String message) { info++; } public void error(String message, Throwable t) { error++; } }}
 
 
data/java/javacvefixed140.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java;import com.github.steveice10.mc.protocol.packet.ingame.server.ServerDisconnectPacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.network.translators.chat.MessageTranslator;@Translator(packet = ServerDisconnectPacket.class)public class JavaDisconnectPacket extends PacketTranslator<ServerDisconnectPacket> { @Override public void translate(GeyserSession session, ServerDisconnectPacket packet) { session.disconnect(MessageTranslator.convertMessage(packet.getReason(), session.getLocale())); }}
 
 
data/java/javacvefixed141.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java.scoreboard;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import com.github.steveice10.mc.protocol.packet.ingame.server.scoreboard.ServerDisplayScoreboardPacket;@Translator(packet = ServerDisplayScoreboardPacket.class)public class JavaDisplayScoreboardTranslator extends PacketTranslator<ServerDisplayScoreboardPacket> { @Override public void translate(GeyserSession session, ServerDisplayScoreboardPacket packet) { session.getWorldCache().getScoreboard() .displayObjective(packet.getName(), packet.getPosition()); }}
 
 
data/java/javacvefixed142.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.java.entity;import com.github.steveice10.mc.protocol.packet.ingame.server.entity.ServerEntityAnimationPacket;import com.nukkitx.math.vector.Vector3f;import com.nukkitx.protocol.bedrock.packet.AnimateEntityPacket;import com.nukkitx.protocol.bedrock.packet.AnimatePacket;import com.nukkitx.protocol.bedrock.packet.SpawnParticleEffectPacket;import org.geysermc.connector.entity.Entity;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.utils.DimensionUtils;@Translator(packet = ServerEntityAnimationPacket.class)public class JavaEntityAnimationTranslator extends PacketTranslator<ServerEntityAnimationPacket> { @Override public void translate(GeyserSession session, ServerEntityAnimationPacket packet) { Entity entity; if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) { entity = session.getPlayerEntity(); } else { entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId()); } if (entity == null) return; AnimatePacket animatePacket = new AnimatePacket(); animatePacket.setRuntimeEntityId(entity.getGeyserId()); switch (packet.getAnimation()) { case SWING_ARM: animatePacket.setAction(AnimatePacket.Action.SWING_ARM); break; case EAT_FOOD: // ACTUALLY SWING OFF HAND // Use the OptionalPack to trigger the animation AnimateEntityPacket offHandPacket = new AnimateEntityPacket(); offHandPacket.setAnimation("animation.player.attack.rotations.offhand"); offHandPacket.setNextState("default"); offHandPacket.setBlendOutTime(0.0f); offHandPacket.setStopExpression("query.any_animation_finished"); offHandPacket.setController("__runtime_controller"); offHandPacket.getRuntimeEntityIds().add(entity.getGeyserId()); session.sendUpstreamPacket(offHandPacket); return; case CRITICAL_HIT: animatePacket.setAction(AnimatePacket.Action.CRITICAL_HIT); break; case ENCHANTMENT_CRITICAL_HIT: animatePacket.setAction(AnimatePacket.Action.MAGIC_CRITICAL_HIT); // Unsure if this does anything // Spawn custom particle SpawnParticleEffectPacket stringPacket = new SpawnParticleEffectPacket(); stringPacket.setIdentifier("geyseropt:enchanted_hit_multiple"); stringPacket.setDimensionId(DimensionUtils.javaToBedrock(session.getDimension())); stringPacket.setPosition(Vector3f.ZERO); stringPacket.setUniqueEntityId(entity.getGeyserId()); session.sendUpstreamPacket(stringPacket); break; case LEAVE_BED: animatePacket.setAction(AnimatePacket.Action.WAKE_UP); break; default: // Unknown Animation return; } session.sendUpstreamPacket(animatePacket); }}