code
stringlengths 23
2.05k
| label_name
stringlengths 6
7
| label
int64 0
37
|
---|---|---|
public void translate(MapInfoRequestPacket packet, GeyserSession session) {
long mapId = packet.getUniqueMapId();
ClientboundMapItemDataPacket mapPacket = session.getStoredMaps().remove(mapId);
if (mapPacket != null) {
// Delay the packet 100ms to prevent the client from ignoring the packet
GeyserConnector.getInstance().getGeneralThreadPool().schedule(() -> session.sendUpstreamPacket(mapPacket),
100, TimeUnit.MILLISECONDS);
}
} | CWE-287 | 4 |
public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) {
return new AuthorizationCodeTokenRequest(transport, jsonFactory,
new GenericUrl(tokenServerEncodedUrl), authorizationCode).setClientAuthentication(
clientAuthentication).setRequestInitializer(requestInitializer).setScopes(scopes);
} | CWE-863 | 11 |
public void translate(BlockPickRequestPacket packet, GeyserSession session) {
Vector3i vector = packet.getBlockPosition();
int blockToPick = session.getConnector().getWorldManager().getBlockAt(session, vector.getX(), vector.getY(), vector.getZ());
// Block is air - chunk caching is probably off
if (blockToPick == BlockStateValues.JAVA_AIR_ID) {
// Check for an item frame since the client thinks that's a block when it's an entity in Java
ItemFrameEntity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition());
if (entity != null) {
// Check to see if the item frame has an item in it first
if (entity.getHeldItem() != null && entity.getHeldItem().getId() != 0) {
// Grab the item in the frame
InventoryUtils.findOrCreateItem(session, entity.getHeldItem());
} else {
// Grab the frame as the item
InventoryUtils.findOrCreateItem(session, entity.getEntityType() == EntityType.GLOW_ITEM_FRAME ? "minecraft:glow_item_frame" : "minecraft:item_frame");
}
}
return;
}
InventoryUtils.findOrCreateItem(session, BlockRegistries.JAVA_BLOCKS.get(blockToPick).getPickItem());
}
| CWE-287 | 4 |
public void translate(ServerStopSoundPacket packet, GeyserSession session) {
// Runs if all sounds are stopped
if (packet.getSound() == null) {
StopSoundPacket stopPacket = new StopSoundPacket();
stopPacket.setStoppingAllSound(true);
stopPacket.setSoundName("");
session.sendUpstreamPacket(stopPacket);
return;
}
String packetSound;
if (packet.getSound() instanceof BuiltinSound) {
packetSound = ((BuiltinSound) packet.getSound()).getName();
} else if (packet.getSound() instanceof CustomSound) {
packetSound = ((CustomSound) packet.getSound()).getName();
} else {
session.getConnector().getLogger().debug("Unknown sound packet, we were unable to map this. " + packet.toString());
return;
}
SoundMapping soundMapping = Registries.SOUNDS.get(packetSound.replace("minecraft:", ""));
session.getConnector().getLogger()
.debug("[StopSound] Sound mapping " + packetSound + " -> "
+ soundMapping + (soundMapping == null ? "[not found]" : "")
+ " - " + packet.toString());
String playsound;
if (soundMapping == null || soundMapping.getPlaysound() == null) {
// no mapping
session.getConnector().getLogger()
.debug("[StopSound] Defaulting to sound server gave us.");
playsound = packetSound;
} else {
playsound = soundMapping.getPlaysound();
}
StopSoundPacket stopSoundPacket = new StopSoundPacket();
stopSoundPacket.setSoundName(playsound);
// packet not mapped in the library
stopSoundPacket.setStoppingAllSound(false);
session.sendUpstreamPacket(stopSoundPacket);
session.getConnector().getLogger().debug("[StopSound] Packet sent - " + packet.toString() + " --> " + stopSoundPacket);
} | CWE-287 | 4 |
public void testAADLengthComputation() {
Assert.assertArrayEquals(AAD_LENGTH, com.nimbusds.jose.crypto.AAD.computeLength(AAD));
} | CWE-345 | 22 |
public void existingDocumentNonTerminalFromUIDeprecatedCheckEscaping() throws Exception
{
// current document = xwiki:Main.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(false);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Submit from the UI space=X.Y&tocreate=space
when(mockRequest.getParameter("space")).thenReturn("X.Y");
when(mockRequest.getParameter("tocreate")).thenReturn("space");
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify null is returned (this means the response has been returned)
assertNull(result);
// Note1: The space parameter was previously considered as space name, not space reference, so it is escaped.
// Note2: We are creating X\.Y.WebHome because the tocreate parameter says "space".
verify(mockURLFactory).createURL("X\\.Y", "WebHome", "edit", "template=&parent=Main.WebHome&title=X.Y", null,
"xwiki", context);
} | CWE-862 | 8 |
public String getEncryptedValue() {
try {
Cipher cipher = KEY.encrypt();
// add the magic suffix which works like a check sum.
return new String(Base64.encode(cipher.doFinal((value+MAGIC).getBytes("UTF-8"))));
} catch (GeneralSecurityException e) {
throw new Error(e); // impossible
} catch (UnsupportedEncodingException e) {
throw new Error(e); // impossible
}
} | CWE-326 | 9 |
private void initAndSaveDocument(XWikiContext context, XWikiDocument newDocument, String title, String template,
String parent) throws XWikiException
{
XWiki xwiki = context.getWiki();
// Set the locale and default locale, considering that we're creating the original version of the document
// (not a translation).
newDocument.setLocale(Locale.ROOT);
if (newDocument.getDefaultLocale() == Locale.ROOT) {
newDocument.setDefaultLocale(xwiki.getLocalePreference(context));
}
// Copy the template.
readFromTemplate(newDocument, template, context);
// Set the parent field.
if (!StringUtils.isEmpty(parent)) {
DocumentReference parentReference = this.currentmixedReferenceResolver.resolve(parent);
newDocument.setParentReference(parentReference);
}
// Set the document title
if (title != null) {
newDocument.setTitle(title);
}
// Set the author and creator.
DocumentReference currentUserReference = context.getUserReference();
newDocument.setAuthorReference(currentUserReference);
newDocument.setCreatorReference(currentUserReference);
// Make sure the user is allowed to make this modification
xwiki.checkSavingDocument(currentUserReference, newDocument, context);
xwiki.saveDocument(newDocument, context);
} | CWE-862 | 8 |
public String accessToken(String username) {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
return JWT.create()
.withExpiresAt(new Date(new Date().getTime() + ACCESS_EXPIRE_TIME))
.withIssuer(ISSUER)
.withClaim("username", username)
.sign(algorithm);
} | CWE-20 | 0 |
public void translate(ServerSetActionBarTextPacket packet, GeyserSession session) {
String text;
if (packet.getText() == null) { //TODO 1.17 can this happen?
text = " ";
} else {
text = MessageTranslator.convertMessage(packet.getText(), session.getLocale());
}
SetTitlePacket titlePacket = new SetTitlePacket();
titlePacket.setType(SetTitlePacket.Type.ACTIONBAR);
titlePacket.setText(text);
titlePacket.setXuid("");
titlePacket.setPlatformOnlineId("");
session.sendUpstreamPacket(titlePacket);
} | CWE-287 | 4 |
public void testGetAndRemove() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.add("name1", "value1");
headers.add("name2", "value2", "value3");
headers.add("name3", "value4", "value5", "value6");
assertThat(headers.getAndRemove("name1", "defaultvalue")).isEqualTo("value1");
assertThat(headers.getAndRemove("name2")).isEqualTo("value2");
assertThat(headers.getAndRemove("name2")).isNull();
assertThat(headers.getAllAndRemove("name3")).containsExactly("value4", "value5", "value6");
assertThat(headers.size()).isZero();
assertThat(headers.getAndRemove("noname")).isNull();
assertThat(headers.getAndRemove("noname", "defaultvalue")).isEqualTo("defaultvalue");
} | CWE-74 | 1 |
public void newDocumentWebHomeButTerminalFromURL() throws Exception
{
// new document = xwiki:X.Y.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X", "Y"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(true);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Pass the tocreate=terminal request parameter
when(mockRequest.getParameter("tocreate")).thenReturn("terminal");
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify null is returned (this means the response has been returned)
assertNull(result);
// Note: We are creating X.Y instead of X.Y.WebHome because the tocreate parameter says "terminal".
verify(mockURLFactory).createURL("X", "Y", "edit", "template=&parent=Main.WebHome&title=Y", null, "xwiki",
context);
} | CWE-862 | 8 |
public void translate(FilterTextPacket packet, GeyserSession session) {
if (session.getOpenInventory() instanceof CartographyContainer) {
// We don't want to be able to rename in the cartography table
return;
}
packet.setFromServer(true);
session.sendUpstreamPacket(packet);
if (session.getOpenInventory() instanceof AnvilContainer) {
// Java Edition sends a packet every time an item is renamed even slightly in GUI. Fortunately, this works out for us now
ClientRenameItemPacket renameItemPacket = new ClientRenameItemPacket(packet.getText());
session.sendDownstreamPacket(renameItemPacket);
}
} | CWE-287 | 4 |
private <P extends T> void translate0(GeyserSession session, PacketTranslator<P> translator, P packet) {
if (session.isClosed()) {
return;
}
try {
translator.translate(packet, session);
} catch (Throwable ex) {
GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.network.translator.packet.failed", packet.getClass().getSimpleName()), ex);
ex.printStackTrace();
}
} | CWE-287 | 4 |
public void notExistingDocumentFromUIButSpaceTooLong() throws Exception
{
// current document = xwiki:Main.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(false);
when(document.getLocalReferenceMaxLength()).thenReturn(10);
context.setDoc(document);
when(mockRequest.getParameter("spaceReference")).thenReturn("1.3.5.7.9.11");
when(mockRequest.getParameter("name")).thenReturn("Foo");
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify that the create template is rendered, so the UI is displayed for the user to see the error.
assertEquals("create", result);
// Check that the exception is properly set in the context for the UI to display.
XWikiException exception = (XWikiException) this.oldcore.getScriptContext().getAttribute("createException");
assertNotNull(exception);
assertEquals(XWikiException.ERROR_XWIKI_APP_DOCUMENT_PATH_TOO_LONG, exception.getCode());
// We should not get this far so no redirect should be done, just the template will be rendered.
verify(mockURLFactory, never()).createURL(any(), any(), any(), any(), any(),
any(), any(XWikiContext.class));
} | CWE-862 | 8 |
private CallbackHandler getCallbackHandler(
@UnderInitialization(WrappedFactory.class) LibPQFactory this,
Properties info) throws PSQLException {
// Determine the callback handler
CallbackHandler cbh;
String sslpasswordcallback = PGProperty.SSL_PASSWORD_CALLBACK.get(info);
if (sslpasswordcallback != null) {
try {
cbh = (CallbackHandler) ObjectFactory.instantiate(sslpasswordcallback, info, false, null);
} catch (Exception e) {
throw new PSQLException(
GT.tr("The password callback class provided {0} could not be instantiated.",
sslpasswordcallback),
PSQLState.CONNECTION_FAILURE, e);
}
} else {
cbh = new ConsoleCallbackHandler(PGProperty.SSL_PASSWORD.get(info));
}
return cbh;
} | CWE-665 | 32 |
public void translate(ContainerClosePacket packet, GeyserSession session) {
byte windowId = packet.getId();
//Client wants close confirmation
session.sendUpstreamPacket(packet);
session.setClosingInventory(false);
if (windowId == -1 && session.getOpenInventory() instanceof MerchantContainer) {
// 1.16.200 - window ID is always -1 sent from Bedrock
windowId = (byte) session.getOpenInventory().getId();
}
Inventory openInventory = session.getOpenInventory();
if (openInventory != null) {
if (windowId == openInventory.getId()) {
ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(windowId);
session.sendDownstreamPacket(closeWindowPacket);
InventoryUtils.closeInventory(session, windowId, false);
} else if (openInventory.isPending()) {
InventoryUtils.displayInventory(session, openInventory);
openInventory.setPending(false);
}
}
} | CWE-287 | 4 |
public static boolean isPermitted(
final Optional<AuthenticationService> authenticationService,
final Optional<User> optionalUser,
final JsonRpcMethod jsonRpcMethod) {
AtomicBoolean foundMatchingPermission = new AtomicBoolean();
if (authenticationService.isPresent()) {
if (optionalUser.isPresent()) {
User user = optionalUser.get();
for (String perm : jsonRpcMethod.getPermissions()) {
user.isAuthorized(
perm,
(authed) -> {
if (authed.result()) {
LOG.trace(
"user {} authorized : {} via permission {}",
user,
jsonRpcMethod.getName(),
perm);
foundMatchingPermission.set(true);
}
});
}
}
} else {
// no auth provider configured thus anything is permitted
foundMatchingPermission.set(true);
}
if (!foundMatchingPermission.get()) {
LOG.trace("user NOT authorized : {}", jsonRpcMethod.getName());
}
return foundMatchingPermission.get();
} | CWE-400 | 2 |
public void shouldNotGetModificationsFromOtherBranches() throws Exception {
makeACommitToSecondBranch();
hg(workingDirectory, "pull").runOrBomb(null);
List<Modification> actual = hgCommand.modificationsSince(new StringRevision(REVISION_0));
assertThat(actual.size(), is(2));
assertThat(actual.get(0).getRevision(), is(REVISION_2));
assertThat(actual.get(1).getRevision(), is(REVISION_1));
} | CWE-77 | 14 |
public void translate(ServerScoreboardObjectivePacket packet, GeyserSession session) {
WorldCache worldCache = session.getWorldCache();
Scoreboard scoreboard = worldCache.getScoreboard();
Objective objective = scoreboard.getObjective(packet.getName());
int pps = worldCache.increaseAndGetScoreboardPacketsPerSecond();
if (objective == null && packet.getAction() != ObjectiveAction.REMOVE) {
objective = scoreboard.registerNewObjective(packet.getName(), false);
}
switch (packet.getAction()) {
case ADD:
case UPDATE:
objective.setDisplayName(MessageTranslator.convertMessage(packet.getDisplayName()))
.setType(packet.getType().ordinal());
break;
case REMOVE:
scoreboard.unregisterObjective(packet.getName());
break;
}
if (objective == null || !objective.isActive()) {
return;
}
// ScoreboardUpdater will handle it for us if the packets per second
// (for score and team packets) is higher then the first threshold
if (pps < ScoreboardUpdater.FIRST_SCORE_PACKETS_PER_SECOND_THRESHOLD) {
scoreboard.onUpdate();
}
} | CWE-287 | 4 |
public void translate(ServerKeepAlivePacket packet, GeyserSession session) {
if (!session.getConnector().getConfig().isForwardPlayerPing()) {
return;
}
NetworkStackLatencyPacket latencyPacket = new NetworkStackLatencyPacket();
latencyPacket.setFromServer(true);
latencyPacket.setTimestamp(packet.getPingId() * 1000);
session.sendUpstreamPacket(latencyPacket);
} | CWE-287 | 4 |
public void translate(CommandBlockUpdatePacket packet, GeyserSession session) {
String command = packet.getCommand();
boolean outputTracked = packet.isOutputTracked();
if (packet.isBlock()) {
CommandBlockMode mode;
switch (packet.getMode()) {
case CHAIN: // The green one
mode = CommandBlockMode.SEQUENCE;
break;
case REPEATING: // The purple one
mode = CommandBlockMode.AUTO;
break;
default: // NORMAL, the orange one
mode = CommandBlockMode.REDSTONE;
break;
}
boolean isConditional = packet.isConditional();
boolean automatic = !packet.isRedstoneMode(); // Automatic = Always Active option in Java
ClientUpdateCommandBlockPacket commandBlockPacket = new ClientUpdateCommandBlockPacket(
new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()),
command, mode, outputTracked, isConditional, automatic);
session.sendDownstreamPacket(commandBlockPacket);
} else {
ClientUpdateCommandBlockMinecartPacket commandMinecartPacket = new ClientUpdateCommandBlockMinecartPacket(
(int) session.getEntityCache().getEntityByGeyserId(packet.getMinecartRuntimeEntityId()).getEntityId(),
command, outputTracked
);
session.sendDownstreamPacket(commandMinecartPacket);
}
} | CWE-287 | 4 |
public String resolveDriverClassName(DriverClassNameResolveRequest request) {
return driverResources.resolveSqlDriverNameFromJar(request.getJdbcDriverFileUrl());
} | CWE-20 | 0 |
public void newDocumentWebHomeTopLevelFromURL() throws Exception
{
// new document = xwiki:X.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(true);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify null is returned (this means the response has been returned)
assertNull(result);
// Note: The title is not "WebHome", but "X" (the space's name) to avoid exposing "WebHome" in the UI.
verify(mockURLFactory).createURL("X", "WebHome", "edit", "template=&parent=Main.WebHome&title=X", null, "xwiki",
context);
} | CWE-862 | 8 |
public void addShouldIncreaseAndRemoveShouldDecreaseTheSize() {
final HttpHeadersBase headers = newEmptyHeaders();
assertThat(headers.size()).isEqualTo(0);
headers.add("name1", "value1", "value2");
assertThat(headers.size()).isEqualTo(2);
headers.add("name2", "value3", "value4");
assertThat(headers.size()).isEqualTo(4);
headers.add("name3", "value5");
assertThat(headers.size()).isEqualTo(5);
headers.remove("name3");
assertThat(headers.size()).isEqualTo(4);
headers.remove("name1");
assertThat(headers.size()).isEqualTo(2);
headers.remove("name2");
assertThat(headers.size()).isEqualTo(0);
assertThat(headers.isEmpty()).isTrue();
} | CWE-74 | 1 |
public User updateUser(JpaUser user) throws NotFoundException, UnauthorizedException {
if (!UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, user.getRoles()))
throw new UnauthorizedException("The user is not allowed to set the admin role on other users");
JpaUser updateUser = UserDirectoryPersistenceUtil.findUser(user.getUsername(), user.getOrganization().getId(), emf);
if (updateUser == null) {
throw new NotFoundException("User " + user.getUsername() + " not found.");
}
logger.debug("updateUser({})", user.getUsername());
if (!UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, updateUser.getRoles()))
throw new UnauthorizedException("The user is not allowed to update an admin user");
String encodedPassword;
//only update Password if a value is set
if (StringUtils.isEmpty(user.getPassword())) {
encodedPassword = updateUser.getPassword();
} else {
// Update an JPA user with an encoded password.
encodedPassword = PasswordEncoder.encode(user.getPassword(), user.getUsername());
}
// Only save internal roles
Set<JpaRole> roles = UserDirectoryPersistenceUtil.saveRoles(filterRoles(user.getRoles()), emf);
JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization(
(JpaOrganization) user.getOrganization(), emf);
JpaUser updatedUser = UserDirectoryPersistenceUtil.saveUser(
new JpaUser(user.getUsername(), encodedPassword, organization, user.getName(), user.getEmail(), user
.getProvider(), true, roles), emf);
cache.put(user.getUsername() + DELIMITER + organization.getId(), updatedUser);
updateGroupMembership(user);
return updatedUser;
} | CWE-327 | 3 |
public void translate(AdventureSettingsPacket packet, GeyserSession session) {
boolean isFlying = packet.getSettings().contains(AdventureSetting.FLYING);
if (!isFlying && session.getGameMode() == GameMode.SPECTATOR) {
// We should always be flying in spectator mode
session.sendAdventureSettings();
return;
}
session.setFlying(isFlying);
ClientPlayerAbilitiesPacket abilitiesPacket = new ClientPlayerAbilitiesPacket(isFlying);
session.sendDownstreamPacket(abilitiesPacket);
if (isFlying && session.getPlayerEntity().getMetadata().getFlags().getFlag(EntityFlag.SWIMMING)) {
// Bedrock can fly and swim at the same time? Make sure that can't happen
session.setSwimming(false);
}
} | CWE-287 | 4 |
public static synchronized InitialContext getInitialContext(final Hints hints)
throws NamingException {
return getInitialContext();
} | CWE-20 | 0 |
public void subValidateFail(ViolationCollector col) {
col.addViolation(FAILED+"subclass");
} | CWE-74 | 1 |
public static void init(final InitialContext applicationContext) {
synchronized (GeoTools.class) {
context = applicationContext;
}
fireConfigurationChanged();
} | CWE-20 | 0 |
public void multipleValuesPerNameShouldBeAllowed() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.add("name", "value1");
headers.add("name", "value2");
headers.add("name", "value3");
assertThat(headers.size()).isEqualTo(3);
final List<String> values = headers.getAll("name");
assertThat(values).hasSize(3)
.containsExactly("value1", "value2", "value3");
} | CWE-74 | 1 |
public void addViolation(String propertyName, String message) {
violationOccurred = true;
String messageTemplate = escapeEl(message);
context.buildConstraintViolationWithTemplate(messageTemplate)
.addPropertyNode(propertyName)
.addConstraintViolation();
} | CWE-74 | 1 |
public void testContains() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.addLong("long", Long.MAX_VALUE);
assertThat(headers.containsLong("long", Long.MAX_VALUE)).isTrue();
assertThat(headers.containsLong("long", Long.MIN_VALUE)).isFalse();
headers.addInt("int", Integer.MIN_VALUE);
assertThat(headers.containsInt("int", Integer.MIN_VALUE)).isTrue();
assertThat(headers.containsInt("int", Integer.MAX_VALUE)).isFalse();
headers.addDouble("double", Double.MAX_VALUE);
assertThat(headers.containsDouble("double", Double.MAX_VALUE)).isTrue();
assertThat(headers.containsDouble("double", Double.MIN_VALUE)).isFalse();
headers.addFloat("float", Float.MAX_VALUE);
assertThat(headers.containsFloat("float", Float.MAX_VALUE)).isTrue();
assertThat(headers.containsFloat("float", Float.MIN_VALUE)).isFalse();
final long millis = System.currentTimeMillis();
headers.addTimeMillis("millis", millis);
assertThat(headers.containsTimeMillis("millis", millis)).isTrue();
// This test doesn't work on midnight, January 1, 1970 UTC
assertThat(headers.containsTimeMillis("millis", 0)).isFalse();
headers.addObject("object", "Hello World");
assertThat(headers.containsObject("object", "Hello World")).isTrue();
assertThat(headers.containsObject("object", "")).isFalse();
headers.add("name", "value");
assertThat(headers.contains("name", "value")).isTrue();
assertThat(headers.contains("name", "value1")).isFalse();
} | CWE-74 | 1 |
public void translate(ServerSetSlotPacket packet, GeyserSession session) {
if (packet.getWindowId() == 255) { //cursor
GeyserItemStack newItem = GeyserItemStack.from(packet.getItem());
session.getPlayerInventory().setCursor(newItem, session);
InventoryUtils.updateCursor(session);
return;
}
//TODO: support window id -2, should update player inventory
Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId());
if (inventory == null)
return;
inventory.setStateId(packet.getStateId());
InventoryTranslator translator = session.getInventoryTranslator();
if (translator != null) {
if (session.getCraftingGridFuture() != null) {
session.getCraftingGridFuture().cancel(false);
}
session.setCraftingGridFuture(session.scheduleInEventLoop(() -> updateCraftingGrid(session, packet, inventory, translator), 150, TimeUnit.MILLISECONDS));
GeyserItemStack newItem = GeyserItemStack.from(packet.getItem());
if (packet.getWindowId() == 0 && !(translator instanceof PlayerInventoryTranslator)) {
// In rare cases, the window ID can still be 0 but Java treats it as valid
session.getPlayerInventory().setItem(packet.getSlot(), newItem, session);
InventoryTranslator.PLAYER_INVENTORY_TRANSLATOR.updateSlot(session, session.getPlayerInventory(), packet.getSlot());
} else {
inventory.setItem(packet.getSlot(), newItem, session);
translator.updateSlot(session, inventory, packet.getSlot());
}
}
} | CWE-287 | 4 |
public void getWithDefaultValueWorks() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.add("name1", "value1");
assertThat(headers.get("name1", "defaultvalue")).isEqualTo("value1");
assertThat(headers.get("noname", "defaultvalue")).isEqualTo("defaultvalue");
} | CWE-74 | 1 |
public void newDocumentButNonTerminalFromURL() throws Exception
{
// new document = xwiki:X.Y
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("X"), "Y");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(true);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Pass the tocreate=nonterminal request parameter
when(mockRequest.getParameter("tocreate")).thenReturn("nonterminal");
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify null is returned (this means the response has been returned)
assertNull(result);
verify(mockURLFactory).createURL("X.Y", "WebHome", "edit", "template=&parent=Main.WebHome&title=Y", null,
"xwiki", context);
} | CWE-862 | 8 |
public void checkConnection(UrlArgument repoUrl) {
final String ref = fullUpstreamRef();
final CommandLine commandLine = git().withArgs("ls-remote").withArg(repoUrl).withArg(ref);
final ConsoleResult result = commandLine.runOrBomb(new NamedProcessTag(repoUrl.forDisplay()));
if (!hasExactlyOneMatchingBranch(result)) {
throw new CommandLineException(format("The ref %s could not be found.", ref));
}
} | CWE-77 | 14 |
public void existingDocumentFromUITemplateSpecified() throws Exception
{
// current document = xwiki:Main.WebHome
DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
XWikiDocument document = mock(XWikiDocument.class);
when(document.getDocumentReference()).thenReturn(documentReference);
when(document.isNew()).thenReturn(false);
when(document.getLocalReferenceMaxLength()).thenReturn(255);
context.setDoc(document);
// Submit from the UI spaceReference=X&name=Y&template=XWiki.MyTemplate
String templateDocumentFullName = "XWiki.MyTemplate";
DocumentReference templateDocumentReference =
new DocumentReference("MyTemplate", Arrays.asList("XWiki"), "xwiki");
when(mockRequest.getParameter("spaceReference")).thenReturn("X");
when(mockRequest.getParameter("name")).thenReturn("Y");
when(mockRequest.getParameter("template")).thenReturn("XWiki.MyTemplate");
// Mock the passed template document as existing.
mockTemplateDocumentExisting(templateDocumentFullName, templateDocumentReference);
// Run the action
String result = action.render(context);
// The tests are below this line!
// Verify null is returned (this means the response has been returned)
assertNull(result);
// Note: We are creating X.Y.WebHome and using the template specified in the request.
verify(mockURLFactory).createURL("X.Y", "WebHome", "edit",
"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context);
} | CWE-862 | 8 |
public void translate(MoveEntityAbsolutePacket packet, GeyserSession session) {
session.setLastVehicleMoveTimestamp(System.currentTimeMillis());
float y = packet.getPosition().getY();
if (session.getRidingVehicleEntity() instanceof BoatEntity) {
// Remove the offset to prevents boats from looking like they're floating in water
y -= EntityType.BOAT.getOffset();
}
ClientVehicleMovePacket clientVehicleMovePacket = new ClientVehicleMovePacket(
packet.getPosition().getX(), y, packet.getPosition().getZ(),
packet.getRotation().getY() - 90, packet.getRotation().getX()
);
session.sendDownstreamPacket(clientVehicleMovePacket);
} | CWE-287 | 4 |
public void iteratorSetShouldFail() {
final HttpHeadersBase headers = newEmptyHeaders();
headers.add("name1", "value1", "value2", "value3");
headers.add("name2", "value4");
assertThat(headers.size()).isEqualTo(4);
assertThatThrownBy(() -> headers.iterator().next().setValue(""))
.isInstanceOf(UnsupportedOperationException.class);
} | CWE-74 | 1 |
public void translate(AnimatePacket packet, GeyserSession session) {
// Stop the player sending animations before they have fully spawned into the server
if (!session.isSpawned()) {
return;
}
switch (packet.getAction()) {
case SWING_ARM:
// Delay so entity damage can be processed first
session.scheduleInEventLoop(() ->
session.sendDownstreamPacket(new ClientPlayerSwingArmPacket(Hand.MAIN_HAND)),
25,
TimeUnit.MILLISECONDS
);
break;
// These two might need to be flipped, but my recommendation is getting moving working first
case ROW_LEFT:
// Packet value is a float of how long one has been rowing, so we convert that into a boolean
session.setSteeringLeft(packet.getRowingTime() > 0.0);
ClientSteerBoatPacket steerLeftPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());
session.sendDownstreamPacket(steerLeftPacket);
break;
case ROW_RIGHT:
session.setSteeringRight(packet.getRowingTime() > 0.0);
ClientSteerBoatPacket steerRightPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight());
session.sendDownstreamPacket(steerRightPacket);
break;
}
} | CWE-287 | 4 |
private DefaultHttpClient makeHttpClient() {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
try {
logger.debug("Installing forgiving hostname verifier and trust managers");
X509TrustManager trustManager = createTrustManager();
X509HostnameVerifier hostNameVerifier = createHostNameVerifier();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom());
SSLSocketFactory ssf = new SSLSocketFactory(sslContext, hostNameVerifier);
ClientConnectionManager ccm = defaultHttpClient.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
} catch (NoSuchAlgorithmException e) {
logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
} catch (KeyManagementException e) {
logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
}
return defaultHttpClient;
} | CWE-346 | 16 |
public static CharSequence createOptimized(String value) {
return io.netty.handler.codec.http.HttpHeaders.newEntity(value);
} | CWE-20 | 0 |
public void cleanup() {
} | CWE-362 | 18 |
private static AsciiString normalizeName(CharSequence name) {
checkArgument(requireNonNull(name, "name").length() > 0, "name is empty.");
return HttpHeaderNames.of(name);
} | CWE-74 | 1 |
public Map<String, FileEntry> generatorCode(TableDetails tableDetails, String tablePrefix,
Map<String, String> customProperties, List<TemplateFile> templateFiles) {
Map<String, FileEntry> map = new HashMap<>(templateFiles.size());
// 模板渲染
Map<String, Object> context = GenUtils.getContext(tableDetails, tablePrefix, customProperties);
for (TemplateFile templateFile : templateFiles) {
FileEntry fileEntry = new FileEntry();
fileEntry.setType(templateFile.getType());
// 替换路径中的占位符
String filename = StrUtil.format(templateFile.getFilename(), context);
fileEntry.setFilename(filename);
String parentFilePath = GenUtils.evaluateRealPath(templateFile.getParentFilePath(), context);
fileEntry.setParentFilePath(parentFilePath);
// 如果是文件
if (TemplateEntryTypeEnum.FILE.getType().equals(fileEntry.getType())) {
fileEntry.setFilePath(GenUtils.concatFilePath(parentFilePath, filename));
// 文件内容渲染
TemplateEngineTypeEnum engineTypeEnum = TemplateEngineTypeEnum.of(templateFile.getEngineType());
String content = templateEngineDelegator.render(engineTypeEnum, templateFile.getContent(), context);
fileEntry.setContent(content);
}
else {
String currentPath = GenUtils.evaluateRealPath(templateFile.getFilename(), context);
fileEntry.setFilePath(GenUtils.concatFilePath(parentFilePath, currentPath));
}
map.put(fileEntry.getFilePath(), fileEntry);
}
return map;
} | CWE-20 | 0 |
final void addObject(CharSequence name, Object... values) {
final AsciiString normalizedName = normalizeName(name);
requireNonNull(values, "values");
for (Object v : values) {
requireNonNullElement(values, v);
addObject(normalizedName, v);
}
} | CWE-74 | 1 |
/*package*/ static Secret tryDecrypt(Cipher cipher, byte[] in) throws UnsupportedEncodingException {
try {
String plainText = new String(cipher.doFinal(in), "UTF-8");
if(plainText.endsWith(MAGIC))
return new Secret(plainText.substring(0,plainText.length()-MAGIC.length()));
return null;
} catch (GeneralSecurityException e) {
return null; // if the key doesn't match with the bytes, it can result in BadPaddingException
}
} | CWE-326 | 9 |
public void correctExample() throws Exception {
assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))
.isEmpty();
assertThat(TestLoggerFactory.getAllLoggingEvents())
.isEmpty();
} | CWE-74 | 1 |
public void translate(ShowCreditsPacket packet, GeyserSession session) {
if (packet.getStatus() == ShowCreditsPacket.Status.END_CREDITS) {
ClientRequestPacket javaRespawnPacket = new ClientRequestPacket(ClientRequest.RESPAWN);
session.sendDownstreamPacket(javaRespawnPacket);
}
} | CWE-287 | 4 |
int bmp_validate(jas_stream_t *in)
{
int n;
int i;
uchar buf[2];
assert(JAS_STREAM_MAXPUTBACK >= 2);
/* Read the first two characters that constitute the signature. */
if ((n = jas_stream_read(in, (char *) buf, 2)) < 0) {
return -1;
}
/* Put the characters read back onto the stream. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough characters? */
if (n < 2) {
return -1;
}
/* Is the signature correct for the BMP format? */
if (buf[0] == (BMP_MAGIC & 0xff) && buf[1] == (BMP_MAGIC >> 8)) {
return 0;
}
return -1;
} | CWE-20 | 0 |
void HeaderMapImpl::insertByKey(HeaderString&& key, HeaderString&& value) {
EntryCb cb = ConstSingleton<StaticLookupTable>::get().find(key.getStringView());
if (cb) {
key.clear();
StaticLookupResponse ref_lookup_response = cb(*this);
if (*ref_lookup_response.entry_ == nullptr) {
maybeCreateInline(ref_lookup_response.entry_, *ref_lookup_response.key_, std::move(value));
} else {
appendToHeader((*ref_lookup_response.entry_)->value(), value.getStringView());
value.clear();
}
} else {
std::list<HeaderEntryImpl>::iterator i = headers_.insert(std::move(key), std::move(value));
i->entry_ = i;
}
} | CWE-400 | 2 |
void UTFstring::UpdateFromUTF8()
{
delete [] _Data;
// find the size of the final UCS-2 string
size_t i;
for (_Length=0, i=0; i<UTF8string.length(); _Length++) {
uint8 lead = static_cast<uint8>(UTF8string[i]);
if (lead < 0x80)
i++;
else if ((lead >> 5) == 0x6)
i += 2;
else if ((lead >> 4) == 0xe)
i += 3;
else if ((lead >> 3) == 0x1e)
i += 4;
else
// Invalid size?
break;
}
_Data = new wchar_t[_Length+1];
size_t j;
for (j=0, i=0; i<UTF8string.length(); j++) {
uint8 lead = static_cast<uint8>(UTF8string[i]);
if (lead < 0x80) {
_Data[j] = lead;
i++;
} else if ((lead >> 5) == 0x6) {
_Data[j] = ((lead & 0x1F) << 6) + (UTF8string[i+1] & 0x3F);
i += 2;
} else if ((lead >> 4) == 0xe) {
_Data[j] = ((lead & 0x0F) << 12) + ((UTF8string[i+1] & 0x3F) << 6) + (UTF8string[i+2] & 0x3F);
i += 3;
} else if ((lead >> 3) == 0x1e) {
_Data[j] = ((lead & 0x07) << 18) + ((UTF8string[i+1] & 0x3F) << 12) + ((UTF8string[i+2] & 0x3F) << 6) + (UTF8string[i+3] & 0x3F);
i += 4;
} else
// Invalid char?
break;
}
_Data[j] = 0;
} | CWE-200 | 10 |
void RemoteFsDevice::load()
{
if (RemoteFsDevice::constSambaAvahiProtocol==details.url.scheme()) {
// Start Avahi listener...
Avahi::self();
QUrlQuery q(details.url);
if (q.hasQueryItem(constServiceNameQuery)) {
details.serviceName=q.queryItemValue(constServiceNameQuery);
}
if (!details.serviceName.isEmpty()) {
AvahiService *srv=Avahi::self()->getService(details.serviceName);
if (!srv || srv->getHost().isEmpty()) {
sub=tr("Not Available");
} else {
sub=tr("Available");
}
}
connect(Avahi::self(), SIGNAL(serviceAdded(QString)), SLOT(serviceAdded(QString)));
connect(Avahi::self(), SIGNAL(serviceRemoved(QString)), SLOT(serviceRemoved(QString)));
}
if (isConnected()) {
setAudioFolder();
readOpts(settingsFileName(), opts, true);
rescan(false); // Read from cache if we have it!
}
} | CWE-20 | 0 |
ECDSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,
const std::string& params,
const std::string& provider) const
{
#if defined(BOTAN_HAS_BEARSSL)
if(provider == "bearssl" || provider.empty())
{
try
{
return make_bearssl_ecdsa_sig_op(*this, params);
}
catch(Lookup_Error& e)
{
if(provider == "bearssl")
throw;
}
}
#endif
#if defined(BOTAN_HAS_OPENSSL)
if(provider == "openssl" || provider.empty())
{
try
{
return make_openssl_ecdsa_sig_op(*this, params);
}
catch(Lookup_Error& e)
{
if(provider == "openssl")
throw;
}
}
#endif
if(provider == "base" || provider.empty())
return std::unique_ptr<PK_Ops::Signature>(new ECDSA_Signature_Operation(*this, params));
throw Provider_Not_Found(algo_name(), provider);
} | CWE-200 | 10 |
RemoteDevicePropertiesWidget::RemoteDevicePropertiesWidget(QWidget *parent)
: QWidget(parent)
, modified(false)
, saveable(false)
{
setupUi(this);
if (qobject_cast<QTabWidget *>(parent)) {
verticalLayout->setMargin(4);
}
type->addItem(tr("Samba Share"), (int)Type_Samba);
type->addItem(tr("Samba Share (Auto-discover host and port)"), (int)Type_SambaAvahi);
type->addItem(tr("Secure Shell (sshfs)"), (int)Type_SshFs);
type->addItem(tr("Locally Mounted Folder"), (int)Type_File);
} | CWE-20 | 0 |
int CephxSessionHandler::_calc_signature(Message *m, uint64_t *psig)
{
const ceph_msg_header& header = m->get_header();
const ceph_msg_footer& footer = m->get_footer();
// optimized signature calculation
// - avoid temporary allocated buffers from encode_encrypt[_enc_bl]
// - skip the leading 4 byte wrapper from encode_encrypt
struct {
__u8 v;
__le64 magic;
__le32 len;
__le32 header_crc;
__le32 front_crc;
__le32 middle_crc;
__le32 data_crc;
} __attribute__ ((packed)) sigblock = {
1, mswab(AUTH_ENC_MAGIC), mswab<uint32_t>(4*4),
mswab<uint32_t>(header.crc), mswab<uint32_t>(footer.front_crc),
mswab<uint32_t>(footer.middle_crc), mswab<uint32_t>(footer.data_crc)
};
char exp_buf[CryptoKey::get_max_outbuf_size(sizeof(sigblock))];
try {
const CryptoKey::in_slice_t in {
sizeof(sigblock),
reinterpret_cast<const unsigned char*>(&sigblock)
};
const CryptoKey::out_slice_t out {
sizeof(exp_buf),
reinterpret_cast<unsigned char*>(&exp_buf)
};
key.encrypt(cct, in, out);
} catch (std::exception& e) {
lderr(cct) << __func__ << " failed to encrypt signature block" << dendl;
return -1;
}
*psig = *reinterpret_cast<__le64*>(exp_buf);
ldout(cct, 10) << __func__ << " seq " << m->get_seq()
<< " front_crc_ = " << footer.front_crc
<< " middle_crc = " << footer.middle_crc
<< " data_crc = " << footer.data_crc
<< " sig = " << *psig
<< dendl;
return 0;
} | CWE-287 | 4 |
error_t coapServerInitResponse(CoapServerContext *context)
{
CoapMessageHeader *requestHeader;
CoapMessageHeader *responseHeader;
//Point to the CoAP request header
requestHeader = (CoapMessageHeader *) context->request.buffer;
//Point to the CoAP response header
responseHeader = (CoapMessageHeader *) context->response.buffer;
//Format message header
responseHeader->version = COAP_VERSION_1;
responseHeader->tokenLen = requestHeader->tokenLen;
responseHeader->code = COAP_CODE_INTERNAL_SERVER;
responseHeader->mid = requestHeader->mid;
//If immediately available, the response to a request carried in a
//Confirmable message is carried in an Acknowledgement (ACK) message
if(requestHeader->type == COAP_TYPE_CON)
{
responseHeader->type = COAP_TYPE_ACK;
}
else
{
responseHeader->type = COAP_TYPE_NON;
}
//The token is used to match a response with a request
osMemcpy(responseHeader->token, requestHeader->token,
requestHeader->tokenLen);
//Set the length of the CoAP message
context->response.length = sizeof(CoapMessageHeader) + responseHeader->tokenLen;
context->response.pos = 0;
//Sucessful processing
return NO_ERROR;
} | CWE-20 | 0 |
void RemoteFsDevice::serviceRemoved(const QString &name)
{
if (name==details.serviceName && constSambaAvahiProtocol==details.url.scheme()) {
sub=tr("Not Available");
updateStatus();
}
} | CWE-20 | 0 |
static void HeaderMapImplGetByteSize(benchmark::State& state) {
HeaderMapImpl headers;
addDummyHeaders(headers, state.range(0));
uint64_t size = 0;
for (auto _ : state) {
size += headers.byteSize();
}
benchmark::DoNotOptimize(size);
} | CWE-400 | 2 |
v8::Local<v8::Object> CreateNativeEvent(
v8::Isolate* isolate,
v8::Local<v8::Object> sender,
content::RenderFrameHost* frame,
electron::mojom::ElectronBrowser::MessageSyncCallback callback) {
v8::Local<v8::Object> event;
if (frame && callback) {
gin::Handle<Event> native_event = Event::Create(isolate);
native_event->SetCallback(std::move(callback));
event = v8::Local<v8::Object>::Cast(native_event.ToV8());
} else {
// No need to create native event if we do not need to send reply.
event = CreateEvent(isolate);
}
Dictionary dict(isolate, event);
dict.Set("sender", sender);
// Should always set frameId even when callback is null.
if (frame)
dict.Set("frameId", frame->GetRoutingID());
return event;
} | CWE-668 | 7 |
void CarbonProtocolReader::skip(const FieldType ft) {
switch (ft) {
case FieldType::True:
case FieldType::False: {
break;
}
case FieldType::Int8: {
readRaw<int8_t>();
break;
}
case FieldType::Int16: {
readRaw<int16_t>();
break;
}
case FieldType::Int32: {
readRaw<int32_t>();
break;
}
case FieldType::Int64: {
readRaw<int64_t>();
break;
}
case FieldType::Double: {
readRaw<double>();
break;
}
case FieldType::Float: {
readRaw<float>();
break;
}
case FieldType::Binary: {
readRaw<std::string>();
break;
}
case FieldType::List: {
skipLinearContainer();
break;
}
case FieldType::Struct: {
readStructBegin();
while (true) {
const auto fieldType = readFieldHeader().first;
if (fieldType == FieldType::Stop) {
break;
}
skip(fieldType);
}
readStructEnd();
break;
}
case FieldType::Set: {
skipLinearContainer();
break;
}
case FieldType::Map: {
skipKVContainer();
break;
}
default: { break; }
}
} | CWE-674 | 28 |
void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval,
jas_seqent_t maxval)
{
int i;
int j;
jas_seqent_t v;
jas_seqent_t *rowstart;
jas_seqent_t *data;
int rowstep;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
data = rowstart;
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
v = *data;
if (v < minval) {
*data = minval;
} else if (v > maxval) {
*data = maxval;
}
}
}
}
} | CWE-20 | 0 |
TEST_F(RouterTest, MissingRequiredHeaders) {
NiceMock<Http::MockRequestEncoder> encoder;
Http::ResponseDecoder* response_decoder = nullptr;
expectNewStreamWithImmediateEncoder(encoder, &response_decoder, Http::Protocol::Http10);
expectResponseTimerCreate();
Http::TestRequestHeaderMapImpl headers;
HttpTestUtility::addDefaultHeaders(headers);
headers.removeMethod();
EXPECT_CALL(encoder, encodeHeaders(_, _))
.WillOnce(Invoke([](const Http::RequestHeaderMap& headers, bool) -> Http::Status {
return Http::HeaderUtility::checkRequiredRequestHeaders(headers);
}));
EXPECT_CALL(
callbacks_,
sendLocalReply(Http::Code::ServiceUnavailable,
testing::Eq("missing required header: :method"), _, _,
"filter_removed_required_request_headers{missing_required_header:_:method}"))
.WillOnce(testing::InvokeWithoutArgs([] {}));
router_.decodeHeaders(headers, true);
router_.onDestroy();
} | CWE-670 | 36 |
void jas_matrix_asl(jas_matrix_t *matrix, int n)
{
int i;
int j;
jas_seqent_t *rowstart;
int rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
//*data <<= n;
*data = jas_seqent_asl(*data, n);
}
}
}
} | CWE-20 | 0 |
static void setAppend(SetType& set, const VariantType& v) {
auto value_type = type(v);
if (value_type != HPHP::serialize::Type::INT64 &&
value_type != HPHP::serialize::Type::STRING) {
throw HPHP::serialize::UnserializeError(
"Unsupported keyset element of type " +
folly::to<std::string>(value_type));
}
set.append(v);
} | CWE-674 | 28 |
void RemoteFsDevice::serviceAdded(const QString &name)
{
if (name==details.serviceName && constSambaAvahiProtocol==details.url.scheme()) {
sub=tr("Available");
updateStatus();
}
} | CWE-20 | 0 |
inline typename V::SetType FBUnserializer<V>::unserializeSet() {
p_ += CODE_SIZE;
// the set size is written so we can reserve it in the set
// in future. Skip past it for now.
unserializeInt64();
typename V::SetType ret = V::createSet();
size_t code = nextCode();
while (code != FB_SERIALIZE_STOP) {
V::setAppend(ret, unserializeThing());
code = nextCode();
}
p_ += CODE_SIZE;
return ret;
} | CWE-674 | 28 |
R_API RBinJavaAnnotation *r_bin_java_annotation_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaAnnotation *annotation = NULL;
RBinJavaElementValuePair *evps = NULL;
ut64 offset = 0;
annotation = R_NEW0 (RBinJavaAnnotation);
if (!annotation) {
return NULL;
}
// (ut16) read and set annotation_value.type_idx;
annotation->type_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
// (ut16) read and set annotation_value.num_element_value_pairs;
annotation->num_element_value_pairs = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
annotation->element_value_pairs = r_list_newf (r_bin_java_element_pair_free);
// read annotation_value.num_element_value_pairs, and append to annotation_value.element_value_pairs
for (i = 0; i < annotation->num_element_value_pairs; i++) {
if (offset > sz) {
break;
}
evps = r_bin_java_element_pair_new (buffer + offset, sz - offset, buf_offset + offset);
if (evps) {
offset += evps->size;
r_list_append (annotation->element_value_pairs, (void *) evps);
}
}
annotation->size = offset;
return annotation;
} | CWE-119 | 26 |
void Phase2() final {
Local<Context> context_handle = Deref(context);
Context::Scope context_scope{context_handle};
Local<Object> object = Local<Object>::Cast(Deref(reference));
result = Unmaybe(object->Delete(context_handle, key->CopyInto()));
} | CWE-913 | 24 |
boost::int64_t lazy_entry::int_value() const
{
TORRENT_ASSERT(m_type == int_t);
boost::int64_t val = 0;
bool negative = false;
if (*m_data.start == '-') negative = true;
parse_int(negative?m_data.start+1:m_data.start, m_data.start + m_size, 'e', val);
if (negative) val = -val;
return val;
} | CWE-119 | 26 |
void RemoteDevicePropertiesWidget::setType()
{
if (Type_SshFs==type->itemData(type->currentIndex()).toInt() && 0==sshPort->value()) {
sshPort->setValue(22);
}
if (Type_Samba==type->itemData(type->currentIndex()).toInt() && 0==smbPort->value()) {
smbPort->setValue(445);
}
} | CWE-20 | 0 |
set<int> PipeSocketHandler::listen(const SocketEndpoint& endpoint) {
lock_guard<std::recursive_mutex> guard(globalMutex);
string pipePath = endpoint.name();
if (pipeServerSockets.find(pipePath) != pipeServerSockets.end()) {
throw runtime_error("Tried to listen twice on the same path");
}
sockaddr_un local;
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
FATAL_FAIL(fd);
initServerSocket(fd);
local.sun_family = AF_UNIX; /* local is declared before socket() ^ */
strcpy(local.sun_path, pipePath.c_str());
unlink(local.sun_path);
FATAL_FAIL(::bind(fd, (struct sockaddr*)&local, sizeof(sockaddr_un)));
::listen(fd, 5);
#ifndef WIN32
FATAL_FAIL(::chmod(local.sun_path, S_IRUSR | S_IWUSR | S_IXUSR));
#endif
pipeServerSockets[pipePath] = set<int>({fd});
return pipeServerSockets[pipePath];
} | CWE-362 | 18 |
int ConnectionImpl::saveHeader(const nghttp2_frame* frame, HeaderString&& name,
HeaderString&& value) {
StreamImpl* stream = getStream(frame->hd.stream_id);
if (!stream) {
// We have seen 1 or 2 crashes where we get a headers callback but there is no associated
// stream data. I honestly am not sure how this can happen. However, from reading the nghttp2
// code it looks possible that inflate_header_block() can safely inflate headers for an already
// closed stream, but will still call the headers callback. Since that seems possible, we should
// ignore this case here.
// TODO(mattklein123): Figure out a test case that can hit this.
stats_.headers_cb_no_stream_.inc();
return 0;
}
stream->saveHeader(std::move(name), std::move(value));
if (stream->headers_->byteSize() > max_request_headers_kb_ * 1024) {
// This will cause the library to reset/close the stream.
stats_.header_overflow_.inc();
return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
} else {
return 0;
}
} | CWE-400 | 2 |
CmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE
{
size_t origin = parameters.size() > 1 ? 1 : 0;
if (parameters[origin].empty())
{
user->WriteNumeric(ERR_NOORIGIN, "No origin specified");
return CMD_FAILURE;
}
ClientProtocol::Messages::Pong pong(parameters[0], origin ? parameters[1] : "");
user->Send(ServerInstance->GetRFCEvents().pong, pong);
return CMD_SUCCESS;
} | CWE-732 | 13 |
static int emulate_store_desc_ptr(struct x86_emulate_ctxt *ctxt,
void (*get)(struct x86_emulate_ctxt *ctxt,
struct desc_ptr *ptr))
{
struct desc_ptr desc_ptr;
if (ctxt->mode == X86EMUL_MODE_PROT64)
ctxt->op_bytes = 8;
get(ctxt, &desc_ptr);
if (ctxt->op_bytes == 2) {
ctxt->op_bytes = 4;
desc_ptr.address &= 0x00ffffff;
}
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return segmented_write(ctxt, ctxt->dst.addr.mem,
&desc_ptr, 2 + ctxt->op_bytes);
} | CWE-200 | 10 |
R_API ut64 r_bin_java_element_pair_calc_size(RBinJavaElementValuePair *evp) {
ut64 sz = 0;
if (evp == NULL) {
return sz;
}
// evp->element_name_idx = r_bin_java_read_short(bin, bin->b->cur);
sz += 2;
// evp->value = r_bin_java_element_value_new (bin, offset+2);
if (evp->value) {
sz += r_bin_java_element_value_calc_size (evp->value);
}
return sz;
} | CWE-119 | 26 |
cosine_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr,
Buffer *buf, int *err, gchar **err_info)
{
int pkt_len;
char line[COSINE_LINE_LENGTH];
if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
return FALSE;
if (file_gets(line, COSINE_LINE_LENGTH, wth->random_fh) == NULL) {
*err = file_error(wth->random_fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Parse the header */
pkt_len = parse_cosine_rec_hdr(phdr, line, err, err_info);
if (pkt_len == -1)
return FALSE;
/* Convert the ASCII hex dump to binary data */
return parse_cosine_hex_dump(wth->random_fh, phdr, pkt_len, buf, err,
err_info);
} | CWE-119 | 26 |
int my_redel(const char *org_name, const char *tmp_name,
time_t backup_time_stamp, myf MyFlags)
{
int error=1;
DBUG_ENTER("my_redel");
DBUG_PRINT("my",("org_name: '%s' tmp_name: '%s' MyFlags: %d",
org_name,tmp_name,MyFlags));
if (my_copystat(org_name,tmp_name,MyFlags) < 0)
goto end;
if (MyFlags & MY_REDEL_MAKE_BACKUP)
{
char name_buff[FN_REFLEN + MY_BACKUP_NAME_EXTRA_LENGTH];
my_create_backup_name(name_buff, org_name, backup_time_stamp);
if (my_rename(org_name, name_buff, MyFlags))
goto end;
}
else if (my_delete(org_name, MyFlags))
goto end;
if (my_rename(tmp_name,org_name,MyFlags))
goto end;
error=0;
end:
DBUG_RETURN(error);
} /* my_redel */ | CWE-362 | 18 |
static port::StatusOr<CudnnRnnSequenceTensorDescriptor> Create(
GpuExecutor* parent, int max_seq_length, int batch_size, int data_size,
const absl::Span<const int>& seq_lengths, bool time_major,
cudnnDataType_t data_type) {
CHECK_GT(max_seq_length, 0);
int dims[] = {batch_size, data_size, 1};
int strides[] = {dims[1] * dims[2], dims[2], 1};
TensorDescriptor tensor_desc = CreateTensorDescriptor();
RETURN_IF_CUDNN_ERROR(cudnnSetTensorNdDescriptor(
/*tensorDesc=*/tensor_desc.get(), /*dataType=*/data_type,
/*nbDims=*/sizeof(dims) / sizeof(dims[0]), /*dimA=*/dims,
/*strideA=*/strides));
const int* seq_lengths_array = seq_lengths.data();
RNNDataDescriptor data_desc = CreateRNNDataDescriptor();
float padding_fill = 0.0f;
cudnnRNNDataLayout_t layout;
if (time_major) {
layout = CUDNN_RNN_DATA_LAYOUT_SEQ_MAJOR_UNPACKED;
} else {
layout = CUDNN_RNN_DATA_LAYOUT_BATCH_MAJOR_UNPACKED;
}
RETURN_IF_CUDNN_ERROR(cudnnSetRNNDataDescriptor(
/*RNNDataDesc=*/data_desc.get(), /*dataType*/ data_type,
/*layout=*/layout,
/*maxSeqLength=*/max_seq_length,
/*batchSize=*/batch_size, /*vectorSize=*/data_size,
/*seqLengthArray=*/seq_lengths_array,
/*paddingFill*/ (void*)&padding_fill));
return CudnnRnnSequenceTensorDescriptor(
parent, max_seq_length, batch_size, data_size, data_type,
std::move(data_desc), std::move(tensor_desc));
} | CWE-20 | 0 |
static int em_jmp_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned short sel, old_sel;
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
u8 cpl = ctxt->ops->cpl(ctxt);
/* Assignment of RIP may only fail in 64-bit mode */
if (ctxt->mode == X86EMUL_MODE_PROT64)
ops->get_segment(ctxt, &old_sel, &old_desc, NULL,
VCPU_SREG_CS);
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl,
X86_TRANSFER_CALL_JMP,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_far(ctxt, ctxt->src.val, &new_desc);
if (rc != X86EMUL_CONTINUE) {
WARN_ON(ctxt->mode != X86EMUL_MODE_PROT64);
/* assigning eip failed; restore the old cs */
ops->set_segment(ctxt, old_sel, &old_desc, 0, VCPU_SREG_CS);
return rc;
}
return rc;
} | CWE-200 | 10 |
RemoteFsDevice::RemoteFsDevice(MusicLibraryModel *m, const DeviceOptions &options, const Details &d)
: FsDevice(m, d.name, createUdi(d.name))
, mountToken(0)
, currentMountStatus(false)
, details(d)
, proc(0)
, mounterIface(0)
, messageSent(false)
{
opts=options;
// details.path=Utils::fixPath(details.path);
load();
mount();
icn=MonoIcon::icon(details.isLocalFile()
? FontAwesome::foldero
: constSshfsProtocol==details.url.scheme()
? FontAwesome::linux_os
: FontAwesome::windows, Utils::monoIconColor());
} | CWE-20 | 0 |
auto Phase3() -> Local<Value> final {
return Boolean::New(Isolate::GetCurrent(), did_set);
} | CWE-913 | 24 |
void Init(void)
{
for(int i = 0;i < 19;i++) {
#ifdef DEBUG_QMCODER
char string[5] = "X0 ";
string[1] = (i / 10) + '0';
string[2] = (i % 10) + '0';
X[i].Init(string);
string[0] = 'M';
M[i].Init(string);
#else
X[i].Init();
M[i].Init();
#endif
}
} | CWE-119 | 26 |
R_API RBinJavaAttrInfo *r_bin_java_synthetic_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 0;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
if (!attr) {
return NULL;
}
offset += 6;
attr->type = R_BIN_JAVA_ATTR_TYPE_SYNTHETIC_ATTR;
attr->size = offset;
return attr;
} | CWE-119 | 26 |
IntegrationStreamDecoderPtr HttpIntegrationTest::sendRequestAndWaitForResponse(
const Http::TestHeaderMapImpl& request_headers, uint32_t request_body_size,
const Http::TestHeaderMapImpl& response_headers, uint32_t response_size, int upstream_index) {
ASSERT(codec_client_ != nullptr);
// Send the request to Envoy.
IntegrationStreamDecoderPtr response;
if (request_body_size) {
response = codec_client_->makeRequestWithBody(request_headers, request_body_size);
} else {
response = codec_client_->makeHeaderOnlyRequest(request_headers);
}
waitForNextUpstreamRequest(upstream_index);
// Send response headers, and end_stream if there is no response body.
upstream_request_->encodeHeaders(response_headers, response_size == 0);
// Send any response data, with end_stream true.
if (response_size) {
upstream_request_->encodeData(response_size, true);
}
// Wait for the response to be read by the codec client.
response->waitForEndStream();
return response;
} | CWE-400 | 2 |
ECDSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len,
RandomNumberGenerator& rng)
{
BigInt m(msg, msg_len, m_group.get_order_bits());
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
const BigInt k = generate_rfc6979_nonce(m_x, m_group.get_order(), m, m_rfc6979_hash);
#else
const BigInt k = m_group.random_scalar(rng);
#endif
const BigInt k_inv = m_group.inverse_mod_order(k);
const BigInt r = m_group.mod_order(
m_group.blinded_base_point_multiply_x(k, rng, m_ws));
const BigInt xrm = m_group.mod_order(m_group.multiply_mod_order(m_x, r) + m);
const BigInt s = m_group.multiply_mod_order(k_inv, xrm);
// With overwhelming probability, a bug rather than actual zero r/s
if(r.is_zero() || s.is_zero())
throw Internal_Error("During ECDSA signature generated zero r/s");
return BigInt::encode_fixed_length_int_pair(r, s, m_group.get_order_bytes());
} | CWE-200 | 10 |
R_API RBinJavaAttrInfo *r_bin_java_annotation_default_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 0;
RBinJavaAttrInfo *attr = NULL;
attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
offset += 6;
if (attr && sz >= offset) {
attr->type = R_BIN_JAVA_ATTR_TYPE_ANNOTATION_DEFAULT_ATTR;
attr->info.annotation_default_attr.default_value = r_bin_java_element_value_new (buffer + offset, sz - offset, buf_offset + offset);
if (attr->info.annotation_default_attr.default_value) {
offset += attr->info.annotation_default_attr.default_value->size;
}
}
r_bin_java_print_annotation_default_attr_summary (attr);
return attr;
} | CWE-119 | 26 |
parse_cosine_hex_dump(FILE_T fh, struct wtap_pkthdr *phdr, int pkt_len,
Buffer* buf, int *err, gchar **err_info)
{
guint8 *pd;
gchar line[COSINE_LINE_LENGTH];
int i, hex_lines, n, caplen = 0;
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, COSINE_MAX_PACKET_LEN);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (empty_line(line)) {
break;
}
if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers");
return FALSE;
}
caplen += n;
}
phdr->caplen = caplen;
return TRUE;
} | CWE-119 | 26 |
void* TFE_HandleToDLPack(TFE_TensorHandle* h, TF_Status* status) {
const Tensor* tensor = GetTensorFromHandle(h, status);
TF_DataType data_type = static_cast<TF_DataType>(tensor->dtype());
TensorReference tensor_ref(*tensor); // This will call buf_->Ref()
auto* tf_dlm_tensor_ctx = new TfDlManagedTensorCtx(tensor_ref);
tf_dlm_tensor_ctx->reference = tensor_ref;
DLManagedTensor* dlm_tensor = &tf_dlm_tensor_ctx->tensor;
dlm_tensor->manager_ctx = tf_dlm_tensor_ctx;
dlm_tensor->deleter = &DLManagedTensorDeleter;
dlm_tensor->dl_tensor.ctx = GetDlContext(h, status);
int ndim = tensor->dims();
dlm_tensor->dl_tensor.ndim = ndim;
dlm_tensor->dl_tensor.data = TFE_TensorHandleDevicePointer(h, status);
dlm_tensor->dl_tensor.dtype = GetDlDataType(data_type, status);
std::vector<int64_t>* shape_arr = &tf_dlm_tensor_ctx->shape;
std::vector<int64_t>* stride_arr = &tf_dlm_tensor_ctx->strides;
shape_arr->resize(ndim);
stride_arr->resize(ndim, 1);
for (int i = 0; i < ndim; i++) {
(*shape_arr)[i] = tensor->dim_size(i);
}
for (int i = ndim - 2; i >= 0; --i) {
(*stride_arr)[i] = (*shape_arr)[i + 1] * (*stride_arr)[i + 1];
}
dlm_tensor->dl_tensor.shape = &(*shape_arr)[0];
// There are two ways to represent compact row-major data
// 1) nullptr indicates tensor is compact and row-majored.
// 2) fill in the strides array as the real case for compact row-major data.
// Here we choose option 2, since some frameworks didn't handle the strides
// argument properly.
dlm_tensor->dl_tensor.strides = &(*stride_arr)[0];
dlm_tensor->dl_tensor.byte_offset =
0; // TF doesn't handle the strides and byte_offsets here
return static_cast<void*>(dlm_tensor);
} | CWE-20 | 0 |
mptctl_eventenable (unsigned long arg)
{
struct mpt_ioctl_eventenable __user *uarg = (void __user *) arg;
struct mpt_ioctl_eventenable karg;
MPT_ADAPTER *ioc;
int iocnum;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventenable))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_eventenable - "
"Unable to read in mpt_ioctl_eventenable struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_eventenable() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_eventenable called.\n",
ioc->name));
if (ioc->events == NULL) {
/* Have not yet allocated memory - do so now.
*/
int sz = MPTCTL_EVENT_LOG_SIZE * sizeof(MPT_IOCTL_EVENTS);
ioc->events = kzalloc(sz, GFP_KERNEL);
if (!ioc->events) {
printk(MYIOC_s_ERR_FMT
": ERROR - Insufficient memory to add adapter!\n",
ioc->name);
return -ENOMEM;
}
ioc->alloc_total += sz;
ioc->eventContext = 0;
}
/* Update the IOC event logging flag.
*/
ioc->eventTypes = karg.eventTypes;
return 0;
} | CWE-362 | 18 |
compat_mpt_command(struct file *filp, unsigned int cmd,
unsigned long arg)
{
struct mpt_ioctl_command32 karg32;
struct mpt_ioctl_command32 __user *uarg = (struct mpt_ioctl_command32 __user *) arg;
struct mpt_ioctl_command karg;
MPT_ADAPTER *iocp = NULL;
int iocnum, iocnumX;
int nonblock = (filp->f_flags & O_NONBLOCK);
int ret;
if (copy_from_user(&karg32, (char __user *)arg, sizeof(karg32)))
return -EFAULT;
/* Verify intended MPT adapter */
iocnumX = karg32.hdr.iocnum & 0xFF;
if (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||
(iocp == NULL)) {
printk(KERN_DEBUG MYNAM "::compat_mpt_command @%d - ioc%d not found!\n",
__LINE__, iocnumX);
return -ENODEV;
}
if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)
return ret;
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "compat_mpt_command() called\n",
iocp->name));
/* Copy data to karg */
karg.hdr.iocnum = karg32.hdr.iocnum;
karg.hdr.port = karg32.hdr.port;
karg.timeout = karg32.timeout;
karg.maxReplyBytes = karg32.maxReplyBytes;
karg.dataInSize = karg32.dataInSize;
karg.dataOutSize = karg32.dataOutSize;
karg.maxSenseBytes = karg32.maxSenseBytes;
karg.dataSgeOffset = karg32.dataSgeOffset;
karg.replyFrameBufPtr = (char __user *)(unsigned long)karg32.replyFrameBufPtr;
karg.dataInBufPtr = (char __user *)(unsigned long)karg32.dataInBufPtr;
karg.dataOutBufPtr = (char __user *)(unsigned long)karg32.dataOutBufPtr;
karg.senseDataPtr = (char __user *)(unsigned long)karg32.senseDataPtr;
/* Pass new structure to do_mpt_command
*/
ret = mptctl_do_mpt_command (karg, &uarg->MF);
mutex_unlock(&iocp->ioctl_cmds.mutex);
return ret;
} | CWE-362 | 18 |
std::shared_ptr<SQLiteDBInstance> getTestDBC() {
auto dbc = SQLiteDBManager::getUnique();
char* err = nullptr;
std::vector<std::string> queries = {
"CREATE TABLE test_table (username varchar(30) primary key, age int)",
"INSERT INTO test_table VALUES (\"mike\", 23)",
"INSERT INTO test_table VALUES (\"matt\", 24)"};
for (auto q : queries) {
sqlite3_exec(dbc->db(), q.c_str(), nullptr, nullptr, &err);
if (err != nullptr) {
throw std::domain_error(std::string("Cannot create testing DBC's db: ") +
err);
}
}
return dbc;
} | CWE-77 | 14 |
void RemoteFsDevice::unmount()
{
if (details.isLocalFile()) {
return;
}
if (!isConnected() || proc) {
return;
}
if (messageSent) {
return;
}
if (constSambaProtocol==details.url.scheme() || constSambaAvahiProtocol==details.url.scheme()) {
mounter()->umount(mountPoint(details, false), getpid());
setStatusMessage(tr("Disconnecting..."));
messageSent=true;
return;
}
QString cmd;
QStringList args;
if (!details.isLocalFile()) {
QString mp=mountPoint(details, false);
if (!mp.isEmpty()) {
cmd=Utils::findExe("fusermount");
if (!cmd.isEmpty()) {
args << QLatin1String("-u") << QLatin1String("-z") << mp;
} else {
emit error(tr("\"fusermount\" is not installed!"));
}
}
}
if (!cmd.isEmpty()) {
setStatusMessage(tr("Disconnecting..."));
proc=new QProcess(this);
proc->setProperty("unmount", true);
connect(proc, SIGNAL(finished(int)), SLOT(procFinished(int)));
proc->start(cmd, args, QIODevice::ReadOnly);
}
} | CWE-20 | 0 |
void HeaderMapImpl::appendToHeader(HeaderString& header, absl::string_view data) {
if (data.empty()) {
return;
}
if (!header.empty()) {
header.append(",", 1);
}
header.append(data.data(), data.size());
} | CWE-400 | 2 |
QPDFObjectHandle::parse(PointerHolder<InputSource> input,
std::string const& object_description,
QPDFTokenizer& tokenizer, bool& empty,
StringDecrypter* decrypter, QPDF* context)
{
return parseInternal(input, object_description, tokenizer, empty,
decrypter, context, false, false, false);
} | CWE-20 | 0 |
MpdCantataMounterInterface * RemoteFsDevice::mounter()
{
if (!mounterIface) {
if (!QDBusConnection::systemBus().interface()->isServiceRegistered(MpdCantataMounterInterface::staticInterfaceName())) {
QDBusConnection::systemBus().interface()->startService(MpdCantataMounterInterface::staticInterfaceName());
}
mounterIface=new MpdCantataMounterInterface(MpdCantataMounterInterface::staticInterfaceName(),
"/Mounter", QDBusConnection::systemBus(), this);
connect(mounterIface, SIGNAL(mountStatus(const QString &, int, int)), SLOT(mountStatus(const QString &, int, int)));
connect(mounterIface, SIGNAL(umountStatus(const QString &, int, int)), SLOT(umountStatus(const QString &, int, int)));
}
return mounterIface;
} | CWE-20 | 0 |
std::string get_wml_location(const std::string &filename, const std::string ¤t_dir)
{
DBG_FS << "Looking for '" << filename << "'." << std::endl;
assert(game_config::path.empty() == false);
std::string result;
if (filename.empty()) {
LOG_FS << " invalid filename" << std::endl;
return result;
}
if (filename.find("..") != std::string::npos) {
ERR_FS << "Illegal path '" << filename << "' (\"..\" not allowed)." << std::endl;
return result;
}
if (ends_with(filename, ".pbl")) {
ERR_FS << "Illegal path '" << filename << "' (.pbl files are not allowed)." << std::endl;
return result;
}
bool already_found = false;
if (filename[0] == '~')
{
// If the filename starts with '~', look in the user data directory.
result = get_user_data_dir() + "/data/" + filename.substr(1);
DBG_FS << " trying '" << result << "'" << std::endl;
already_found = file_exists(result) || is_directory(result);
}
else if (filename.size() >= 2 && filename[0] == '.' && filename[1] == '/')
{
// If the filename begins with a "./", look in the same directory
// as the file currently being preprocessed.
if (!current_dir.empty())
{
result = current_dir;
}
else
{
result = game_config::path;
}
result += filename.substr(2);
}
else if (!game_config::path.empty())
result = game_config::path + "/data/" + filename;
DBG_FS << " trying '" << result << "'" << std::endl;
if (result.empty() ||
(!already_found && !file_exists(result) && !is_directory(result)))
{
DBG_FS << " not found" << std::endl;
result.clear();
}
else
DBG_FS << " found: '" << result << "'" << std::endl;
return result;
} | CWE-200 | 10 |
MpdCantataMounterInterface * RemoteFsDevice::mounter()
{
if (!mounterIface) {
if (!QDBusConnection::systemBus().interface()->isServiceRegistered(MpdCantataMounterInterface::staticInterfaceName())) {
QDBusConnection::systemBus().interface()->startService(MpdCantataMounterInterface::staticInterfaceName());
}
mounterIface=new MpdCantataMounterInterface(MpdCantataMounterInterface::staticInterfaceName(),
"/Mounter", QDBusConnection::systemBus(), this);
connect(mounterIface, SIGNAL(mountStatus(const QString &, int, int)), SLOT(mountStatus(const QString &, int, int)));
connect(mounterIface, SIGNAL(umountStatus(const QString &, int, int)), SLOT(umountStatus(const QString &, int, int)));
}
return mounterIface;
} | CWE-20 | 0 |
int jas_seq2d_output(jas_matrix_t *matrix, FILE *out)
{
#define MAXLINELEN 80
int i;
int j;
jas_seqent_t x;
char buf[MAXLINELEN + 1];
char sbuf[MAXLINELEN + 1];
int n;
fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_seq2d_xstart(matrix),
jas_seq2d_ystart(matrix));
fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_matrix_numcols(matrix),
jas_matrix_numrows(matrix));
buf[0] = '\0';
for (i = 0; i < jas_matrix_numrows(matrix); ++i) {
for (j = 0; j < jas_matrix_numcols(matrix); ++j) {
x = jas_matrix_get(matrix, i, j);
sprintf(sbuf, "%s%4ld", (strlen(buf) > 0) ? " " : "",
JAS_CAST(long, x));
n = JAS_CAST(int, strlen(buf));
if (n + JAS_CAST(int, strlen(sbuf)) > MAXLINELEN) {
fputs(buf, out);
fputs("\n", out);
buf[0] = '\0';
}
strcat(buf, sbuf);
if (j == jas_matrix_numcols(matrix) - 1) {
fputs(buf, out);
fputs("\n", out);
buf[0] = '\0';
}
}
}
fputs(buf, out);
return 0;
} | CWE-20 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.