id stringlengths 27 31 | content stringlengths 14 287k | max_stars_repo_path stringlengths 52 57 |
|---|---|---|
crossvul-java_data_bad_4952_0 | /*****************************************************************************
* 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. *
* *
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* Patrick Niemeyer (pat@pat.net) *
* Author of Learning Java, O'Reilly & Associates *
* *
*****************************************************************************/
package bsh;
import java.lang.reflect.*;
import java.lang.reflect.InvocationHandler;
import java.io.*;
import java.util.Hashtable;
/**
XThis is a dynamically loaded extension which extends This.java and adds
support for the generalized interface proxy mechanism introduced in
JDK1.3. XThis allows bsh scripted objects to implement arbitrary
interfaces (be arbitrary event listener types).
Note: This module relies on new features of JDK1.3 and will not compile
with JDK1.2 or lower. For those environments simply do not compile this
class.
Eventually XThis should become simply This, but for backward compatibility
we will maintain This without requiring support for the proxy mechanism.
XThis stands for "eXtended This" (I had to call it something).
@see JThis See also JThis with explicit JFC support for compatibility.
@see This
*/
public class XThis extends This
{
/**
A cache of proxy interface handlers.
Currently just one per interface.
*/
Hashtable interfaces;
transient InvocationHandler invocationHandler = new Handler();
public XThis( NameSpace namespace, Interpreter declaringInterp ) {
super( namespace, declaringInterp );
}
public String toString() {
return "'this' reference (XThis) to Bsh object: " + namespace;
}
/**
Get dynamic proxy for interface, caching those it creates.
*/
public Object getInterface( Class clas )
{
return getInterface( new Class[] { clas } );
}
/**
Get dynamic proxy for interface, caching those it creates.
*/
public Object getInterface( Class [] ca )
{
if ( interfaces == null )
interfaces = new Hashtable();
// Make a hash of the interface hashcodes in order to cache them
int hash = 21;
for(int i=0; i<ca.length; i++)
hash *= ca[i].hashCode() + 3;
Object hashKey = new Integer(hash);
Object interf = interfaces.get( hashKey );
if ( interf == null )
{
ClassLoader classLoader = ca[0].getClassLoader(); // ?
interf = Proxy.newProxyInstance(
classLoader, ca, invocationHandler );
interfaces.put( hashKey, interf );
}
return interf;
}
/**
This is the invocation handler for the dynamic proxy.
<p>
Notes:
Inner class for the invocation handler seems to shield this unavailable
interface from JDK1.2 VM...
I don't understand this. JThis works just fine even if those
classes aren't there (doesn't it?) This class shouldn't be loaded
if an XThis isn't instantiated in NameSpace.java, should it?
*/
class Handler implements InvocationHandler
{
public Object invoke( Object proxy, Method method, Object[] args )
throws Throwable
{
try {
return invokeImpl( proxy, method, args );
} catch ( TargetError te ) {
// Unwrap target exception. If the interface declares that
// it throws the ex it will be delivered. If not it will be
// wrapped in an UndeclaredThrowable
throw te.getTarget();
} catch ( EvalError ee ) {
// Ease debugging...
// XThis.this refers to the enclosing class instance
if ( Interpreter.DEBUG )
Interpreter.debug( "EvalError in scripted interface: "
+ XThis.this.toString() + ": "+ ee );
throw ee;
}
}
public Object invokeImpl( Object proxy, Method method, Object[] args )
throws EvalError
{
String methodName = method.getName();
CallStack callstack = new CallStack( namespace );
/*
If equals() is not explicitly defined we must override the
default implemented by the This object protocol for scripted
object. To support XThis equals() must test for equality with
the generated proxy object, not the scripted bsh This object;
otherwise callers from outside in Java will not see a the
proxy object as equal to itself.
*/
BshMethod equalsMethod = null;
try {
equalsMethod = namespace.getMethod(
"equals", new Class [] { Object.class } );
} catch ( UtilEvalError e ) {/*leave null*/ }
if ( methodName.equals("equals" ) && equalsMethod == null ) {
Object obj = args[0];
return proxy == obj ? Boolean.TRUE : Boolean.FALSE;
}
/*
If toString() is not explicitly defined override the default
to show the proxy interfaces.
*/
BshMethod toStringMethod = null;
try {
toStringMethod =
namespace.getMethod( "toString", new Class [] { } );
} catch ( UtilEvalError e ) {/*leave null*/ }
if ( methodName.equals("toString" ) && toStringMethod == null)
{
Class [] ints = proxy.getClass().getInterfaces();
// XThis.this refers to the enclosing class instance
StringBuffer sb = new StringBuffer(
XThis.this.toString() + "\nimplements:" );
for(int i=0; i<ints.length; i++)
sb.append( " "+ ints[i].getName()
+ ((ints.length > 1)?",":"") );
return sb.toString();
}
Class [] paramTypes = method.getParameterTypes();
return Primitive.unwrap(
invokeMethod( methodName, Primitive.wrap(args, paramTypes) ) );
}
};
}
| ./CrossVul/dataset_final_sorted/CWE-19/java/bad_4952_0 |
crossvul-java_data_bad_4757_3 | package org.bouncycastle.math.raw;
import java.math.BigInteger;
import org.bouncycastle.util.Pack;
public abstract class Nat224
{
private static final long M = 0xFFFFFFFFL;
public static int add(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (y[4] & M);
z[4] = (int)c;
c >>>= 32;
c += (x[5] & M) + (y[5] & M);
z[5] = (int)c;
c >>>= 32;
c += (x[6] & M) + (y[6] & M);
z[6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int add(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
long c = 0;
c += (x[xOff + 0] & M) + (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (x[xOff + 1] & M) + (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (x[xOff + 2] & M) + (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (x[xOff + 3] & M) + (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
c += (x[xOff + 4] & M) + (y[yOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
c += (x[xOff + 5] & M) + (y[yOff + 5] & M);
z[zOff + 5] = (int)c;
c >>>= 32;
c += (x[xOff + 6] & M) + (y[yOff + 6] & M);
z[zOff + 6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addBothTo(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (y[4] & M) + (z[4] & M);
z[4] = (int)c;
c >>>= 32;
c += (x[5] & M) + (y[5] & M) + (z[5] & M);
z[5] = (int)c;
c >>>= 32;
c += (x[6] & M) + (y[6] & M) + (z[6] & M);
z[6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addBothTo(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
long c = 0;
c += (x[xOff + 0] & M) + (y[yOff + 0] & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (x[xOff + 1] & M) + (y[yOff + 1] & M) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (x[xOff + 2] & M) + (y[yOff + 2] & M) + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (x[xOff + 3] & M) + (y[yOff + 3] & M) + (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
c += (x[xOff + 4] & M) + (y[yOff + 4] & M) + (z[zOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
c += (x[xOff + 5] & M) + (y[yOff + 5] & M) + (z[zOff + 5] & M);
z[zOff + 5] = (int)c;
c >>>= 32;
c += (x[xOff + 6] & M) + (y[yOff + 6] & M) + (z[zOff + 6] & M);
z[zOff + 6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int[] z)
{
long c = 0;
c += (x[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (z[4] & M);
z[4] = (int)c;
c >>>= 32;
c += (x[5] & M) + (z[5] & M);
z[5] = (int)c;
c >>>= 32;
c += (x[6] & M) + (z[6] & M);
z[6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int xOff, int[] z, int zOff, int cIn)
{
long c = cIn & M;
c += (x[xOff + 0] & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (x[xOff + 1] & M) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (x[xOff + 2] & M) + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (x[xOff + 3] & M) + (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
c += (x[xOff + 4] & M) + (z[zOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
c += (x[xOff + 5] & M) + (z[zOff + 5] & M);
z[zOff + 5] = (int)c;
c >>>= 32;
c += (x[xOff + 6] & M) + (z[zOff + 6] & M);
z[zOff + 6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addToEachOther(int[] u, int uOff, int[] v, int vOff)
{
long c = 0;
c += (u[uOff + 0] & M) + (v[vOff + 0] & M);
u[uOff + 0] = (int)c;
v[vOff + 0] = (int)c;
c >>>= 32;
c += (u[uOff + 1] & M) + (v[vOff + 1] & M);
u[uOff + 1] = (int)c;
v[vOff + 1] = (int)c;
c >>>= 32;
c += (u[uOff + 2] & M) + (v[vOff + 2] & M);
u[uOff + 2] = (int)c;
v[vOff + 2] = (int)c;
c >>>= 32;
c += (u[uOff + 3] & M) + (v[vOff + 3] & M);
u[uOff + 3] = (int)c;
v[vOff + 3] = (int)c;
c >>>= 32;
c += (u[uOff + 4] & M) + (v[vOff + 4] & M);
u[uOff + 4] = (int)c;
v[vOff + 4] = (int)c;
c >>>= 32;
c += (u[uOff + 5] & M) + (v[vOff + 5] & M);
u[uOff + 5] = (int)c;
v[vOff + 5] = (int)c;
c >>>= 32;
c += (u[uOff + 6] & M) + (v[vOff + 6] & M);
u[uOff + 6] = (int)c;
v[vOff + 6] = (int)c;
c >>>= 32;
return (int)c;
}
public static void copy(int[] x, int[] z)
{
z[0] = x[0];
z[1] = x[1];
z[2] = x[2];
z[3] = x[3];
z[4] = x[4];
z[5] = x[5];
z[6] = x[6];
}
public static int[] create()
{
return new int[7];
}
public static int[] createExt()
{
return new int[14];
}
public static boolean diff(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
boolean pos = gte(x, xOff, y, yOff);
if (pos)
{
sub(x, xOff, y, yOff, z, zOff);
}
else
{
sub(y, yOff, x, xOff, z, zOff);
}
return pos;
}
public static boolean eq(int[] x, int[] y)
{
for (int i = 6; i >= 0; --i)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public static int[] fromBigInteger(BigInteger x)
{
if (x.signum() < 0 || x.bitLength() > 224)
{
throw new IllegalArgumentException();
}
int[] z = create();
int i = 0;
while (x.signum() != 0)
{
z[i++] = x.intValue();
x = x.shiftRight(32);
}
return z;
}
public static int getBit(int[] x, int bit)
{
if (bit == 0)
{
return x[0] & 1;
}
int w = bit >> 5;
if (w < 0 || w >= 7)
{
return 0;
}
int b = bit & 31;
return (x[w] >>> b) & 1;
}
public static boolean gte(int[] x, int[] y)
{
for (int i = 6; i >= 0; --i)
{
int x_i = x[i] ^ Integer.MIN_VALUE;
int y_i = y[i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean gte(int[] x, int xOff, int[] y, int yOff)
{
for (int i = 6; i >= 0; --i)
{
int x_i = x[xOff + i] ^ Integer.MIN_VALUE;
int y_i = y[yOff + i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean isOne(int[] x)
{
if (x[0] != 1)
{
return false;
}
for (int i = 1; i < 7; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static boolean isZero(int[] x)
{
for (int i = 0; i < 7; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static void mul(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
long y_4 = y[4] & M;
long y_5 = y[5] & M;
long y_6 = y[6] & M;
{
long c = 0, x_0 = x[0] & M;
c += x_0 * y_0;
zz[0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[3] = (int)c;
c >>>= 32;
c += x_0 * y_4;
zz[4] = (int)c;
c >>>= 32;
c += x_0 * y_5;
zz[5] = (int)c;
c >>>= 32;
c += x_0 * y_6;
zz[6] = (int)c;
c >>>= 32;
zz[7] = (int)c;
}
for (int i = 1; i < 7; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[i + 4] & M);
zz[i + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[i + 5] & M);
zz[i + 5] = (int)c;
c >>>= 32;
c += x_i * y_6 + (zz[i + 6] & M);
zz[i + 6] = (int)c;
c >>>= 32;
zz[i + 7] = (int)c;
}
}
public static void mul(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
long y_4 = y[yOff + 4] & M;
long y_5 = y[yOff + 5] & M;
long y_6 = y[yOff + 6] & M;
{
long c = 0, x_0 = x[xOff + 0] & M;
c += x_0 * y_0;
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_0 * y_4;
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += x_0 * y_5;
zz[zzOff + 5] = (int)c;
c >>>= 32;
c += x_0 * y_6;
zz[zzOff + 6] = (int)c;
c >>>= 32;
zz[zzOff + 7] = (int)c;
}
for (int i = 1; i < 7; ++i)
{
++zzOff;
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[zzOff + 5] & M);
zz[zzOff + 5] = (int)c;
c >>>= 32;
c += x_i * y_6 + (zz[zzOff + 6] & M);
zz[zzOff + 6] = (int)c;
c >>>= 32;
zz[zzOff + 7] = (int)c;
}
}
public static int mulAddTo(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
long y_4 = y[4] & M;
long y_5 = y[5] & M;
long y_6 = y[6] & M;
long zc = 0;
for (int i = 0; i < 7; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[i + 4] & M);
zz[i + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[i + 5] & M);
zz[i + 5] = (int)c;
c >>>= 32;
c += x_i * y_6 + (zz[i + 6] & M);
zz[i + 6] = (int)c;
c >>>= 32;
c += zc + (zz[i + 7] & M);
zz[i + 7] = (int)c;
zc = c >>> 32;
}
return (int)zc;
}
public static int mulAddTo(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
long y_4 = y[yOff + 4] & M;
long y_5 = y[yOff + 5] & M;
long y_6 = y[yOff + 6] & M;
long zc = 0;
for (int i = 0; i < 7; ++i)
{
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[zzOff + 5] & M);
zz[zzOff + 5] = (int)c;
c >>>= 32;
c += x_i * y_6 + (zz[zzOff + 6] & M);
zz[zzOff + 6] = (int)c;
c >>>= 32;
c += zc + (zz[zzOff + 7] & M);
zz[zzOff + 7] = (int)c;
zc = c >>> 32;
++zzOff;
}
return (int)zc;
}
public static long mul33Add(int w, int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
// assert w >>> 31 == 0;
long c = 0, wVal = w & M;
long x0 = x[xOff + 0] & M;
c += wVal * x0 + (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long x1 = x[xOff + 1] & M;
c += wVal * x1 + x0 + (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
long x2 = x[xOff + 2] & M;
c += wVal * x2 + x1 + (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
long x3 = x[xOff + 3] & M;
c += wVal * x3 + x2 + (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
long x4 = x[xOff + 4] & M;
c += wVal * x4 + x3 + (y[yOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
long x5 = x[xOff + 5] & M;
c += wVal * x5 + x4 + (y[yOff + 5] & M);
z[zOff + 5] = (int)c;
c >>>= 32;
long x6 = x[xOff + 6] & M;
c += wVal * x6 + x5 + (y[yOff + 6] & M);
z[zOff + 6] = (int)c;
c >>>= 32;
c += x6;
return c;
}
public static int mulByWord(int x, int[] z)
{
long c = 0, xVal = x & M;
c += xVal * (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += xVal * (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += xVal * (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += xVal * (z[3] & M);
z[3] = (int)c;
c >>>= 32;
c += xVal * (z[4] & M);
z[4] = (int)c;
c >>>= 32;
c += xVal * (z[5] & M);
z[5] = (int)c;
c >>>= 32;
c += xVal * (z[6] & M);
z[6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int mulByWordAddTo(int x, int[] y, int[] z)
{
long c = 0, xVal = x & M;
c += xVal * (z[0] & M) + (y[0] & M);
z[0] = (int)c;
c >>>= 32;
c += xVal * (z[1] & M) + (y[1] & M);
z[1] = (int)c;
c >>>= 32;
c += xVal * (z[2] & M) + (y[2] & M);
z[2] = (int)c;
c >>>= 32;
c += xVal * (z[3] & M) + (y[3] & M);
z[3] = (int)c;
c >>>= 32;
c += xVal * (z[4] & M) + (y[4] & M);
z[4] = (int)c;
c >>>= 32;
c += xVal * (z[5] & M) + (y[5] & M);
z[5] = (int)c;
c >>>= 32;
c += xVal * (z[6] & M) + (y[6] & M);
z[6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int mulWordAddTo(int x, int[] y, int yOff, int[] z, int zOff)
{
long c = 0, xVal = x & M;
c += xVal * (y[yOff + 0] & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += xVal * (y[yOff + 1] & M) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += xVal * (y[yOff + 2] & M) + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += xVal * (y[yOff + 3] & M) + (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
c += xVal * (y[yOff + 4] & M) + (z[zOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
c += xVal * (y[yOff + 5] & M) + (z[zOff + 5] & M);
z[zOff + 5] = (int)c;
c >>>= 32;
c += xVal * (y[yOff + 6] & M) + (z[zOff + 6] & M);
z[zOff + 6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int mul33DWordAdd(int x, long y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 3;
long c = 0, xVal = x & M;
long y00 = y & M;
c += xVal * y00 + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long y01 = y >>> 32;
c += xVal * y01 + y00 + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += y01 + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(7, z, zOff, 4);
}
public static int mul33WordAdd(int x, int y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 4;
long c = 0, xVal = x & M, yVal = y & M;
c += yVal * xVal + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += yVal + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(7, z, zOff, 3);
}
public static int mulWordDwordAdd(int x, long y, int[] z, int zOff)
{
// assert zOff <= 4;
long c = 0, xVal = x & M;
c += xVal * (y & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += xVal * (y >>> 32) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(7, z, zOff, 3);
}
public static int mulWord(int x, int[] y, int[] z, int zOff)
{
long c = 0, xVal = x & M;
int i = 0;
do
{
c += xVal * (y[i] & M);
z[zOff + i] = (int)c;
c >>>= 32;
}
while (++i < 7);
return (int)c;
}
public static void square(int[] x, int[] zz)
{
long x_0 = x[0] & M;
long zz_1;
int c = 0, w;
{
int i = 6, j = 14;
do
{
long xVal = (x[i--] & M);
long p = xVal * xVal;
zz[--j] = (c << 31) | (int)(p >>> 33);
zz[--j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[1] & M;
long zz_2 = zz[2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[2] & M;
long zz_3 = zz[3] & M;
long zz_4 = zz[4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[3] & M;
long zz_5 = zz[5] & M;
long zz_6 = zz[6] & M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_4 &= M;
zz_6 += zz_5 >>> 32;
zz_5 &= M;
}
long x_4 = x[4] & M;
long zz_7 = zz[7] & M;
long zz_8 = zz[8] & M;
{
zz_4 += x_4 * x_0;
w = (int)zz_4;
zz[4] = (w << 1) | c;
c = w >>> 31;
zz_5 += (zz_4 >>> 32) + x_4 * x_1;
zz_6 += (zz_5 >>> 32) + x_4 * x_2;
zz_5 &= M;
zz_7 += (zz_6 >>> 32) + x_4 * x_3;
zz_6 &= M;
zz_8 += zz_7 >>> 32;
zz_7 &= M;
}
long x_5 = x[5] & M;
long zz_9 = zz[9] & M;
long zz_10 = zz[10] & M;
{
zz_5 += x_5 * x_0;
w = (int)zz_5;
zz[5] = (w << 1) | c;
c = w >>> 31;
zz_6 += (zz_5 >>> 32) + x_5 * x_1;
zz_7 += (zz_6 >>> 32) + x_5 * x_2;
zz_6 &= M;
zz_8 += (zz_7 >>> 32) + x_5 * x_3;
zz_7 &= M;
zz_9 += (zz_8 >>> 32) + x_5 * x_4;
zz_8 &= M;
zz_10 += zz_9 >>> 32;
zz_9 &= M;
}
long x_6 = x[6] & M;
long zz_11 = zz[11] & M;
long zz_12 = zz[12] & M;
{
zz_6 += x_6 * x_0;
w = (int)zz_6;
zz[6] = (w << 1) | c;
c = w >>> 31;
zz_7 += (zz_6 >>> 32) + x_6 * x_1;
zz_8 += (zz_7 >>> 32) + x_6 * x_2;
zz_9 += (zz_8 >>> 32) + x_6 * x_3;
zz_10 += (zz_9 >>> 32) + x_6 * x_4;
zz_11 += (zz_10 >>> 32) + x_6 * x_5;
zz_12 += zz_11 >>> 32;
}
w = (int)zz_7;
zz[7] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_8;
zz[8] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_9;
zz[9] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_10;
zz[10] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_11;
zz[11] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_12;
zz[12] = (w << 1) | c;
c = w >>> 31;
w = zz[13] + (int)(zz_12 >> 32);
zz[13] = (w << 1) | c;
}
public static void square(int[] x, int xOff, int[] zz, int zzOff)
{
long x_0 = x[xOff + 0] & M;
long zz_1;
int c = 0, w;
{
int i = 6, j = 14;
do
{
long xVal = (x[xOff + i--] & M);
long p = xVal * xVal;
zz[zzOff + --j] = (c << 31) | (int)(p >>> 33);
zz[zzOff + --j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[zzOff + 0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[xOff + 1] & M;
long zz_2 = zz[zzOff + 2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[zzOff + 1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[xOff + 2] & M;
long zz_3 = zz[zzOff + 3] & M;
long zz_4 = zz[zzOff + 4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[zzOff + 2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[xOff + 3] & M;
long zz_5 = zz[zzOff + 5] & M;
long zz_6 = zz[zzOff + 6] & M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[zzOff + 3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_4 &= M;
zz_6 += zz_5 >>> 32;
zz_5 &= M;
}
long x_4 = x[xOff + 4] & M;
long zz_7 = zz[zzOff + 7] & M;
long zz_8 = zz[zzOff + 8] & M;
{
zz_4 += x_4 * x_0;
w = (int)zz_4;
zz[zzOff + 4] = (w << 1) | c;
c = w >>> 31;
zz_5 += (zz_4 >>> 32) + x_4 * x_1;
zz_6 += (zz_5 >>> 32) + x_4 * x_2;
zz_5 &= M;
zz_7 += (zz_6 >>> 32) + x_4 * x_3;
zz_6 &= M;
zz_8 += zz_7 >>> 32;
zz_7 &= M;
}
long x_5 = x[xOff + 5] & M;
long zz_9 = zz[zzOff + 9] & M;
long zz_10 = zz[zzOff + 10] & M;
{
zz_5 += x_5 * x_0;
w = (int)zz_5;
zz[zzOff + 5] = (w << 1) | c;
c = w >>> 31;
zz_6 += (zz_5 >>> 32) + x_5 * x_1;
zz_7 += (zz_6 >>> 32) + x_5 * x_2;
zz_6 &= M;
zz_8 += (zz_7 >>> 32) + x_5 * x_3;
zz_7 &= M;
zz_9 += (zz_8 >>> 32) + x_5 * x_4;
zz_8 &= M;
zz_10 += zz_9 >>> 32;
zz_9 &= M;
}
long x_6 = x[xOff + 6] & M;
long zz_11 = zz[zzOff + 11] & M;
long zz_12 = zz[zzOff + 12] & M;
{
zz_6 += x_6 * x_0;
w = (int)zz_6;
zz[zzOff + 6] = (w << 1) | c;
c = w >>> 31;
zz_7 += (zz_6 >>> 32) + x_6 * x_1;
zz_8 += (zz_7 >>> 32) + x_6 * x_2;
zz_9 += (zz_8 >>> 32) + x_6 * x_3;
zz_10 += (zz_9 >>> 32) + x_6 * x_4;
zz_11 += (zz_10 >>> 32) + x_6 * x_5;
zz_12 += zz_11 >>> 32;
}
w = (int)zz_7;
zz[zzOff + 7] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_8;
zz[zzOff + 8] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_9;
zz[zzOff + 9] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_10;
zz[zzOff + 10] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_11;
zz[zzOff + 11] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_12;
zz[zzOff + 12] = (w << 1) | c;
c = w >>> 31;
w = zz[zzOff + 13] + (int)(zz_12 >> 32);
zz[zzOff + 13] = (w << 1) | c;
}
public static int sub(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
c += (x[4] & M) - (y[4] & M);
z[4] = (int)c;
c >>= 32;
c += (x[5] & M) - (y[5] & M);
z[5] = (int)c;
c >>= 32;
c += (x[6] & M) - (y[6] & M);
z[6] = (int)c;
c >>= 32;
return (int)c;
}
public static int sub(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
long c = 0;
c += (x[xOff + 0] & M) - (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (x[xOff + 1] & M) - (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (x[xOff + 2] & M) - (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (x[xOff + 3] & M) - (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
c += (x[xOff + 4] & M) - (y[yOff + 4] & M);
z[zOff + 4] = (int)c;
c >>= 32;
c += (x[xOff + 5] & M) - (y[yOff + 5] & M);
z[zOff + 5] = (int)c;
c >>= 32;
c += (x[xOff + 6] & M) - (y[yOff + 6] & M);
z[zOff + 6] = (int)c;
c >>= 32;
return (int)c;
}
public static int subBothFrom(int[] x, int[] y, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
c += (z[4] & M) - (x[4] & M) - (y[4] & M);
z[4] = (int)c;
c >>= 32;
c += (z[5] & M) - (x[5] & M) - (y[5] & M);
z[5] = (int)c;
c >>= 32;
c += (z[6] & M) - (x[6] & M) - (y[6] & M);
z[6] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M);
z[3] = (int)c;
c >>= 32;
c += (z[4] & M) - (x[4] & M);
z[4] = (int)c;
c >>= 32;
c += (z[5] & M) - (x[5] & M);
z[5] = (int)c;
c >>= 32;
c += (z[6] & M) - (x[6] & M);
z[6] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int xOff, int[] z, int zOff)
{
long c = 0;
c += (z[zOff + 0] & M) - (x[xOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (z[zOff + 1] & M) - (x[xOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (z[zOff + 2] & M) - (x[xOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (z[zOff + 3] & M) - (x[xOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
c += (z[zOff + 4] & M) - (x[xOff + 4] & M);
z[zOff + 4] = (int)c;
c >>= 32;
c += (z[zOff + 5] & M) - (x[xOff + 5] & M);
z[zOff + 5] = (int)c;
c >>= 32;
c += (z[zOff + 6] & M) - (x[xOff + 6] & M);
z[zOff + 6] = (int)c;
c >>= 32;
return (int)c;
}
public static BigInteger toBigInteger(int[] x)
{
byte[] bs = new byte[28];
for (int i = 0; i < 7; ++i)
{
int x_i = x[i];
if (x_i != 0)
{
Pack.intToBigEndian(x_i, bs, (6 - i) << 2);
}
}
return new BigInteger(1, bs);
}
public static void zero(int[] z)
{
z[0] = 0;
z[1] = 0;
z[2] = 0;
z[3] = 0;
z[4] = 0;
z[5] = 0;
z[6] = 0;
}
}
| ./CrossVul/dataset_final_sorted/CWE-19/java/bad_4757_3 |
crossvul-java_data_good_4757_1 | package org.bouncycastle.math.raw;
import java.math.BigInteger;
import org.bouncycastle.util.Pack;
public abstract class Nat160
{
private static final long M = 0xFFFFFFFFL;
public static int add(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (y[4] & M);
z[4] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addBothTo(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (y[4] & M) + (z[4] & M);
z[4] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int[] z)
{
long c = 0;
c += (x[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (z[4] & M);
z[4] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int xOff, int[] z, int zOff, int cIn)
{
long c = cIn & M;
c += (x[xOff + 0] & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (x[xOff + 1] & M) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (x[xOff + 2] & M) + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (x[xOff + 3] & M) + (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
c += (x[xOff + 4] & M) + (z[zOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addToEachOther(int[] u, int uOff, int[] v, int vOff)
{
long c = 0;
c += (u[uOff + 0] & M) + (v[vOff + 0] & M);
u[uOff + 0] = (int)c;
v[vOff + 0] = (int)c;
c >>>= 32;
c += (u[uOff + 1] & M) + (v[vOff + 1] & M);
u[uOff + 1] = (int)c;
v[vOff + 1] = (int)c;
c >>>= 32;
c += (u[uOff + 2] & M) + (v[vOff + 2] & M);
u[uOff + 2] = (int)c;
v[vOff + 2] = (int)c;
c >>>= 32;
c += (u[uOff + 3] & M) + (v[vOff + 3] & M);
u[uOff + 3] = (int)c;
v[vOff + 3] = (int)c;
c >>>= 32;
c += (u[uOff + 4] & M) + (v[vOff + 4] & M);
u[uOff + 4] = (int)c;
v[vOff + 4] = (int)c;
c >>>= 32;
return (int)c;
}
public static void copy(int[] x, int[] z)
{
z[0] = x[0];
z[1] = x[1];
z[2] = x[2];
z[3] = x[3];
z[4] = x[4];
}
public static int[] create()
{
return new int[5];
}
public static int[] createExt()
{
return new int[10];
}
public static boolean diff(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
boolean pos = gte(x, xOff, y, yOff);
if (pos)
{
sub(x, xOff, y, yOff, z, zOff);
}
else
{
sub(y, yOff, x, xOff, z, zOff);
}
return pos;
}
public static boolean eq(int[] x, int[] y)
{
for (int i = 4; i >= 0; --i)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public static int[] fromBigInteger(BigInteger x)
{
if (x.signum() < 0 || x.bitLength() > 160)
{
throw new IllegalArgumentException();
}
int[] z = create();
int i = 0;
while (x.signum() != 0)
{
z[i++] = x.intValue();
x = x.shiftRight(32);
}
return z;
}
public static int getBit(int[] x, int bit)
{
if (bit == 0)
{
return x[0] & 1;
}
int w = bit >> 5;
if (w < 0 || w >= 5)
{
return 0;
}
int b = bit & 31;
return (x[w] >>> b) & 1;
}
public static boolean gte(int[] x, int[] y)
{
for (int i = 4; i >= 0; --i)
{
int x_i = x[i] ^ Integer.MIN_VALUE;
int y_i = y[i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean gte(int[] x, int xOff, int[] y, int yOff)
{
for (int i = 4; i >= 0; --i)
{
int x_i = x[xOff + i] ^ Integer.MIN_VALUE;
int y_i = y[yOff + i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean isOne(int[] x)
{
if (x[0] != 1)
{
return false;
}
for (int i = 1; i < 5; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static boolean isZero(int[] x)
{
for (int i = 0; i < 5; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static void mul(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
long y_4 = y[4] & M;
{
long c = 0, x_0 = x[0] & M;
c += x_0 * y_0;
zz[0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[3] = (int)c;
c >>>= 32;
c += x_0 * y_4;
zz[4] = (int)c;
c >>>= 32;
zz[5] = (int)c;
}
for (int i = 1; i < 5; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[i + 4] & M);
zz[i + 4] = (int)c;
c >>>= 32;
zz[i + 5] = (int)c;
}
}
public static void mul(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
long y_4 = y[yOff + 4] & M;
{
long c = 0, x_0 = x[xOff + 0] & M;
c += x_0 * y_0;
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_0 * y_4;
zz[zzOff + 4] = (int)c;
c >>>= 32;
zz[zzOff + 5] = (int)c;
}
for (int i = 1; i < 5; ++i)
{
++zzOff;
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
zz[zzOff + 5] = (int)c;
}
}
public static int mulAddTo(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
long y_4 = y[4] & M;
long zc = 0;
for (int i = 0; i < 5; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[i + 4] & M);
zz[i + 4] = (int)c;
c >>>= 32;
c += zc + (zz[i + 5] & M);
zz[i + 5] = (int)c;
zc = c >>> 32;
}
return (int)zc;
}
public static int mulAddTo(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
long y_4 = y[yOff + 4] & M;
long zc = 0;
for (int i = 0; i < 5; ++i)
{
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += zc + (zz[zzOff + 5] & M);
zz[zzOff + 5] = (int)c;
zc = c >>> 32;
++zzOff;
}
return (int)zc;
}
public static long mul33Add(int w, int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
// assert w >>> 31 == 0;
long c = 0, wVal = w & M;
long x0 = x[xOff + 0] & M;
c += wVal * x0 + (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long x1 = x[xOff + 1] & M;
c += wVal * x1 + x0 + (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
long x2 = x[xOff + 2] & M;
c += wVal * x2 + x1 + (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
long x3 = x[xOff + 3] & M;
c += wVal * x3 + x2 + (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
long x4 = x[xOff + 4] & M;
c += wVal * x4 + x3 + (y[yOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
c += x4;
return c;
}
public static int mulWordAddExt(int x, int[] yy, int yyOff, int[] zz, int zzOff)
{
// assert yyOff <= 5;
// assert zzOff <= 5;
long c = 0, xVal = x & M;
c += xVal * (yy[yyOff + 0] & M) + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 1] & M) + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 2] & M) + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 3] & M) + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 4] & M) + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
return (int)c;
}
public static int mul33DWordAdd(int x, long y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 1;
long c = 0, xVal = x & M;
long y00 = y & M;
c += xVal * y00 + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long y01 = y >>> 32;
c += xVal * y01 + y00 + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += y01 + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(5, z, zOff, 4);
}
public static int mul33WordAdd(int x, int y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 2;
long c = 0, xVal = x & M, yVal = y & M;
c += yVal * xVal + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += yVal + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(5, z, zOff, 3);
}
public static int mulWordDwordAdd(int x, long y, int[] z, int zOff)
{
// assert zOff <= 2;
long c = 0, xVal = x & M;
c += xVal * (y & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += xVal * (y >>> 32) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(5, z, zOff, 3);
}
public static int mulWordsAdd(int x, int y, int[] z, int zOff)
{
// assert zOff <= 3;
long c = 0, xVal = x & M, yVal = y & M;
c += yVal * xVal + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(5, z, zOff, 2);
}
public static int mulWord(int x, int[] y, int[] z, int zOff)
{
long c = 0, xVal = x & M;
int i = 0;
do
{
c += xVal * (y[i] & M);
z[zOff + i] = (int)c;
c >>>= 32;
}
while (++i < 5);
return (int)c;
}
public static void square(int[] x, int[] zz)
{
long x_0 = x[0] & M;
long zz_1;
int c = 0, w;
{
int i = 4, j = 10;
do
{
long xVal = (x[i--] & M);
long p = xVal * xVal;
zz[--j] = (c << 31) | (int)(p >>> 33);
zz[--j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[1] & M;
long zz_2 = zz[2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[2] & M;
long zz_3 = zz[3] & M;
long zz_4 = zz[4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[3] & M;
long zz_5 = (zz[5] & M) + (zz_4 >>> 32); zz_4 &= M;
long zz_6 = (zz[6] & M) + (zz_5 >>> 32); zz_5 &= M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_4 &= M;
zz_6 += zz_5 >>> 32;
zz_5 &= M;
}
long x_4 = x[4] & M;
long zz_7 = (zz[7] & M) + (zz_6 >>> 32); zz_6 &= M;
long zz_8 = (zz[8] & M) + (zz_7 >>> 32); zz_7 &= M;
{
zz_4 += x_4 * x_0;
w = (int)zz_4;
zz[4] = (w << 1) | c;
c = w >>> 31;
zz_5 += (zz_4 >>> 32) + x_4 * x_1;
zz_6 += (zz_5 >>> 32) + x_4 * x_2;
zz_7 += (zz_6 >>> 32) + x_4 * x_3;
zz_8 += zz_7 >>> 32;
}
w = (int)zz_5;
zz[5] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_6;
zz[6] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_7;
zz[7] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_8;
zz[8] = (w << 1) | c;
c = w >>> 31;
w = zz[9] + (int)(zz_8 >>> 32);
zz[9] = (w << 1) | c;
}
public static void square(int[] x, int xOff, int[] zz, int zzOff)
{
long x_0 = x[xOff + 0] & M;
long zz_1;
int c = 0, w;
{
int i = 4, j = 10;
do
{
long xVal = (x[xOff + i--] & M);
long p = xVal * xVal;
zz[zzOff + --j] = (c << 31) | (int)(p >>> 33);
zz[zzOff + --j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[zzOff + 0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[xOff + 1] & M;
long zz_2 = zz[zzOff + 2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[zzOff + 1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[xOff + 2] & M;
long zz_3 = zz[zzOff + 3] & M;
long zz_4 = zz[zzOff + 4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[zzOff + 2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[xOff + 3] & M;
long zz_5 = (zz[zzOff + 5] & M) + (zz_4 >>> 32); zz_4 &= M;
long zz_6 = (zz[zzOff + 6] & M) + (zz_5 >>> 32); zz_5 &= M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[zzOff + 3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_4 &= M;
zz_6 += zz_5 >>> 32;
zz_5 &= M;
}
long x_4 = x[xOff + 4] & M;
long zz_7 = (zz[zzOff + 7] & M) + (zz_6 >>> 32); zz_6 &= M;
long zz_8 = (zz[zzOff + 8] & M) + (zz_7 >>> 32); zz_7 &= M;
{
zz_4 += x_4 * x_0;
w = (int)zz_4;
zz[zzOff + 4] = (w << 1) | c;
c = w >>> 31;
zz_5 += (zz_4 >>> 32) + x_4 * x_1;
zz_6 += (zz_5 >>> 32) + x_4 * x_2;
zz_7 += (zz_6 >>> 32) + x_4 * x_3;
zz_8 += zz_7 >>> 32;
}
w = (int)zz_5;
zz[zzOff + 5] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_6;
zz[zzOff + 6] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_7;
zz[zzOff + 7] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_8;
zz[zzOff + 8] = (w << 1) | c;
c = w >>> 31;
w = zz[zzOff + 9] + (int)(zz_8 >>> 32);
zz[zzOff + 9] = (w << 1) | c;
}
public static int sub(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
c += (x[4] & M) - (y[4] & M);
z[4] = (int)c;
c >>= 32;
return (int)c;
}
public static int sub(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
long c = 0;
c += (x[xOff + 0] & M) - (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (x[xOff + 1] & M) - (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (x[xOff + 2] & M) - (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (x[xOff + 3] & M) - (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
c += (x[xOff + 4] & M) - (y[yOff + 4] & M);
z[zOff + 4] = (int)c;
c >>= 32;
return (int)c;
}
public static int subBothFrom(int[] x, int[] y, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
c += (z[4] & M) - (x[4] & M) - (y[4] & M);
z[4] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M);
z[3] = (int)c;
c >>= 32;
c += (z[4] & M) - (x[4] & M);
z[4] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int xOff, int[] z, int zOff)
{
long c = 0;
c += (z[zOff + 0] & M) - (x[xOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (z[zOff + 1] & M) - (x[xOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (z[zOff + 2] & M) - (x[xOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (z[zOff + 3] & M) - (x[xOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
c += (z[zOff + 4] & M) - (x[xOff + 4] & M);
z[zOff + 4] = (int)c;
c >>= 32;
return (int)c;
}
public static BigInteger toBigInteger(int[] x)
{
byte[] bs = new byte[20];
for (int i = 0; i < 5; ++i)
{
int x_i = x[i];
if (x_i != 0)
{
Pack.intToBigEndian(x_i, bs, (4 - i) << 2);
}
}
return new BigInteger(1, bs);
}
public static void zero(int[] z)
{
z[0] = 0;
z[1] = 0;
z[2] = 0;
z[3] = 0;
z[4] = 0;
}
}
| ./CrossVul/dataset_final_sorted/CWE-19/java/good_4757_1 |
crossvul-java_data_good_4757_3 | package org.bouncycastle.math.raw;
import java.math.BigInteger;
import org.bouncycastle.util.Pack;
public abstract class Nat224
{
private static final long M = 0xFFFFFFFFL;
public static int add(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (y[4] & M);
z[4] = (int)c;
c >>>= 32;
c += (x[5] & M) + (y[5] & M);
z[5] = (int)c;
c >>>= 32;
c += (x[6] & M) + (y[6] & M);
z[6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int add(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
long c = 0;
c += (x[xOff + 0] & M) + (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (x[xOff + 1] & M) + (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (x[xOff + 2] & M) + (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (x[xOff + 3] & M) + (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
c += (x[xOff + 4] & M) + (y[yOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
c += (x[xOff + 5] & M) + (y[yOff + 5] & M);
z[zOff + 5] = (int)c;
c >>>= 32;
c += (x[xOff + 6] & M) + (y[yOff + 6] & M);
z[zOff + 6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addBothTo(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (y[4] & M) + (z[4] & M);
z[4] = (int)c;
c >>>= 32;
c += (x[5] & M) + (y[5] & M) + (z[5] & M);
z[5] = (int)c;
c >>>= 32;
c += (x[6] & M) + (y[6] & M) + (z[6] & M);
z[6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addBothTo(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
long c = 0;
c += (x[xOff + 0] & M) + (y[yOff + 0] & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (x[xOff + 1] & M) + (y[yOff + 1] & M) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (x[xOff + 2] & M) + (y[yOff + 2] & M) + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (x[xOff + 3] & M) + (y[yOff + 3] & M) + (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
c += (x[xOff + 4] & M) + (y[yOff + 4] & M) + (z[zOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
c += (x[xOff + 5] & M) + (y[yOff + 5] & M) + (z[zOff + 5] & M);
z[zOff + 5] = (int)c;
c >>>= 32;
c += (x[xOff + 6] & M) + (y[yOff + 6] & M) + (z[zOff + 6] & M);
z[zOff + 6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int[] z)
{
long c = 0;
c += (x[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (z[4] & M);
z[4] = (int)c;
c >>>= 32;
c += (x[5] & M) + (z[5] & M);
z[5] = (int)c;
c >>>= 32;
c += (x[6] & M) + (z[6] & M);
z[6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int xOff, int[] z, int zOff, int cIn)
{
long c = cIn & M;
c += (x[xOff + 0] & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (x[xOff + 1] & M) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (x[xOff + 2] & M) + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (x[xOff + 3] & M) + (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
c += (x[xOff + 4] & M) + (z[zOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
c += (x[xOff + 5] & M) + (z[zOff + 5] & M);
z[zOff + 5] = (int)c;
c >>>= 32;
c += (x[xOff + 6] & M) + (z[zOff + 6] & M);
z[zOff + 6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addToEachOther(int[] u, int uOff, int[] v, int vOff)
{
long c = 0;
c += (u[uOff + 0] & M) + (v[vOff + 0] & M);
u[uOff + 0] = (int)c;
v[vOff + 0] = (int)c;
c >>>= 32;
c += (u[uOff + 1] & M) + (v[vOff + 1] & M);
u[uOff + 1] = (int)c;
v[vOff + 1] = (int)c;
c >>>= 32;
c += (u[uOff + 2] & M) + (v[vOff + 2] & M);
u[uOff + 2] = (int)c;
v[vOff + 2] = (int)c;
c >>>= 32;
c += (u[uOff + 3] & M) + (v[vOff + 3] & M);
u[uOff + 3] = (int)c;
v[vOff + 3] = (int)c;
c >>>= 32;
c += (u[uOff + 4] & M) + (v[vOff + 4] & M);
u[uOff + 4] = (int)c;
v[vOff + 4] = (int)c;
c >>>= 32;
c += (u[uOff + 5] & M) + (v[vOff + 5] & M);
u[uOff + 5] = (int)c;
v[vOff + 5] = (int)c;
c >>>= 32;
c += (u[uOff + 6] & M) + (v[vOff + 6] & M);
u[uOff + 6] = (int)c;
v[vOff + 6] = (int)c;
c >>>= 32;
return (int)c;
}
public static void copy(int[] x, int[] z)
{
z[0] = x[0];
z[1] = x[1];
z[2] = x[2];
z[3] = x[3];
z[4] = x[4];
z[5] = x[5];
z[6] = x[6];
}
public static int[] create()
{
return new int[7];
}
public static int[] createExt()
{
return new int[14];
}
public static boolean diff(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
boolean pos = gte(x, xOff, y, yOff);
if (pos)
{
sub(x, xOff, y, yOff, z, zOff);
}
else
{
sub(y, yOff, x, xOff, z, zOff);
}
return pos;
}
public static boolean eq(int[] x, int[] y)
{
for (int i = 6; i >= 0; --i)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public static int[] fromBigInteger(BigInteger x)
{
if (x.signum() < 0 || x.bitLength() > 224)
{
throw new IllegalArgumentException();
}
int[] z = create();
int i = 0;
while (x.signum() != 0)
{
z[i++] = x.intValue();
x = x.shiftRight(32);
}
return z;
}
public static int getBit(int[] x, int bit)
{
if (bit == 0)
{
return x[0] & 1;
}
int w = bit >> 5;
if (w < 0 || w >= 7)
{
return 0;
}
int b = bit & 31;
return (x[w] >>> b) & 1;
}
public static boolean gte(int[] x, int[] y)
{
for (int i = 6; i >= 0; --i)
{
int x_i = x[i] ^ Integer.MIN_VALUE;
int y_i = y[i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean gte(int[] x, int xOff, int[] y, int yOff)
{
for (int i = 6; i >= 0; --i)
{
int x_i = x[xOff + i] ^ Integer.MIN_VALUE;
int y_i = y[yOff + i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean isOne(int[] x)
{
if (x[0] != 1)
{
return false;
}
for (int i = 1; i < 7; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static boolean isZero(int[] x)
{
for (int i = 0; i < 7; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static void mul(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
long y_4 = y[4] & M;
long y_5 = y[5] & M;
long y_6 = y[6] & M;
{
long c = 0, x_0 = x[0] & M;
c += x_0 * y_0;
zz[0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[3] = (int)c;
c >>>= 32;
c += x_0 * y_4;
zz[4] = (int)c;
c >>>= 32;
c += x_0 * y_5;
zz[5] = (int)c;
c >>>= 32;
c += x_0 * y_6;
zz[6] = (int)c;
c >>>= 32;
zz[7] = (int)c;
}
for (int i = 1; i < 7; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[i + 4] & M);
zz[i + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[i + 5] & M);
zz[i + 5] = (int)c;
c >>>= 32;
c += x_i * y_6 + (zz[i + 6] & M);
zz[i + 6] = (int)c;
c >>>= 32;
zz[i + 7] = (int)c;
}
}
public static void mul(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
long y_4 = y[yOff + 4] & M;
long y_5 = y[yOff + 5] & M;
long y_6 = y[yOff + 6] & M;
{
long c = 0, x_0 = x[xOff + 0] & M;
c += x_0 * y_0;
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_0 * y_4;
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += x_0 * y_5;
zz[zzOff + 5] = (int)c;
c >>>= 32;
c += x_0 * y_6;
zz[zzOff + 6] = (int)c;
c >>>= 32;
zz[zzOff + 7] = (int)c;
}
for (int i = 1; i < 7; ++i)
{
++zzOff;
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[zzOff + 5] & M);
zz[zzOff + 5] = (int)c;
c >>>= 32;
c += x_i * y_6 + (zz[zzOff + 6] & M);
zz[zzOff + 6] = (int)c;
c >>>= 32;
zz[zzOff + 7] = (int)c;
}
}
public static int mulAddTo(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
long y_4 = y[4] & M;
long y_5 = y[5] & M;
long y_6 = y[6] & M;
long zc = 0;
for (int i = 0; i < 7; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[i + 4] & M);
zz[i + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[i + 5] & M);
zz[i + 5] = (int)c;
c >>>= 32;
c += x_i * y_6 + (zz[i + 6] & M);
zz[i + 6] = (int)c;
c >>>= 32;
c += zc + (zz[i + 7] & M);
zz[i + 7] = (int)c;
zc = c >>> 32;
}
return (int)zc;
}
public static int mulAddTo(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
long y_4 = y[yOff + 4] & M;
long y_5 = y[yOff + 5] & M;
long y_6 = y[yOff + 6] & M;
long zc = 0;
for (int i = 0; i < 7; ++i)
{
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[zzOff + 5] & M);
zz[zzOff + 5] = (int)c;
c >>>= 32;
c += x_i * y_6 + (zz[zzOff + 6] & M);
zz[zzOff + 6] = (int)c;
c >>>= 32;
c += zc + (zz[zzOff + 7] & M);
zz[zzOff + 7] = (int)c;
zc = c >>> 32;
++zzOff;
}
return (int)zc;
}
public static long mul33Add(int w, int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
// assert w >>> 31 == 0;
long c = 0, wVal = w & M;
long x0 = x[xOff + 0] & M;
c += wVal * x0 + (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long x1 = x[xOff + 1] & M;
c += wVal * x1 + x0 + (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
long x2 = x[xOff + 2] & M;
c += wVal * x2 + x1 + (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
long x3 = x[xOff + 3] & M;
c += wVal * x3 + x2 + (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
long x4 = x[xOff + 4] & M;
c += wVal * x4 + x3 + (y[yOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
long x5 = x[xOff + 5] & M;
c += wVal * x5 + x4 + (y[yOff + 5] & M);
z[zOff + 5] = (int)c;
c >>>= 32;
long x6 = x[xOff + 6] & M;
c += wVal * x6 + x5 + (y[yOff + 6] & M);
z[zOff + 6] = (int)c;
c >>>= 32;
c += x6;
return c;
}
public static int mulByWord(int x, int[] z)
{
long c = 0, xVal = x & M;
c += xVal * (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += xVal * (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += xVal * (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += xVal * (z[3] & M);
z[3] = (int)c;
c >>>= 32;
c += xVal * (z[4] & M);
z[4] = (int)c;
c >>>= 32;
c += xVal * (z[5] & M);
z[5] = (int)c;
c >>>= 32;
c += xVal * (z[6] & M);
z[6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int mulByWordAddTo(int x, int[] y, int[] z)
{
long c = 0, xVal = x & M;
c += xVal * (z[0] & M) + (y[0] & M);
z[0] = (int)c;
c >>>= 32;
c += xVal * (z[1] & M) + (y[1] & M);
z[1] = (int)c;
c >>>= 32;
c += xVal * (z[2] & M) + (y[2] & M);
z[2] = (int)c;
c >>>= 32;
c += xVal * (z[3] & M) + (y[3] & M);
z[3] = (int)c;
c >>>= 32;
c += xVal * (z[4] & M) + (y[4] & M);
z[4] = (int)c;
c >>>= 32;
c += xVal * (z[5] & M) + (y[5] & M);
z[5] = (int)c;
c >>>= 32;
c += xVal * (z[6] & M) + (y[6] & M);
z[6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int mulWordAddTo(int x, int[] y, int yOff, int[] z, int zOff)
{
long c = 0, xVal = x & M;
c += xVal * (y[yOff + 0] & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += xVal * (y[yOff + 1] & M) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += xVal * (y[yOff + 2] & M) + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += xVal * (y[yOff + 3] & M) + (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
c += xVal * (y[yOff + 4] & M) + (z[zOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
c += xVal * (y[yOff + 5] & M) + (z[zOff + 5] & M);
z[zOff + 5] = (int)c;
c >>>= 32;
c += xVal * (y[yOff + 6] & M) + (z[zOff + 6] & M);
z[zOff + 6] = (int)c;
c >>>= 32;
return (int)c;
}
public static int mul33DWordAdd(int x, long y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 3;
long c = 0, xVal = x & M;
long y00 = y & M;
c += xVal * y00 + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long y01 = y >>> 32;
c += xVal * y01 + y00 + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += y01 + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(7, z, zOff, 4);
}
public static int mul33WordAdd(int x, int y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 4;
long c = 0, xVal = x & M, yVal = y & M;
c += yVal * xVal + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += yVal + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(7, z, zOff, 3);
}
public static int mulWordDwordAdd(int x, long y, int[] z, int zOff)
{
// assert zOff <= 4;
long c = 0, xVal = x & M;
c += xVal * (y & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += xVal * (y >>> 32) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(7, z, zOff, 3);
}
public static int mulWord(int x, int[] y, int[] z, int zOff)
{
long c = 0, xVal = x & M;
int i = 0;
do
{
c += xVal * (y[i] & M);
z[zOff + i] = (int)c;
c >>>= 32;
}
while (++i < 7);
return (int)c;
}
public static void square(int[] x, int[] zz)
{
long x_0 = x[0] & M;
long zz_1;
int c = 0, w;
{
int i = 6, j = 14;
do
{
long xVal = (x[i--] & M);
long p = xVal * xVal;
zz[--j] = (c << 31) | (int)(p >>> 33);
zz[--j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[1] & M;
long zz_2 = zz[2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[2] & M;
long zz_3 = zz[3] & M;
long zz_4 = zz[4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[3] & M;
long zz_5 = (zz[5] & M) + (zz_4 >>> 32); zz_4 &= M;
long zz_6 = (zz[6] & M) + (zz_5 >>> 32); zz_5 &= M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_4 &= M;
zz_6 += zz_5 >>> 32;
zz_5 &= M;
}
long x_4 = x[4] & M;
long zz_7 = (zz[7] & M) + (zz_6 >>> 32); zz_6 &= M;
long zz_8 = (zz[8] & M) + (zz_7 >>> 32); zz_7 &= M;
{
zz_4 += x_4 * x_0;
w = (int)zz_4;
zz[4] = (w << 1) | c;
c = w >>> 31;
zz_5 += (zz_4 >>> 32) + x_4 * x_1;
zz_6 += (zz_5 >>> 32) + x_4 * x_2;
zz_5 &= M;
zz_7 += (zz_6 >>> 32) + x_4 * x_3;
zz_6 &= M;
zz_8 += zz_7 >>> 32;
zz_7 &= M;
}
long x_5 = x[5] & M;
long zz_9 = (zz[9] & M) + (zz_8 >>> 32); zz_8 &= M;
long zz_10 = (zz[10] & M) + (zz_9 >>> 32); zz_9 &= M;
{
zz_5 += x_5 * x_0;
w = (int)zz_5;
zz[5] = (w << 1) | c;
c = w >>> 31;
zz_6 += (zz_5 >>> 32) + x_5 * x_1;
zz_7 += (zz_6 >>> 32) + x_5 * x_2;
zz_6 &= M;
zz_8 += (zz_7 >>> 32) + x_5 * x_3;
zz_7 &= M;
zz_9 += (zz_8 >>> 32) + x_5 * x_4;
zz_8 &= M;
zz_10 += zz_9 >>> 32;
zz_9 &= M;
}
long x_6 = x[6] & M;
long zz_11 = (zz[11] & M) + (zz_10 >>> 32); zz_10 &= M;
long zz_12 = (zz[12] & M) + (zz_11 >>> 32); zz_11 &= M;
{
zz_6 += x_6 * x_0;
w = (int)zz_6;
zz[6] = (w << 1) | c;
c = w >>> 31;
zz_7 += (zz_6 >>> 32) + x_6 * x_1;
zz_8 += (zz_7 >>> 32) + x_6 * x_2;
zz_9 += (zz_8 >>> 32) + x_6 * x_3;
zz_10 += (zz_9 >>> 32) + x_6 * x_4;
zz_11 += (zz_10 >>> 32) + x_6 * x_5;
zz_12 += zz_11 >>> 32;
}
w = (int)zz_7;
zz[7] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_8;
zz[8] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_9;
zz[9] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_10;
zz[10] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_11;
zz[11] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_12;
zz[12] = (w << 1) | c;
c = w >>> 31;
w = zz[13] + (int)(zz_12 >>> 32);
zz[13] = (w << 1) | c;
}
public static void square(int[] x, int xOff, int[] zz, int zzOff)
{
long x_0 = x[xOff + 0] & M;
long zz_1;
int c = 0, w;
{
int i = 6, j = 14;
do
{
long xVal = (x[xOff + i--] & M);
long p = xVal * xVal;
zz[zzOff + --j] = (c << 31) | (int)(p >>> 33);
zz[zzOff + --j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[zzOff + 0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[xOff + 1] & M;
long zz_2 = zz[zzOff + 2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[zzOff + 1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[xOff + 2] & M;
long zz_3 = zz[zzOff + 3] & M;
long zz_4 = zz[zzOff + 4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[zzOff + 2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[xOff + 3] & M;
long zz_5 = (zz[zzOff + 5] & M) + (zz_4 >>> 32); zz_4 &= M;
long zz_6 = (zz[zzOff + 6] & M) + (zz_5 >>> 32); zz_5 &= M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[zzOff + 3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_4 &= M;
zz_6 += zz_5 >>> 32;
zz_5 &= M;
}
long x_4 = x[xOff + 4] & M;
long zz_7 = (zz[zzOff + 7] & M) + (zz_6 >>> 32); zz_6 &= M;
long zz_8 = (zz[zzOff + 8] & M) + (zz_7 >>> 32); zz_7 &= M;
{
zz_4 += x_4 * x_0;
w = (int)zz_4;
zz[zzOff + 4] = (w << 1) | c;
c = w >>> 31;
zz_5 += (zz_4 >>> 32) + x_4 * x_1;
zz_6 += (zz_5 >>> 32) + x_4 * x_2;
zz_5 &= M;
zz_7 += (zz_6 >>> 32) + x_4 * x_3;
zz_6 &= M;
zz_8 += zz_7 >>> 32;
zz_7 &= M;
}
long x_5 = x[xOff + 5] & M;
long zz_9 = (zz[zzOff + 9] & M) + (zz_8 >>> 32); zz_8 &= M;
long zz_10 = (zz[zzOff + 10] & M) + (zz_9 >>> 32); zz_9 &= M;
{
zz_5 += x_5 * x_0;
w = (int)zz_5;
zz[zzOff + 5] = (w << 1) | c;
c = w >>> 31;
zz_6 += (zz_5 >>> 32) + x_5 * x_1;
zz_7 += (zz_6 >>> 32) + x_5 * x_2;
zz_6 &= M;
zz_8 += (zz_7 >>> 32) + x_5 * x_3;
zz_7 &= M;
zz_9 += (zz_8 >>> 32) + x_5 * x_4;
zz_8 &= M;
zz_10 += zz_9 >>> 32;
zz_9 &= M;
}
long x_6 = x[xOff + 6] & M;
long zz_11 = (zz[zzOff + 11] & M) + (zz_10 >>> 32); zz_10 &= M;
long zz_12 = (zz[zzOff + 12] & M) + (zz_11 >>> 32); zz_11 &= M;
{
zz_6 += x_6 * x_0;
w = (int)zz_6;
zz[zzOff + 6] = (w << 1) | c;
c = w >>> 31;
zz_7 += (zz_6 >>> 32) + x_6 * x_1;
zz_8 += (zz_7 >>> 32) + x_6 * x_2;
zz_9 += (zz_8 >>> 32) + x_6 * x_3;
zz_10 += (zz_9 >>> 32) + x_6 * x_4;
zz_11 += (zz_10 >>> 32) + x_6 * x_5;
zz_12 += zz_11 >>> 32;
}
w = (int)zz_7;
zz[zzOff + 7] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_8;
zz[zzOff + 8] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_9;
zz[zzOff + 9] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_10;
zz[zzOff + 10] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_11;
zz[zzOff + 11] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_12;
zz[zzOff + 12] = (w << 1) | c;
c = w >>> 31;
w = zz[zzOff + 13] + (int)(zz_12 >>> 32);
zz[zzOff + 13] = (w << 1) | c;
}
public static int sub(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
c += (x[4] & M) - (y[4] & M);
z[4] = (int)c;
c >>= 32;
c += (x[5] & M) - (y[5] & M);
z[5] = (int)c;
c >>= 32;
c += (x[6] & M) - (y[6] & M);
z[6] = (int)c;
c >>= 32;
return (int)c;
}
public static int sub(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
long c = 0;
c += (x[xOff + 0] & M) - (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (x[xOff + 1] & M) - (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (x[xOff + 2] & M) - (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (x[xOff + 3] & M) - (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
c += (x[xOff + 4] & M) - (y[yOff + 4] & M);
z[zOff + 4] = (int)c;
c >>= 32;
c += (x[xOff + 5] & M) - (y[yOff + 5] & M);
z[zOff + 5] = (int)c;
c >>= 32;
c += (x[xOff + 6] & M) - (y[yOff + 6] & M);
z[zOff + 6] = (int)c;
c >>= 32;
return (int)c;
}
public static int subBothFrom(int[] x, int[] y, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
c += (z[4] & M) - (x[4] & M) - (y[4] & M);
z[4] = (int)c;
c >>= 32;
c += (z[5] & M) - (x[5] & M) - (y[5] & M);
z[5] = (int)c;
c >>= 32;
c += (z[6] & M) - (x[6] & M) - (y[6] & M);
z[6] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M);
z[3] = (int)c;
c >>= 32;
c += (z[4] & M) - (x[4] & M);
z[4] = (int)c;
c >>= 32;
c += (z[5] & M) - (x[5] & M);
z[5] = (int)c;
c >>= 32;
c += (z[6] & M) - (x[6] & M);
z[6] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int xOff, int[] z, int zOff)
{
long c = 0;
c += (z[zOff + 0] & M) - (x[xOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (z[zOff + 1] & M) - (x[xOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (z[zOff + 2] & M) - (x[xOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (z[zOff + 3] & M) - (x[xOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
c += (z[zOff + 4] & M) - (x[xOff + 4] & M);
z[zOff + 4] = (int)c;
c >>= 32;
c += (z[zOff + 5] & M) - (x[xOff + 5] & M);
z[zOff + 5] = (int)c;
c >>= 32;
c += (z[zOff + 6] & M) - (x[xOff + 6] & M);
z[zOff + 6] = (int)c;
c >>= 32;
return (int)c;
}
public static BigInteger toBigInteger(int[] x)
{
byte[] bs = new byte[28];
for (int i = 0; i < 7; ++i)
{
int x_i = x[i];
if (x_i != 0)
{
Pack.intToBigEndian(x_i, bs, (6 - i) << 2);
}
}
return new BigInteger(1, bs);
}
public static void zero(int[] z)
{
z[0] = 0;
z[1] = 0;
z[2] = 0;
z[3] = 0;
z[4] = 0;
z[5] = 0;
z[6] = 0;
}
}
| ./CrossVul/dataset_final_sorted/CWE-19/java/good_4757_3 |
crossvul-java_data_bad_4757_1 | package org.bouncycastle.math.raw;
import java.math.BigInteger;
import org.bouncycastle.util.Pack;
public abstract class Nat160
{
private static final long M = 0xFFFFFFFFL;
public static int add(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (y[4] & M);
z[4] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addBothTo(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (y[4] & M) + (z[4] & M);
z[4] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int[] z)
{
long c = 0;
c += (x[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (z[4] & M);
z[4] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int xOff, int[] z, int zOff, int cIn)
{
long c = cIn & M;
c += (x[xOff + 0] & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (x[xOff + 1] & M) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (x[xOff + 2] & M) + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (x[xOff + 3] & M) + (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
c += (x[xOff + 4] & M) + (z[zOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addToEachOther(int[] u, int uOff, int[] v, int vOff)
{
long c = 0;
c += (u[uOff + 0] & M) + (v[vOff + 0] & M);
u[uOff + 0] = (int)c;
v[vOff + 0] = (int)c;
c >>>= 32;
c += (u[uOff + 1] & M) + (v[vOff + 1] & M);
u[uOff + 1] = (int)c;
v[vOff + 1] = (int)c;
c >>>= 32;
c += (u[uOff + 2] & M) + (v[vOff + 2] & M);
u[uOff + 2] = (int)c;
v[vOff + 2] = (int)c;
c >>>= 32;
c += (u[uOff + 3] & M) + (v[vOff + 3] & M);
u[uOff + 3] = (int)c;
v[vOff + 3] = (int)c;
c >>>= 32;
c += (u[uOff + 4] & M) + (v[vOff + 4] & M);
u[uOff + 4] = (int)c;
v[vOff + 4] = (int)c;
c >>>= 32;
return (int)c;
}
public static void copy(int[] x, int[] z)
{
z[0] = x[0];
z[1] = x[1];
z[2] = x[2];
z[3] = x[3];
z[4] = x[4];
}
public static int[] create()
{
return new int[5];
}
public static int[] createExt()
{
return new int[10];
}
public static boolean diff(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
boolean pos = gte(x, xOff, y, yOff);
if (pos)
{
sub(x, xOff, y, yOff, z, zOff);
}
else
{
sub(y, yOff, x, xOff, z, zOff);
}
return pos;
}
public static boolean eq(int[] x, int[] y)
{
for (int i = 4; i >= 0; --i)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public static int[] fromBigInteger(BigInteger x)
{
if (x.signum() < 0 || x.bitLength() > 160)
{
throw new IllegalArgumentException();
}
int[] z = create();
int i = 0;
while (x.signum() != 0)
{
z[i++] = x.intValue();
x = x.shiftRight(32);
}
return z;
}
public static int getBit(int[] x, int bit)
{
if (bit == 0)
{
return x[0] & 1;
}
int w = bit >> 5;
if (w < 0 || w >= 5)
{
return 0;
}
int b = bit & 31;
return (x[w] >>> b) & 1;
}
public static boolean gte(int[] x, int[] y)
{
for (int i = 4; i >= 0; --i)
{
int x_i = x[i] ^ Integer.MIN_VALUE;
int y_i = y[i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean gte(int[] x, int xOff, int[] y, int yOff)
{
for (int i = 4; i >= 0; --i)
{
int x_i = x[xOff + i] ^ Integer.MIN_VALUE;
int y_i = y[yOff + i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean isOne(int[] x)
{
if (x[0] != 1)
{
return false;
}
for (int i = 1; i < 5; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static boolean isZero(int[] x)
{
for (int i = 0; i < 5; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static void mul(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
long y_4 = y[4] & M;
{
long c = 0, x_0 = x[0] & M;
c += x_0 * y_0;
zz[0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[3] = (int)c;
c >>>= 32;
c += x_0 * y_4;
zz[4] = (int)c;
c >>>= 32;
zz[5] = (int)c;
}
for (int i = 1; i < 5; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[i + 4] & M);
zz[i + 4] = (int)c;
c >>>= 32;
zz[i + 5] = (int)c;
}
}
public static void mul(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
long y_4 = y[yOff + 4] & M;
{
long c = 0, x_0 = x[xOff + 0] & M;
c += x_0 * y_0;
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_0 * y_4;
zz[zzOff + 4] = (int)c;
c >>>= 32;
zz[zzOff + 5] = (int)c;
}
for (int i = 1; i < 5; ++i)
{
++zzOff;
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
zz[zzOff + 5] = (int)c;
}
}
public static int mulAddTo(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
long y_4 = y[4] & M;
long zc = 0;
for (int i = 0; i < 5; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[i + 4] & M);
zz[i + 4] = (int)c;
c >>>= 32;
c += zc + (zz[i + 5] & M);
zz[i + 5] = (int)c;
zc = c >>> 32;
}
return (int)zc;
}
public static int mulAddTo(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
long y_4 = y[yOff + 4] & M;
long zc = 0;
for (int i = 0; i < 5; ++i)
{
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += zc + (zz[zzOff + 5] & M);
zz[zzOff + 5] = (int)c;
zc = c >>> 32;
++zzOff;
}
return (int)zc;
}
public static long mul33Add(int w, int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
// assert w >>> 31 == 0;
long c = 0, wVal = w & M;
long x0 = x[xOff + 0] & M;
c += wVal * x0 + (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long x1 = x[xOff + 1] & M;
c += wVal * x1 + x0 + (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
long x2 = x[xOff + 2] & M;
c += wVal * x2 + x1 + (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
long x3 = x[xOff + 3] & M;
c += wVal * x3 + x2 + (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
long x4 = x[xOff + 4] & M;
c += wVal * x4 + x3 + (y[yOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
c += x4;
return c;
}
public static int mulWordAddExt(int x, int[] yy, int yyOff, int[] zz, int zzOff)
{
// assert yyOff <= 5;
// assert zzOff <= 5;
long c = 0, xVal = x & M;
c += xVal * (yy[yyOff + 0] & M) + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 1] & M) + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 2] & M) + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 3] & M) + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 4] & M) + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
return (int)c;
}
public static int mul33DWordAdd(int x, long y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 1;
long c = 0, xVal = x & M;
long y00 = y & M;
c += xVal * y00 + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long y01 = y >>> 32;
c += xVal * y01 + y00 + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += y01 + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(5, z, zOff, 4);
}
public static int mul33WordAdd(int x, int y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 2;
long c = 0, xVal = x & M, yVal = y & M;
c += yVal * xVal + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += yVal + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(5, z, zOff, 3);
}
public static int mulWordDwordAdd(int x, long y, int[] z, int zOff)
{
// assert zOff <= 2;
long c = 0, xVal = x & M;
c += xVal * (y & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += xVal * (y >>> 32) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(5, z, zOff, 3);
}
public static int mulWordsAdd(int x, int y, int[] z, int zOff)
{
// assert zOff <= 3;
long c = 0, xVal = x & M, yVal = y & M;
c += yVal * xVal + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(5, z, zOff, 2);
}
public static int mulWord(int x, int[] y, int[] z, int zOff)
{
long c = 0, xVal = x & M;
int i = 0;
do
{
c += xVal * (y[i] & M);
z[zOff + i] = (int)c;
c >>>= 32;
}
while (++i < 5);
return (int)c;
}
public static void square(int[] x, int[] zz)
{
long x_0 = x[0] & M;
long zz_1;
int c = 0, w;
{
int i = 4, j = 10;
do
{
long xVal = (x[i--] & M);
long p = xVal * xVal;
zz[--j] = (c << 31) | (int)(p >>> 33);
zz[--j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[1] & M;
long zz_2 = zz[2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[2] & M;
long zz_3 = zz[3] & M;
long zz_4 = zz[4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[3] & M;
long zz_5 = zz[5] & M;
long zz_6 = zz[6] & M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_4 &= M;
zz_6 += zz_5 >>> 32;
zz_5 &= M;
}
long x_4 = x[4] & M;
long zz_7 = zz[7] & M;
long zz_8 = zz[8] & M;
{
zz_4 += x_4 * x_0;
w = (int)zz_4;
zz[4] = (w << 1) | c;
c = w >>> 31;
zz_5 += (zz_4 >>> 32) + x_4 * x_1;
zz_6 += (zz_5 >>> 32) + x_4 * x_2;
zz_7 += (zz_6 >>> 32) + x_4 * x_3;
zz_8 += zz_7 >>> 32;
}
w = (int)zz_5;
zz[5] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_6;
zz[6] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_7;
zz[7] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_8;
zz[8] = (w << 1) | c;
c = w >>> 31;
w = zz[9] + (int)(zz_8 >> 32);
zz[9] = (w << 1) | c;
}
public static void square(int[] x, int xOff, int[] zz, int zzOff)
{
long x_0 = x[xOff + 0] & M;
long zz_1;
int c = 0, w;
{
int i = 4, j = 10;
do
{
long xVal = (x[xOff + i--] & M);
long p = xVal * xVal;
zz[zzOff + --j] = (c << 31) | (int)(p >>> 33);
zz[zzOff + --j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[zzOff + 0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[xOff + 1] & M;
long zz_2 = zz[zzOff + 2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[zzOff + 1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[xOff + 2] & M;
long zz_3 = zz[zzOff + 3] & M;
long zz_4 = zz[zzOff + 4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[zzOff + 2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[xOff + 3] & M;
long zz_5 = zz[zzOff + 5] & M;
long zz_6 = zz[zzOff + 6] & M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[zzOff + 3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_4 &= M;
zz_6 += zz_5 >>> 32;
zz_5 &= M;
}
long x_4 = x[xOff + 4] & M;
long zz_7 = zz[zzOff + 7] & M;
long zz_8 = zz[zzOff + 8] & M;
{
zz_4 += x_4 * x_0;
w = (int)zz_4;
zz[zzOff + 4] = (w << 1) | c;
c = w >>> 31;
zz_5 += (zz_4 >>> 32) + x_4 * x_1;
zz_6 += (zz_5 >>> 32) + x_4 * x_2;
zz_7 += (zz_6 >>> 32) + x_4 * x_3;
zz_8 += zz_7 >>> 32;
}
w = (int)zz_5;
zz[zzOff + 5] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_6;
zz[zzOff + 6] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_7;
zz[zzOff + 7] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_8;
zz[zzOff + 8] = (w << 1) | c;
c = w >>> 31;
w = zz[zzOff + 9] + (int)(zz_8 >> 32);
zz[zzOff + 9] = (w << 1) | c;
}
public static int sub(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
c += (x[4] & M) - (y[4] & M);
z[4] = (int)c;
c >>= 32;
return (int)c;
}
public static int sub(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
long c = 0;
c += (x[xOff + 0] & M) - (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (x[xOff + 1] & M) - (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (x[xOff + 2] & M) - (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (x[xOff + 3] & M) - (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
c += (x[xOff + 4] & M) - (y[yOff + 4] & M);
z[zOff + 4] = (int)c;
c >>= 32;
return (int)c;
}
public static int subBothFrom(int[] x, int[] y, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
c += (z[4] & M) - (x[4] & M) - (y[4] & M);
z[4] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M);
z[3] = (int)c;
c >>= 32;
c += (z[4] & M) - (x[4] & M);
z[4] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int xOff, int[] z, int zOff)
{
long c = 0;
c += (z[zOff + 0] & M) - (x[xOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (z[zOff + 1] & M) - (x[xOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (z[zOff + 2] & M) - (x[xOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (z[zOff + 3] & M) - (x[xOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
c += (z[zOff + 4] & M) - (x[xOff + 4] & M);
z[zOff + 4] = (int)c;
c >>= 32;
return (int)c;
}
public static BigInteger toBigInteger(int[] x)
{
byte[] bs = new byte[20];
for (int i = 0; i < 5; ++i)
{
int x_i = x[i];
if (x_i != 0)
{
Pack.intToBigEndian(x_i, bs, (4 - i) << 2);
}
}
return new BigInteger(1, bs);
}
public static void zero(int[] z)
{
z[0] = 0;
z[1] = 0;
z[2] = 0;
z[3] = 0;
z[4] = 0;
}
}
| ./CrossVul/dataset_final_sorted/CWE-19/java/bad_4757_1 |
crossvul-java_data_good_4757_0 | package org.bouncycastle.math.raw;
import java.math.BigInteger;
import org.bouncycastle.util.Pack;
public abstract class Nat128
{
private static final long M = 0xFFFFFFFFL;
public static int add(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M);
z[3] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addBothTo(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int[] z)
{
long c = 0;
c += (x[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int xOff, int[] z, int zOff, int cIn)
{
long c = cIn & M;
c += (x[xOff + 0] & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (x[xOff + 1] & M) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (x[xOff + 2] & M) + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (x[xOff + 3] & M) + (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addToEachOther(int[] u, int uOff, int[] v, int vOff)
{
long c = 0;
c += (u[uOff + 0] & M) + (v[vOff + 0] & M);
u[uOff + 0] = (int)c;
v[vOff + 0] = (int)c;
c >>>= 32;
c += (u[uOff + 1] & M) + (v[vOff + 1] & M);
u[uOff + 1] = (int)c;
v[vOff + 1] = (int)c;
c >>>= 32;
c += (u[uOff + 2] & M) + (v[vOff + 2] & M);
u[uOff + 2] = (int)c;
v[vOff + 2] = (int)c;
c >>>= 32;
c += (u[uOff + 3] & M) + (v[vOff + 3] & M);
u[uOff + 3] = (int)c;
v[vOff + 3] = (int)c;
c >>>= 32;
return (int)c;
}
public static void copy(int[] x, int[] z)
{
z[0] = x[0];
z[1] = x[1];
z[2] = x[2];
z[3] = x[3];
}
public static void copy64(long[] x, long[] z)
{
z[0] = x[0];
z[1] = x[1];
}
public static int[] create()
{
return new int[4];
}
public static long[] create64()
{
return new long[2];
}
public static int[] createExt()
{
return new int[8];
}
public static long[] createExt64()
{
return new long[4];
}
public static boolean diff(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
boolean pos = gte(x, xOff, y, yOff);
if (pos)
{
sub(x, xOff, y, yOff, z, zOff);
}
else
{
sub(y, yOff, x, xOff, z, zOff);
}
return pos;
}
public static boolean eq(int[] x, int[] y)
{
for (int i = 3; i >= 0; --i)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public static boolean eq64(long[] x, long[] y)
{
for (int i = 1; i >= 0; --i)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public static int[] fromBigInteger(BigInteger x)
{
if (x.signum() < 0 || x.bitLength() > 128)
{
throw new IllegalArgumentException();
}
int[] z = create();
int i = 0;
while (x.signum() != 0)
{
z[i++] = x.intValue();
x = x.shiftRight(32);
}
return z;
}
public static long[] fromBigInteger64(BigInteger x)
{
if (x.signum() < 0 || x.bitLength() > 128)
{
throw new IllegalArgumentException();
}
long[] z = create64();
int i = 0;
while (x.signum() != 0)
{
z[i++] = x.longValue();
x = x.shiftRight(64);
}
return z;
}
public static int getBit(int[] x, int bit)
{
if (bit == 0)
{
return x[0] & 1;
}
int w = bit >> 5;
if (w < 0 || w >= 4)
{
return 0;
}
int b = bit & 31;
return (x[w] >>> b) & 1;
}
public static boolean gte(int[] x, int[] y)
{
for (int i = 3; i >= 0; --i)
{
int x_i = x[i] ^ Integer.MIN_VALUE;
int y_i = y[i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean gte(int[] x, int xOff, int[] y, int yOff)
{
for (int i = 3; i >= 0; --i)
{
int x_i = x[xOff + i] ^ Integer.MIN_VALUE;
int y_i = y[yOff + i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean isOne(int[] x)
{
if (x[0] != 1)
{
return false;
}
for (int i = 1; i < 4; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static boolean isOne64(long[] x)
{
if (x[0] != 1L)
{
return false;
}
for (int i = 1; i < 2; ++i)
{
if (x[i] != 0L)
{
return false;
}
}
return true;
}
public static boolean isZero(int[] x)
{
for (int i = 0; i < 4; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static boolean isZero64(long[] x)
{
for (int i = 0; i < 2; ++i)
{
if (x[i] != 0L)
{
return false;
}
}
return true;
}
public static void mul(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
{
long c = 0, x_0 = x[0] & M;
c += x_0 * y_0;
zz[0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[3] = (int)c;
c >>>= 32;
zz[4] = (int)c;
}
for (int i = 1; i < 4; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
zz[i + 4] = (int)c;
}
}
public static void mul(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
{
long c = 0, x_0 = x[xOff + 0] & M;
c += x_0 * y_0;
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[zzOff + 3] = (int)c;
c >>>= 32;
zz[zzOff + 4] = (int)c;
}
for (int i = 1; i < 4; ++i)
{
++zzOff;
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
zz[zzOff + 4] = (int)c;
}
}
public static int mulAddTo(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
long zc = 0;
for (int i = 0; i < 4; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
c += zc + (zz[i + 4] & M);
zz[i + 4] = (int)c;
zc = c >>> 32;
}
return (int)zc;
}
public static int mulAddTo(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
long zc = 0;
for (int i = 0; i < 4; ++i)
{
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += zc + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
zc = c >>> 32;
++zzOff;
}
return (int)zc;
}
public static long mul33Add(int w, int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
// assert w >>> 31 == 0;
long c = 0, wVal = w & M;
long x0 = x[xOff + 0] & M;
c += wVal * x0 + (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long x1 = x[xOff + 1] & M;
c += wVal * x1 + x0 + (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
long x2 = x[xOff + 2] & M;
c += wVal * x2 + x1 + (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
long x3 = x[xOff + 3] & M;
c += wVal * x3 + x2 + (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
c += x3;
return c;
}
public static int mulWordAddExt(int x, int[] yy, int yyOff, int[] zz, int zzOff)
{
// assert yyOff <= 4;
// assert zzOff <= 4;
long c = 0, xVal = x & M;
c += xVal * (yy[yyOff + 0] & M) + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 1] & M) + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 2] & M) + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 3] & M) + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
return (int)c;
}
public static int mul33DWordAdd(int x, long y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 0;
long c = 0, xVal = x & M;
long y00 = y & M;
c += xVal * y00 + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long y01 = y >>> 32;
c += xVal * y01 + y00 + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += y01 + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
return (int)c;
}
public static int mul33WordAdd(int x, int y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 1;
long c = 0, xVal = x & M, yVal = y & M;
c += yVal * xVal + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += yVal + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(4, z, zOff, 3);
}
public static int mulWordDwordAdd(int x, long y, int[] z, int zOff)
{
// assert zOff <= 1;
long c = 0, xVal = x & M;
c += xVal * (y & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += xVal * (y >>> 32) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(4, z, zOff, 3);
}
public static int mulWordsAdd(int x, int y, int[] z, int zOff)
{
// assert zOff <= 2;
long c = 0, xVal = x & M, yVal = y & M;
c += yVal * xVal + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(4, z, zOff, 2);
}
public static int mulWord(int x, int[] y, int[] z, int zOff)
{
long c = 0, xVal = x & M;
int i = 0;
do
{
c += xVal * (y[i] & M);
z[zOff + i] = (int)c;
c >>>= 32;
}
while (++i < 4);
return (int)c;
}
public static void square(int[] x, int[] zz)
{
long x_0 = x[0] & M;
long zz_1;
int c = 0, w;
{
int i = 3, j = 8;
do
{
long xVal = (x[i--] & M);
long p = xVal * xVal;
zz[--j] = (c << 31) | (int)(p >>> 33);
zz[--j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[1] & M;
long zz_2 = zz[2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[2] & M;
long zz_3 = zz[3] & M;
long zz_4 = zz[4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[3] & M;
long zz_5 = (zz[5] & M) + (zz_4 >>> 32); zz_4 &= M;
long zz_6 = (zz[6] & M) + (zz_5 >>> 32); zz_5 &= M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_6 += zz_5 >>> 32;
zz_5 &= M;
}
w = (int)zz_4;
zz[4] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_5;
zz[5] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_6;
zz[6] = (w << 1) | c;
c = w >>> 31;
w = zz[7] + (int)(zz_6 >>> 32);
zz[7] = (w << 1) | c;
}
public static void square(int[] x, int xOff, int[] zz, int zzOff)
{
long x_0 = x[xOff + 0] & M;
long zz_1;
int c = 0, w;
{
int i = 3, j = 8;
do
{
long xVal = (x[xOff + i--] & M);
long p = xVal * xVal;
zz[zzOff + --j] = (c << 31) | (int)(p >>> 33);
zz[zzOff + --j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[zzOff + 0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[xOff + 1] & M;
long zz_2 = zz[zzOff + 2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[zzOff + 1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[xOff + 2] & M;
long zz_3 = zz[zzOff + 3] & M;
long zz_4 = zz[zzOff + 4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[zzOff + 2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[xOff + 3] & M;
long zz_5 = (zz[zzOff + 5] & M) + (zz_4 >>> 32); zz_4 &= M;
long zz_6 = (zz[zzOff + 6] & M) + (zz_5 >>> 32); zz_5 &= M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[zzOff + 3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_6 += zz_5 >>> 32;
}
w = (int)zz_4;
zz[zzOff + 4] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_5;
zz[zzOff + 5] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_6;
zz[zzOff + 6] = (w << 1) | c;
c = w >>> 31;
w = zz[zzOff + 7] + (int)(zz_6 >>> 32);
zz[zzOff + 7] = (w << 1) | c;
}
public static int sub(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
return (int)c;
}
public static int sub(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
long c = 0;
c += (x[xOff + 0] & M) - (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (x[xOff + 1] & M) - (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (x[xOff + 2] & M) - (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (x[xOff + 3] & M) - (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
return (int)c;
}
public static int subBothFrom(int[] x, int[] y, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M);
z[3] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int xOff, int[] z, int zOff)
{
long c = 0;
c += (z[zOff + 0] & M) - (x[xOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (z[zOff + 1] & M) - (x[xOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (z[zOff + 2] & M) - (x[xOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (z[zOff + 3] & M) - (x[xOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
return (int)c;
}
public static BigInteger toBigInteger(int[] x)
{
byte[] bs = new byte[16];
for (int i = 0; i < 4; ++i)
{
int x_i = x[i];
if (x_i != 0)
{
Pack.intToBigEndian(x_i, bs, (3 - i) << 2);
}
}
return new BigInteger(1, bs);
}
public static BigInteger toBigInteger64(long[] x)
{
byte[] bs = new byte[16];
for (int i = 0; i < 2; ++i)
{
long x_i = x[i];
if (x_i != 0L)
{
Pack.longToBigEndian(x_i, bs, (1 - i) << 3);
}
}
return new BigInteger(1, bs);
}
public static void zero(int[] z)
{
z[0] = 0;
z[1] = 0;
z[2] = 0;
z[3] = 0;
}
}
| ./CrossVul/dataset_final_sorted/CWE-19/java/good_4757_0 |
crossvul-java_data_bad_4757_0 | package org.bouncycastle.math.raw;
import java.math.BigInteger;
import org.bouncycastle.util.Pack;
public abstract class Nat128
{
private static final long M = 0xFFFFFFFFL;
public static int add(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M);
z[3] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addBothTo(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int[] z)
{
long c = 0;
c += (x[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int xOff, int[] z, int zOff, int cIn)
{
long c = cIn & M;
c += (x[xOff + 0] & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (x[xOff + 1] & M) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (x[xOff + 2] & M) + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (x[xOff + 3] & M) + (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addToEachOther(int[] u, int uOff, int[] v, int vOff)
{
long c = 0;
c += (u[uOff + 0] & M) + (v[vOff + 0] & M);
u[uOff + 0] = (int)c;
v[vOff + 0] = (int)c;
c >>>= 32;
c += (u[uOff + 1] & M) + (v[vOff + 1] & M);
u[uOff + 1] = (int)c;
v[vOff + 1] = (int)c;
c >>>= 32;
c += (u[uOff + 2] & M) + (v[vOff + 2] & M);
u[uOff + 2] = (int)c;
v[vOff + 2] = (int)c;
c >>>= 32;
c += (u[uOff + 3] & M) + (v[vOff + 3] & M);
u[uOff + 3] = (int)c;
v[vOff + 3] = (int)c;
c >>>= 32;
return (int)c;
}
public static void copy(int[] x, int[] z)
{
z[0] = x[0];
z[1] = x[1];
z[2] = x[2];
z[3] = x[3];
}
public static void copy64(long[] x, long[] z)
{
z[0] = x[0];
z[1] = x[1];
}
public static int[] create()
{
return new int[4];
}
public static long[] create64()
{
return new long[2];
}
public static int[] createExt()
{
return new int[8];
}
public static long[] createExt64()
{
return new long[4];
}
public static boolean diff(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
boolean pos = gte(x, xOff, y, yOff);
if (pos)
{
sub(x, xOff, y, yOff, z, zOff);
}
else
{
sub(y, yOff, x, xOff, z, zOff);
}
return pos;
}
public static boolean eq(int[] x, int[] y)
{
for (int i = 3; i >= 0; --i)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public static boolean eq64(long[] x, long[] y)
{
for (int i = 1; i >= 0; --i)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public static int[] fromBigInteger(BigInteger x)
{
if (x.signum() < 0 || x.bitLength() > 128)
{
throw new IllegalArgumentException();
}
int[] z = create();
int i = 0;
while (x.signum() != 0)
{
z[i++] = x.intValue();
x = x.shiftRight(32);
}
return z;
}
public static long[] fromBigInteger64(BigInteger x)
{
if (x.signum() < 0 || x.bitLength() > 128)
{
throw new IllegalArgumentException();
}
long[] z = create64();
int i = 0;
while (x.signum() != 0)
{
z[i++] = x.longValue();
x = x.shiftRight(64);
}
return z;
}
public static int getBit(int[] x, int bit)
{
if (bit == 0)
{
return x[0] & 1;
}
int w = bit >> 5;
if (w < 0 || w >= 4)
{
return 0;
}
int b = bit & 31;
return (x[w] >>> b) & 1;
}
public static boolean gte(int[] x, int[] y)
{
for (int i = 3; i >= 0; --i)
{
int x_i = x[i] ^ Integer.MIN_VALUE;
int y_i = y[i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean gte(int[] x, int xOff, int[] y, int yOff)
{
for (int i = 3; i >= 0; --i)
{
int x_i = x[xOff + i] ^ Integer.MIN_VALUE;
int y_i = y[yOff + i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean isOne(int[] x)
{
if (x[0] != 1)
{
return false;
}
for (int i = 1; i < 4; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static boolean isOne64(long[] x)
{
if (x[0] != 1L)
{
return false;
}
for (int i = 1; i < 2; ++i)
{
if (x[i] != 0L)
{
return false;
}
}
return true;
}
public static boolean isZero(int[] x)
{
for (int i = 0; i < 4; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static boolean isZero64(long[] x)
{
for (int i = 0; i < 2; ++i)
{
if (x[i] != 0L)
{
return false;
}
}
return true;
}
public static void mul(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
{
long c = 0, x_0 = x[0] & M;
c += x_0 * y_0;
zz[0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[3] = (int)c;
c >>>= 32;
zz[4] = (int)c;
}
for (int i = 1; i < 4; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
zz[i + 4] = (int)c;
}
}
public static void mul(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
{
long c = 0, x_0 = x[xOff + 0] & M;
c += x_0 * y_0;
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[zzOff + 3] = (int)c;
c >>>= 32;
zz[zzOff + 4] = (int)c;
}
for (int i = 1; i < 4; ++i)
{
++zzOff;
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
zz[zzOff + 4] = (int)c;
}
}
public static int mulAddTo(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
long zc = 0;
for (int i = 0; i < 4; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
c += zc + (zz[i + 4] & M);
zz[i + 4] = (int)c;
zc = c >>> 32;
}
return (int)zc;
}
public static int mulAddTo(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
long zc = 0;
for (int i = 0; i < 4; ++i)
{
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += zc + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
zc = c >>> 32;
++zzOff;
}
return (int)zc;
}
public static long mul33Add(int w, int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
// assert w >>> 31 == 0;
long c = 0, wVal = w & M;
long x0 = x[xOff + 0] & M;
c += wVal * x0 + (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long x1 = x[xOff + 1] & M;
c += wVal * x1 + x0 + (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
long x2 = x[xOff + 2] & M;
c += wVal * x2 + x1 + (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
long x3 = x[xOff + 3] & M;
c += wVal * x3 + x2 + (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
c += x3;
return c;
}
public static int mulWordAddExt(int x, int[] yy, int yyOff, int[] zz, int zzOff)
{
// assert yyOff <= 4;
// assert zzOff <= 4;
long c = 0, xVal = x & M;
c += xVal * (yy[yyOff + 0] & M) + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 1] & M) + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 2] & M) + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 3] & M) + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
return (int)c;
}
public static int mul33DWordAdd(int x, long y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 0;
long c = 0, xVal = x & M;
long y00 = y & M;
c += xVal * y00 + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long y01 = y >>> 32;
c += xVal * y01 + y00 + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += y01 + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
return (int)c;
}
public static int mul33WordAdd(int x, int y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 1;
long c = 0, xVal = x & M, yVal = y & M;
c += yVal * xVal + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += yVal + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(4, z, zOff, 3);
}
public static int mulWordDwordAdd(int x, long y, int[] z, int zOff)
{
// assert zOff <= 1;
long c = 0, xVal = x & M;
c += xVal * (y & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += xVal * (y >>> 32) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(4, z, zOff, 3);
}
public static int mulWordsAdd(int x, int y, int[] z, int zOff)
{
// assert zOff <= 2;
long c = 0, xVal = x & M, yVal = y & M;
c += yVal * xVal + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(4, z, zOff, 2);
}
public static int mulWord(int x, int[] y, int[] z, int zOff)
{
long c = 0, xVal = x & M;
int i = 0;
do
{
c += xVal * (y[i] & M);
z[zOff + i] = (int)c;
c >>>= 32;
}
while (++i < 4);
return (int)c;
}
public static void square(int[] x, int[] zz)
{
long x_0 = x[0] & M;
long zz_1;
int c = 0, w;
{
int i = 3, j = 8;
do
{
long xVal = (x[i--] & M);
long p = xVal * xVal;
zz[--j] = (c << 31) | (int)(p >>> 33);
zz[--j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[1] & M;
long zz_2 = zz[2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[2] & M;
long zz_3 = zz[3] & M;
long zz_4 = zz[4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[3] & M;
long zz_5 = zz[5] & M;
long zz_6 = zz[6] & M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_6 += zz_5 >>> 32;
zz_5 &= M;
}
w = (int)zz_4;
zz[4] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_5;
zz[5] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_6;
zz[6] = (w << 1) | c;
c = w >>> 31;
w = zz[7] + (int)(zz_6 >> 32);
zz[7] = (w << 1) | c;
}
public static void square(int[] x, int xOff, int[] zz, int zzOff)
{
long x_0 = x[xOff + 0] & M;
long zz_1;
int c = 0, w;
{
int i = 3, j = 8;
do
{
long xVal = (x[xOff + i--] & M);
long p = xVal * xVal;
zz[zzOff + --j] = (c << 31) | (int)(p >>> 33);
zz[zzOff + --j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[zzOff + 0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[xOff + 1] & M;
long zz_2 = zz[zzOff + 2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[zzOff + 1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[xOff + 2] & M;
long zz_3 = zz[zzOff + 3] & M;
long zz_4 = zz[zzOff + 4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[zzOff + 2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[xOff + 3] & M;
long zz_5 = zz[zzOff + 5] & M;
long zz_6 = zz[zzOff + 6] & M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[zzOff + 3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_6 += zz_5 >>> 32;
}
w = (int)zz_4;
zz[zzOff + 4] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_5;
zz[zzOff + 5] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_6;
zz[zzOff + 6] = (w << 1) | c;
c = w >>> 31;
w = zz[zzOff + 7] + (int)(zz_6 >> 32);
zz[zzOff + 7] = (w << 1) | c;
}
public static int sub(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
return (int)c;
}
public static int sub(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
long c = 0;
c += (x[xOff + 0] & M) - (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (x[xOff + 1] & M) - (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (x[xOff + 2] & M) - (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (x[xOff + 3] & M) - (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
return (int)c;
}
public static int subBothFrom(int[] x, int[] y, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M);
z[3] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int xOff, int[] z, int zOff)
{
long c = 0;
c += (z[zOff + 0] & M) - (x[xOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (z[zOff + 1] & M) - (x[xOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (z[zOff + 2] & M) - (x[xOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (z[zOff + 3] & M) - (x[xOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
return (int)c;
}
public static BigInteger toBigInteger(int[] x)
{
byte[] bs = new byte[16];
for (int i = 0; i < 4; ++i)
{
int x_i = x[i];
if (x_i != 0)
{
Pack.intToBigEndian(x_i, bs, (3 - i) << 2);
}
}
return new BigInteger(1, bs);
}
public static BigInteger toBigInteger64(long[] x)
{
byte[] bs = new byte[16];
for (int i = 0; i < 2; ++i)
{
long x_i = x[i];
if (x_i != 0L)
{
Pack.longToBigEndian(x_i, bs, (1 - i) << 3);
}
}
return new BigInteger(1, bs);
}
public static void zero(int[] z)
{
z[0] = 0;
z[1] = 0;
z[2] = 0;
z[3] = 0;
}
}
| ./CrossVul/dataset_final_sorted/CWE-19/java/bad_4757_0 |
crossvul-java_data_bad_4757_2 | package org.bouncycastle.math.raw;
import java.math.BigInteger;
import org.bouncycastle.util.Pack;
public abstract class Nat192
{
private static final long M = 0xFFFFFFFFL;
public static int add(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (y[4] & M);
z[4] = (int)c;
c >>>= 32;
c += (x[5] & M) + (y[5] & M);
z[5] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addBothTo(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (y[4] & M) + (z[4] & M);
z[4] = (int)c;
c >>>= 32;
c += (x[5] & M) + (y[5] & M) + (z[5] & M);
z[5] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int[] z)
{
long c = 0;
c += (x[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (z[4] & M);
z[4] = (int)c;
c >>>= 32;
c += (x[5] & M) + (z[5] & M);
z[5] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int xOff, int[] z, int zOff, int cIn)
{
long c = cIn & M;
c += (x[xOff + 0] & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (x[xOff + 1] & M) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (x[xOff + 2] & M) + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (x[xOff + 3] & M) + (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
c += (x[xOff + 4] & M) + (z[zOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
c += (x[xOff + 5] & M) + (z[zOff + 5] & M);
z[zOff + 5] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addToEachOther(int[] u, int uOff, int[] v, int vOff)
{
long c = 0;
c += (u[uOff + 0] & M) + (v[vOff + 0] & M);
u[uOff + 0] = (int)c;
v[vOff + 0] = (int)c;
c >>>= 32;
c += (u[uOff + 1] & M) + (v[vOff + 1] & M);
u[uOff + 1] = (int)c;
v[vOff + 1] = (int)c;
c >>>= 32;
c += (u[uOff + 2] & M) + (v[vOff + 2] & M);
u[uOff + 2] = (int)c;
v[vOff + 2] = (int)c;
c >>>= 32;
c += (u[uOff + 3] & M) + (v[vOff + 3] & M);
u[uOff + 3] = (int)c;
v[vOff + 3] = (int)c;
c >>>= 32;
c += (u[uOff + 4] & M) + (v[vOff + 4] & M);
u[uOff + 4] = (int)c;
v[vOff + 4] = (int)c;
c >>>= 32;
c += (u[uOff + 5] & M) + (v[vOff + 5] & M);
u[uOff + 5] = (int)c;
v[vOff + 5] = (int)c;
c >>>= 32;
return (int)c;
}
public static void copy(int[] x, int[] z)
{
z[0] = x[0];
z[1] = x[1];
z[2] = x[2];
z[3] = x[3];
z[4] = x[4];
z[5] = x[5];
}
public static void copy64(long[] x, long[] z)
{
z[0] = x[0];
z[1] = x[1];
z[2] = x[2];
}
public static int[] create()
{
return new int[6];
}
public static long[] create64()
{
return new long[3];
}
public static int[] createExt()
{
return new int[12];
}
public static long[] createExt64()
{
return new long[6];
}
public static boolean diff(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
boolean pos = gte(x, xOff, y, yOff);
if (pos)
{
sub(x, xOff, y, yOff, z, zOff);
}
else
{
sub(y, yOff, x, xOff, z, zOff);
}
return pos;
}
public static boolean eq(int[] x, int[] y)
{
for (int i = 5; i >= 0; --i)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public static boolean eq64(long[] x, long[] y)
{
for (int i = 2; i >= 0; --i)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public static int[] fromBigInteger(BigInteger x)
{
if (x.signum() < 0 || x.bitLength() > 192)
{
throw new IllegalArgumentException();
}
int[] z = create();
int i = 0;
while (x.signum() != 0)
{
z[i++] = x.intValue();
x = x.shiftRight(32);
}
return z;
}
public static long[] fromBigInteger64(BigInteger x)
{
if (x.signum() < 0 || x.bitLength() > 192)
{
throw new IllegalArgumentException();
}
long[] z = create64();
int i = 0;
while (x.signum() != 0)
{
z[i++] = x.longValue();
x = x.shiftRight(64);
}
return z;
}
public static int getBit(int[] x, int bit)
{
if (bit == 0)
{
return x[0] & 1;
}
int w = bit >> 5;
if (w < 0 || w >= 6)
{
return 0;
}
int b = bit & 31;
return (x[w] >>> b) & 1;
}
public static boolean gte(int[] x, int[] y)
{
for (int i = 5; i >= 0; --i)
{
int x_i = x[i] ^ Integer.MIN_VALUE;
int y_i = y[i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean gte(int[] x, int xOff, int[] y, int yOff)
{
for (int i = 5; i >= 0; --i)
{
int x_i = x[xOff + i] ^ Integer.MIN_VALUE;
int y_i = y[yOff + i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean isOne(int[] x)
{
if (x[0] != 1)
{
return false;
}
for (int i = 1; i < 6; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static boolean isOne64(long[] x)
{
if (x[0] != 1L)
{
return false;
}
for (int i = 1; i < 3; ++i)
{
if (x[i] != 0L)
{
return false;
}
}
return true;
}
public static boolean isZero(int[] x)
{
for (int i = 0; i < 6; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static boolean isZero64(long[] x)
{
for (int i = 0; i < 3; ++i)
{
if (x[i] != 0L)
{
return false;
}
}
return true;
}
public static void mul(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
long y_4 = y[4] & M;
long y_5 = y[5] & M;
{
long c = 0, x_0 = x[0] & M;
c += x_0 * y_0;
zz[0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[3] = (int)c;
c >>>= 32;
c += x_0 * y_4;
zz[4] = (int)c;
c >>>= 32;
c += x_0 * y_5;
zz[5] = (int)c;
c >>>= 32;
zz[6] = (int)c;
}
for (int i = 1; i < 6; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[i + 4] & M);
zz[i + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[i + 5] & M);
zz[i + 5] = (int)c;
c >>>= 32;
zz[i + 6] = (int)c;
}
}
public static void mul(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
long y_4 = y[yOff + 4] & M;
long y_5 = y[yOff + 5] & M;
{
long c = 0, x_0 = x[xOff + 0] & M;
c += x_0 * y_0;
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_0 * y_4;
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += x_0 * y_5;
zz[zzOff + 5] = (int)c;
c >>>= 32;
zz[zzOff + 6] = (int)c;
}
for (int i = 1; i < 6; ++i)
{
++zzOff;
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[zzOff + 5] & M);
zz[zzOff + 5] = (int)c;
c >>>= 32;
zz[zzOff + 6] = (int)c;
}
}
public static int mulAddTo(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
long y_4 = y[4] & M;
long y_5 = y[5] & M;
long zc = 0;
for (int i = 0; i < 6; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[i + 4] & M);
zz[i + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[i + 5] & M);
zz[i + 5] = (int)c;
c >>>= 32;
c += zc + (zz[i + 6] & M);
zz[i + 6] = (int)c;
zc = c >>> 32;
}
return (int)zc;
}
public static int mulAddTo(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
long y_4 = y[yOff + 4] & M;
long y_5 = y[yOff + 5] & M;
long zc = 0;
for (int i = 0; i < 6; ++i)
{
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[zzOff + 5] & M);
zz[zzOff + 5] = (int)c;
c >>>= 32;
c += zc + (zz[zzOff + 6] & M);
zz[zzOff + 6] = (int)c;
zc = c >>> 32;
++zzOff;
}
return (int)zc;
}
public static long mul33Add(int w, int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
// assert w >>> 31 == 0;
long c = 0, wVal = w & M;
long x0 = x[xOff + 0] & M;
c += wVal * x0 + (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long x1 = x[xOff + 1] & M;
c += wVal * x1 + x0 + (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
long x2 = x[xOff + 2] & M;
c += wVal * x2 + x1 + (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
long x3 = x[xOff + 3] & M;
c += wVal * x3 + x2 + (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
long x4 = x[xOff + 4] & M;
c += wVal * x4 + x3 + (y[yOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
long x5 = x[xOff + 5] & M;
c += wVal * x5 + x4 + (y[yOff + 5] & M);
z[zOff + 5] = (int)c;
c >>>= 32;
c += x5;
return c;
}
public static int mulWordAddExt(int x, int[] yy, int yyOff, int[] zz, int zzOff)
{
// assert yyOff <= 6;
// assert zzOff <= 6;
long c = 0, xVal = x & M;
c += xVal * (yy[yyOff + 0] & M) + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 1] & M) + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 2] & M) + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 3] & M) + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 4] & M) + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 5] & M) + (zz[zzOff + 5] & M);
zz[zzOff + 5] = (int)c;
c >>>= 32;
return (int)c;
}
public static int mul33DWordAdd(int x, long y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 2;
long c = 0, xVal = x & M;
long y00 = y & M;
c += xVal * y00 + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long y01 = y >>> 32;
c += xVal * y01 + y00 + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += y01 + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(6, z, zOff, 4);
}
public static int mul33WordAdd(int x, int y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 3;
long c = 0, xVal = x & M, yVal = y & M;
c += yVal * xVal + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += yVal + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(6, z, zOff, 3);
}
public static int mulWordDwordAdd(int x, long y, int[] z, int zOff)
{
// assert zOff <= 3;
long c = 0, xVal = x & M;
c += xVal * (y & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += xVal * (y >>> 32) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(6, z, zOff, 3);
}
public static int mulWord(int x, int[] y, int[] z, int zOff)
{
long c = 0, xVal = x & M;
int i = 0;
do
{
c += xVal * (y[i] & M);
z[zOff + i] = (int)c;
c >>>= 32;
}
while (++i < 6);
return (int)c;
}
public static void square(int[] x, int[] zz)
{
long x_0 = x[0] & M;
long zz_1;
int c = 0, w;
{
int i = 5, j = 12;
do
{
long xVal = (x[i--] & M);
long p = xVal * xVal;
zz[--j] = (c << 31) | (int)(p >>> 33);
zz[--j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[1] & M;
long zz_2 = zz[2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[2] & M;
long zz_3 = zz[3] & M;
long zz_4 = zz[4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[3] & M;
long zz_5 = zz[5] & M;
long zz_6 = zz[6] & M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_4 &= M;
zz_6 += zz_5 >>> 32;
zz_5 &= M;
}
long x_4 = x[4] & M;
long zz_7 = zz[7] & M;
long zz_8 = zz[8] & M;
{
zz_4 += x_4 * x_0;
w = (int)zz_4;
zz[4] = (w << 1) | c;
c = w >>> 31;
zz_5 += (zz_4 >>> 32) + x_4 * x_1;
zz_6 += (zz_5 >>> 32) + x_4 * x_2;
zz_5 &= M;
zz_7 += (zz_6 >>> 32) + x_4 * x_3;
zz_6 &= M;
zz_8 += zz_7 >>> 32;
zz_7 &= M;
}
long x_5 = x[5] & M;
long zz_9 = zz[9] & M;
long zz_10 = zz[10] & M;
{
zz_5 += x_5 * x_0;
w = (int)zz_5;
zz[5] = (w << 1) | c;
c = w >>> 31;
zz_6 += (zz_5 >>> 32) + x_5 * x_1;
zz_7 += (zz_6 >>> 32) + x_5 * x_2;
zz_8 += (zz_7 >>> 32) + x_5 * x_3;
zz_9 += (zz_8 >>> 32) + x_5 * x_4;
zz_10 += zz_9 >>> 32;
}
w = (int)zz_6;
zz[6] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_7;
zz[7] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_8;
zz[8] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_9;
zz[9] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_10;
zz[10] = (w << 1) | c;
c = w >>> 31;
w = zz[11] + (int)(zz_10 >> 32);
zz[11] = (w << 1) | c;
}
public static void square(int[] x, int xOff, int[] zz, int zzOff)
{
long x_0 = x[xOff + 0] & M;
long zz_1;
int c = 0, w;
{
int i = 5, j = 12;
do
{
long xVal = (x[xOff + i--] & M);
long p = xVal * xVal;
zz[zzOff + --j] = (c << 31) | (int)(p >>> 33);
zz[zzOff + --j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[zzOff + 0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[xOff + 1] & M;
long zz_2 = zz[zzOff + 2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[zzOff + 1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[xOff + 2] & M;
long zz_3 = zz[zzOff + 3] & M;
long zz_4 = zz[zzOff + 4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[zzOff + 2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[xOff + 3] & M;
long zz_5 = zz[zzOff + 5] & M;
long zz_6 = zz[zzOff + 6] & M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[zzOff + 3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_4 &= M;
zz_6 += zz_5 >>> 32;
zz_5 &= M;
}
long x_4 = x[xOff + 4] & M;
long zz_7 = zz[zzOff + 7] & M;
long zz_8 = zz[zzOff + 8] & M;
{
zz_4 += x_4 * x_0;
w = (int)zz_4;
zz[zzOff + 4] = (w << 1) | c;
c = w >>> 31;
zz_5 += (zz_4 >>> 32) + x_4 * x_1;
zz_6 += (zz_5 >>> 32) + x_4 * x_2;
zz_5 &= M;
zz_7 += (zz_6 >>> 32) + x_4 * x_3;
zz_6 &= M;
zz_8 += zz_7 >>> 32;
zz_7 &= M;
}
long x_5 = x[xOff + 5] & M;
long zz_9 = zz[zzOff + 9] & M;
long zz_10 = zz[zzOff + 10] & M;
{
zz_5 += x_5 * x_0;
w = (int)zz_5;
zz[zzOff + 5] = (w << 1) | c;
c = w >>> 31;
zz_6 += (zz_5 >>> 32) + x_5 * x_1;
zz_7 += (zz_6 >>> 32) + x_5 * x_2;
zz_8 += (zz_7 >>> 32) + x_5 * x_3;
zz_9 += (zz_8 >>> 32) + x_5 * x_4;
zz_10 += zz_9 >>> 32;
}
w = (int)zz_6;
zz[zzOff + 6] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_7;
zz[zzOff + 7] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_8;
zz[zzOff + 8] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_9;
zz[zzOff + 9] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_10;
zz[zzOff + 10] = (w << 1) | c;
c = w >>> 31;
w = zz[zzOff + 11] + (int)(zz_10 >> 32);
zz[zzOff + 11] = (w << 1) | c;
}
public static int sub(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
c += (x[4] & M) - (y[4] & M);
z[4] = (int)c;
c >>= 32;
c += (x[5] & M) - (y[5] & M);
z[5] = (int)c;
c >>= 32;
return (int)c;
}
public static int sub(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
long c = 0;
c += (x[xOff + 0] & M) - (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (x[xOff + 1] & M) - (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (x[xOff + 2] & M) - (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (x[xOff + 3] & M) - (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
c += (x[xOff + 4] & M) - (y[yOff + 4] & M);
z[zOff + 4] = (int)c;
c >>= 32;
c += (x[xOff + 5] & M) - (y[yOff + 5] & M);
z[zOff + 5] = (int)c;
c >>= 32;
return (int)c;
}
public static int subBothFrom(int[] x, int[] y, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
c += (z[4] & M) - (x[4] & M) - (y[4] & M);
z[4] = (int)c;
c >>= 32;
c += (z[5] & M) - (x[5] & M) - (y[5] & M);
z[5] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M);
z[3] = (int)c;
c >>= 32;
c += (z[4] & M) - (x[4] & M);
z[4] = (int)c;
c >>= 32;
c += (z[5] & M) - (x[5] & M);
z[5] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int xOff, int[] z, int zOff)
{
long c = 0;
c += (z[zOff + 0] & M) - (x[xOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (z[zOff + 1] & M) - (x[xOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (z[zOff + 2] & M) - (x[xOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (z[zOff + 3] & M) - (x[xOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
c += (z[zOff + 4] & M) - (x[xOff + 4] & M);
z[zOff + 4] = (int)c;
c >>= 32;
c += (z[zOff + 5] & M) - (x[xOff + 5] & M);
z[zOff + 5] = (int)c;
c >>= 32;
return (int)c;
}
public static BigInteger toBigInteger(int[] x)
{
byte[] bs = new byte[24];
for (int i = 0; i < 6; ++i)
{
int x_i = x[i];
if (x_i != 0)
{
Pack.intToBigEndian(x_i, bs, (5 - i) << 2);
}
}
return new BigInteger(1, bs);
}
public static BigInteger toBigInteger64(long[] x)
{
byte[] bs = new byte[24];
for (int i = 0; i < 3; ++i)
{
long x_i = x[i];
if (x_i != 0L)
{
Pack.longToBigEndian(x_i, bs, (2 - i) << 3);
}
}
return new BigInteger(1, bs);
}
public static void zero(int[] z)
{
z[0] = 0;
z[1] = 0;
z[2] = 0;
z[3] = 0;
z[4] = 0;
z[5] = 0;
}
}
| ./CrossVul/dataset_final_sorted/CWE-19/java/bad_4757_2 |
crossvul-java_data_good_4757_2 | package org.bouncycastle.math.raw;
import java.math.BigInteger;
import org.bouncycastle.util.Pack;
public abstract class Nat192
{
private static final long M = 0xFFFFFFFFL;
public static int add(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (y[4] & M);
z[4] = (int)c;
c >>>= 32;
c += (x[5] & M) + (y[5] & M);
z[5] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addBothTo(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) + (y[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (y[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (y[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (y[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (y[4] & M) + (z[4] & M);
z[4] = (int)c;
c >>>= 32;
c += (x[5] & M) + (y[5] & M) + (z[5] & M);
z[5] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int[] z)
{
long c = 0;
c += (x[0] & M) + (z[0] & M);
z[0] = (int)c;
c >>>= 32;
c += (x[1] & M) + (z[1] & M);
z[1] = (int)c;
c >>>= 32;
c += (x[2] & M) + (z[2] & M);
z[2] = (int)c;
c >>>= 32;
c += (x[3] & M) + (z[3] & M);
z[3] = (int)c;
c >>>= 32;
c += (x[4] & M) + (z[4] & M);
z[4] = (int)c;
c >>>= 32;
c += (x[5] & M) + (z[5] & M);
z[5] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addTo(int[] x, int xOff, int[] z, int zOff, int cIn)
{
long c = cIn & M;
c += (x[xOff + 0] & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += (x[xOff + 1] & M) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (x[xOff + 2] & M) + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (x[xOff + 3] & M) + (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
c += (x[xOff + 4] & M) + (z[zOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
c += (x[xOff + 5] & M) + (z[zOff + 5] & M);
z[zOff + 5] = (int)c;
c >>>= 32;
return (int)c;
}
public static int addToEachOther(int[] u, int uOff, int[] v, int vOff)
{
long c = 0;
c += (u[uOff + 0] & M) + (v[vOff + 0] & M);
u[uOff + 0] = (int)c;
v[vOff + 0] = (int)c;
c >>>= 32;
c += (u[uOff + 1] & M) + (v[vOff + 1] & M);
u[uOff + 1] = (int)c;
v[vOff + 1] = (int)c;
c >>>= 32;
c += (u[uOff + 2] & M) + (v[vOff + 2] & M);
u[uOff + 2] = (int)c;
v[vOff + 2] = (int)c;
c >>>= 32;
c += (u[uOff + 3] & M) + (v[vOff + 3] & M);
u[uOff + 3] = (int)c;
v[vOff + 3] = (int)c;
c >>>= 32;
c += (u[uOff + 4] & M) + (v[vOff + 4] & M);
u[uOff + 4] = (int)c;
v[vOff + 4] = (int)c;
c >>>= 32;
c += (u[uOff + 5] & M) + (v[vOff + 5] & M);
u[uOff + 5] = (int)c;
v[vOff + 5] = (int)c;
c >>>= 32;
return (int)c;
}
public static void copy(int[] x, int[] z)
{
z[0] = x[0];
z[1] = x[1];
z[2] = x[2];
z[3] = x[3];
z[4] = x[4];
z[5] = x[5];
}
public static void copy64(long[] x, long[] z)
{
z[0] = x[0];
z[1] = x[1];
z[2] = x[2];
}
public static int[] create()
{
return new int[6];
}
public static long[] create64()
{
return new long[3];
}
public static int[] createExt()
{
return new int[12];
}
public static long[] createExt64()
{
return new long[6];
}
public static boolean diff(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
boolean pos = gte(x, xOff, y, yOff);
if (pos)
{
sub(x, xOff, y, yOff, z, zOff);
}
else
{
sub(y, yOff, x, xOff, z, zOff);
}
return pos;
}
public static boolean eq(int[] x, int[] y)
{
for (int i = 5; i >= 0; --i)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public static boolean eq64(long[] x, long[] y)
{
for (int i = 2; i >= 0; --i)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public static int[] fromBigInteger(BigInteger x)
{
if (x.signum() < 0 || x.bitLength() > 192)
{
throw new IllegalArgumentException();
}
int[] z = create();
int i = 0;
while (x.signum() != 0)
{
z[i++] = x.intValue();
x = x.shiftRight(32);
}
return z;
}
public static long[] fromBigInteger64(BigInteger x)
{
if (x.signum() < 0 || x.bitLength() > 192)
{
throw new IllegalArgumentException();
}
long[] z = create64();
int i = 0;
while (x.signum() != 0)
{
z[i++] = x.longValue();
x = x.shiftRight(64);
}
return z;
}
public static int getBit(int[] x, int bit)
{
if (bit == 0)
{
return x[0] & 1;
}
int w = bit >> 5;
if (w < 0 || w >= 6)
{
return 0;
}
int b = bit & 31;
return (x[w] >>> b) & 1;
}
public static boolean gte(int[] x, int[] y)
{
for (int i = 5; i >= 0; --i)
{
int x_i = x[i] ^ Integer.MIN_VALUE;
int y_i = y[i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean gte(int[] x, int xOff, int[] y, int yOff)
{
for (int i = 5; i >= 0; --i)
{
int x_i = x[xOff + i] ^ Integer.MIN_VALUE;
int y_i = y[yOff + i] ^ Integer.MIN_VALUE;
if (x_i < y_i)
return false;
if (x_i > y_i)
return true;
}
return true;
}
public static boolean isOne(int[] x)
{
if (x[0] != 1)
{
return false;
}
for (int i = 1; i < 6; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static boolean isOne64(long[] x)
{
if (x[0] != 1L)
{
return false;
}
for (int i = 1; i < 3; ++i)
{
if (x[i] != 0L)
{
return false;
}
}
return true;
}
public static boolean isZero(int[] x)
{
for (int i = 0; i < 6; ++i)
{
if (x[i] != 0)
{
return false;
}
}
return true;
}
public static boolean isZero64(long[] x)
{
for (int i = 0; i < 3; ++i)
{
if (x[i] != 0L)
{
return false;
}
}
return true;
}
public static void mul(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
long y_4 = y[4] & M;
long y_5 = y[5] & M;
{
long c = 0, x_0 = x[0] & M;
c += x_0 * y_0;
zz[0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[3] = (int)c;
c >>>= 32;
c += x_0 * y_4;
zz[4] = (int)c;
c >>>= 32;
c += x_0 * y_5;
zz[5] = (int)c;
c >>>= 32;
zz[6] = (int)c;
}
for (int i = 1; i < 6; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[i + 4] & M);
zz[i + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[i + 5] & M);
zz[i + 5] = (int)c;
c >>>= 32;
zz[i + 6] = (int)c;
}
}
public static void mul(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
long y_4 = y[yOff + 4] & M;
long y_5 = y[yOff + 5] & M;
{
long c = 0, x_0 = x[xOff + 0] & M;
c += x_0 * y_0;
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_0 * y_1;
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_0 * y_2;
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_0 * y_3;
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_0 * y_4;
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += x_0 * y_5;
zz[zzOff + 5] = (int)c;
c >>>= 32;
zz[zzOff + 6] = (int)c;
}
for (int i = 1; i < 6; ++i)
{
++zzOff;
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[zzOff + 5] & M);
zz[zzOff + 5] = (int)c;
c >>>= 32;
zz[zzOff + 6] = (int)c;
}
}
public static int mulAddTo(int[] x, int[] y, int[] zz)
{
long y_0 = y[0] & M;
long y_1 = y[1] & M;
long y_2 = y[2] & M;
long y_3 = y[3] & M;
long y_4 = y[4] & M;
long y_5 = y[5] & M;
long zc = 0;
for (int i = 0; i < 6; ++i)
{
long c = 0, x_i = x[i] & M;
c += x_i * y_0 + (zz[i + 0] & M);
zz[i + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[i + 1] & M);
zz[i + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[i + 2] & M);
zz[i + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[i + 3] & M);
zz[i + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[i + 4] & M);
zz[i + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[i + 5] & M);
zz[i + 5] = (int)c;
c >>>= 32;
c += zc + (zz[i + 6] & M);
zz[i + 6] = (int)c;
zc = c >>> 32;
}
return (int)zc;
}
public static int mulAddTo(int[] x, int xOff, int[] y, int yOff, int[] zz, int zzOff)
{
long y_0 = y[yOff + 0] & M;
long y_1 = y[yOff + 1] & M;
long y_2 = y[yOff + 2] & M;
long y_3 = y[yOff + 3] & M;
long y_4 = y[yOff + 4] & M;
long y_5 = y[yOff + 5] & M;
long zc = 0;
for (int i = 0; i < 6; ++i)
{
long c = 0, x_i = x[xOff + i] & M;
c += x_i * y_0 + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += x_i * y_1 + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += x_i * y_2 + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += x_i * y_3 + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += x_i * y_4 + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += x_i * y_5 + (zz[zzOff + 5] & M);
zz[zzOff + 5] = (int)c;
c >>>= 32;
c += zc + (zz[zzOff + 6] & M);
zz[zzOff + 6] = (int)c;
zc = c >>> 32;
++zzOff;
}
return (int)zc;
}
public static long mul33Add(int w, int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
// assert w >>> 31 == 0;
long c = 0, wVal = w & M;
long x0 = x[xOff + 0] & M;
c += wVal * x0 + (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long x1 = x[xOff + 1] & M;
c += wVal * x1 + x0 + (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
long x2 = x[xOff + 2] & M;
c += wVal * x2 + x1 + (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
long x3 = x[xOff + 3] & M;
c += wVal * x3 + x2 + (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
long x4 = x[xOff + 4] & M;
c += wVal * x4 + x3 + (y[yOff + 4] & M);
z[zOff + 4] = (int)c;
c >>>= 32;
long x5 = x[xOff + 5] & M;
c += wVal * x5 + x4 + (y[yOff + 5] & M);
z[zOff + 5] = (int)c;
c >>>= 32;
c += x5;
return c;
}
public static int mulWordAddExt(int x, int[] yy, int yyOff, int[] zz, int zzOff)
{
// assert yyOff <= 6;
// assert zzOff <= 6;
long c = 0, xVal = x & M;
c += xVal * (yy[yyOff + 0] & M) + (zz[zzOff + 0] & M);
zz[zzOff + 0] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 1] & M) + (zz[zzOff + 1] & M);
zz[zzOff + 1] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 2] & M) + (zz[zzOff + 2] & M);
zz[zzOff + 2] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 3] & M) + (zz[zzOff + 3] & M);
zz[zzOff + 3] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 4] & M) + (zz[zzOff + 4] & M);
zz[zzOff + 4] = (int)c;
c >>>= 32;
c += xVal * (yy[yyOff + 5] & M) + (zz[zzOff + 5] & M);
zz[zzOff + 5] = (int)c;
c >>>= 32;
return (int)c;
}
public static int mul33DWordAdd(int x, long y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 2;
long c = 0, xVal = x & M;
long y00 = y & M;
c += xVal * y00 + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
long y01 = y >>> 32;
c += xVal * y01 + y00 + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += y01 + (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
c += (z[zOff + 3] & M);
z[zOff + 3] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(6, z, zOff, 4);
}
public static int mul33WordAdd(int x, int y, int[] z, int zOff)
{
// assert x >>> 31 == 0;
// assert zOff <= 3;
long c = 0, xVal = x & M, yVal = y & M;
c += yVal * xVal + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += yVal + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(6, z, zOff, 3);
}
public static int mulWordDwordAdd(int x, long y, int[] z, int zOff)
{
// assert zOff <= 3;
long c = 0, xVal = x & M;
c += xVal * (y & M) + (z[zOff + 0] & M);
z[zOff + 0] = (int)c;
c >>>= 32;
c += xVal * (y >>> 32) + (z[zOff + 1] & M);
z[zOff + 1] = (int)c;
c >>>= 32;
c += (z[zOff + 2] & M);
z[zOff + 2] = (int)c;
c >>>= 32;
return c == 0 ? 0 : Nat.incAt(6, z, zOff, 3);
}
public static int mulWord(int x, int[] y, int[] z, int zOff)
{
long c = 0, xVal = x & M;
int i = 0;
do
{
c += xVal * (y[i] & M);
z[zOff + i] = (int)c;
c >>>= 32;
}
while (++i < 6);
return (int)c;
}
public static void square(int[] x, int[] zz)
{
long x_0 = x[0] & M;
long zz_1;
int c = 0, w;
{
int i = 5, j = 12;
do
{
long xVal = (x[i--] & M);
long p = xVal * xVal;
zz[--j] = (c << 31) | (int)(p >>> 33);
zz[--j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[1] & M;
long zz_2 = zz[2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[2] & M;
long zz_3 = zz[3] & M;
long zz_4 = zz[4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[3] & M;
long zz_5 = (zz[5] & M) + (zz_4 >>> 32); zz_4 &= M;
long zz_6 = (zz[6] & M) + (zz_5 >>> 32); zz_5 &= M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_4 &= M;
zz_6 += zz_5 >>> 32;
zz_5 &= M;
}
long x_4 = x[4] & M;
long zz_7 = (zz[7] & M) + (zz_6 >>> 32); zz_6 &= M;
long zz_8 = (zz[8] & M) + (zz_7 >>> 32); zz_7 &= M;
{
zz_4 += x_4 * x_0;
w = (int)zz_4;
zz[4] = (w << 1) | c;
c = w >>> 31;
zz_5 += (zz_4 >>> 32) + x_4 * x_1;
zz_6 += (zz_5 >>> 32) + x_4 * x_2;
zz_5 &= M;
zz_7 += (zz_6 >>> 32) + x_4 * x_3;
zz_6 &= M;
zz_8 += zz_7 >>> 32;
zz_7 &= M;
}
long x_5 = x[5] & M;
long zz_9 = (zz[9] & M) + (zz_8 >>> 32); zz_8 &= M;
long zz_10 = (zz[10] & M) + (zz_9 >>> 32); zz_9 &= M;
{
zz_5 += x_5 * x_0;
w = (int)zz_5;
zz[5] = (w << 1) | c;
c = w >>> 31;
zz_6 += (zz_5 >>> 32) + x_5 * x_1;
zz_7 += (zz_6 >>> 32) + x_5 * x_2;
zz_8 += (zz_7 >>> 32) + x_5 * x_3;
zz_9 += (zz_8 >>> 32) + x_5 * x_4;
zz_10 += zz_9 >>> 32;
}
w = (int)zz_6;
zz[6] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_7;
zz[7] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_8;
zz[8] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_9;
zz[9] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_10;
zz[10] = (w << 1) | c;
c = w >>> 31;
w = zz[11] + (int)(zz_10 >>> 32);
zz[11] = (w << 1) | c;
}
public static void square(int[] x, int xOff, int[] zz, int zzOff)
{
long x_0 = x[xOff + 0] & M;
long zz_1;
int c = 0, w;
{
int i = 5, j = 12;
do
{
long xVal = (x[xOff + i--] & M);
long p = xVal * xVal;
zz[zzOff + --j] = (c << 31) | (int)(p >>> 33);
zz[zzOff + --j] = (int)(p >>> 1);
c = (int)p;
}
while (i > 0);
{
long p = x_0 * x_0;
zz_1 = ((c << 31) & M) | (p >>> 33);
zz[zzOff + 0] = (int)p;
c = (int)(p >>> 32) & 1;
}
}
long x_1 = x[xOff + 1] & M;
long zz_2 = zz[zzOff + 2] & M;
{
zz_1 += x_1 * x_0;
w = (int)zz_1;
zz[zzOff + 1] = (w << 1) | c;
c = w >>> 31;
zz_2 += zz_1 >>> 32;
}
long x_2 = x[xOff + 2] & M;
long zz_3 = zz[zzOff + 3] & M;
long zz_4 = zz[zzOff + 4] & M;
{
zz_2 += x_2 * x_0;
w = (int)zz_2;
zz[zzOff + 2] = (w << 1) | c;
c = w >>> 31;
zz_3 += (zz_2 >>> 32) + x_2 * x_1;
zz_4 += zz_3 >>> 32;
zz_3 &= M;
}
long x_3 = x[xOff + 3] & M;
long zz_5 = (zz[zzOff + 5] & M) + (zz_4 >>> 32); zz_4 &= M;
long zz_6 = (zz[zzOff + 6] & M) + (zz_5 >>> 32); zz_5 &= M;
{
zz_3 += x_3 * x_0;
w = (int)zz_3;
zz[zzOff + 3] = (w << 1) | c;
c = w >>> 31;
zz_4 += (zz_3 >>> 32) + x_3 * x_1;
zz_5 += (zz_4 >>> 32) + x_3 * x_2;
zz_4 &= M;
zz_6 += zz_5 >>> 32;
zz_5 &= M;
}
long x_4 = x[xOff + 4] & M;
long zz_7 = (zz[zzOff + 7] & M) + (zz_6 >>> 32); zz_6 &= M;
long zz_8 = (zz[zzOff + 8] & M) + (zz_7 >>> 32); zz_7 &= M;
{
zz_4 += x_4 * x_0;
w = (int)zz_4;
zz[zzOff + 4] = (w << 1) | c;
c = w >>> 31;
zz_5 += (zz_4 >>> 32) + x_4 * x_1;
zz_6 += (zz_5 >>> 32) + x_4 * x_2;
zz_5 &= M;
zz_7 += (zz_6 >>> 32) + x_4 * x_3;
zz_6 &= M;
zz_8 += zz_7 >>> 32;
zz_7 &= M;
}
long x_5 = x[xOff + 5] & M;
long zz_9 = (zz[zzOff + 9] & M) + (zz_8 >>> 32); zz_8 &= M;
long zz_10 = (zz[zzOff + 10] & M) + (zz_9 >>> 32); zz_9 &= M;
{
zz_5 += x_5 * x_0;
w = (int)zz_5;
zz[zzOff + 5] = (w << 1) | c;
c = w >>> 31;
zz_6 += (zz_5 >>> 32) + x_5 * x_1;
zz_7 += (zz_6 >>> 32) + x_5 * x_2;
zz_8 += (zz_7 >>> 32) + x_5 * x_3;
zz_9 += (zz_8 >>> 32) + x_5 * x_4;
zz_10 += zz_9 >>> 32;
}
w = (int)zz_6;
zz[zzOff + 6] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_7;
zz[zzOff + 7] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_8;
zz[zzOff + 8] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_9;
zz[zzOff + 9] = (w << 1) | c;
c = w >>> 31;
w = (int)zz_10;
zz[zzOff + 10] = (w << 1) | c;
c = w >>> 31;
w = zz[zzOff + 11] + (int)(zz_10 >>> 32);
zz[zzOff + 11] = (w << 1) | c;
}
public static int sub(int[] x, int[] y, int[] z)
{
long c = 0;
c += (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
c += (x[4] & M) - (y[4] & M);
z[4] = (int)c;
c >>= 32;
c += (x[5] & M) - (y[5] & M);
z[5] = (int)c;
c >>= 32;
return (int)c;
}
public static int sub(int[] x, int xOff, int[] y, int yOff, int[] z, int zOff)
{
long c = 0;
c += (x[xOff + 0] & M) - (y[yOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (x[xOff + 1] & M) - (y[yOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (x[xOff + 2] & M) - (y[yOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (x[xOff + 3] & M) - (y[yOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
c += (x[xOff + 4] & M) - (y[yOff + 4] & M);
z[zOff + 4] = (int)c;
c >>= 32;
c += (x[xOff + 5] & M) - (y[yOff + 5] & M);
z[zOff + 5] = (int)c;
c >>= 32;
return (int)c;
}
public static int subBothFrom(int[] x, int[] y, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M) - (y[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M) - (y[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M) - (y[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M) - (y[3] & M);
z[3] = (int)c;
c >>= 32;
c += (z[4] & M) - (x[4] & M) - (y[4] & M);
z[4] = (int)c;
c >>= 32;
c += (z[5] & M) - (x[5] & M) - (y[5] & M);
z[5] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int[] z)
{
long c = 0;
c += (z[0] & M) - (x[0] & M);
z[0] = (int)c;
c >>= 32;
c += (z[1] & M) - (x[1] & M);
z[1] = (int)c;
c >>= 32;
c += (z[2] & M) - (x[2] & M);
z[2] = (int)c;
c >>= 32;
c += (z[3] & M) - (x[3] & M);
z[3] = (int)c;
c >>= 32;
c += (z[4] & M) - (x[4] & M);
z[4] = (int)c;
c >>= 32;
c += (z[5] & M) - (x[5] & M);
z[5] = (int)c;
c >>= 32;
return (int)c;
}
public static int subFrom(int[] x, int xOff, int[] z, int zOff)
{
long c = 0;
c += (z[zOff + 0] & M) - (x[xOff + 0] & M);
z[zOff + 0] = (int)c;
c >>= 32;
c += (z[zOff + 1] & M) - (x[xOff + 1] & M);
z[zOff + 1] = (int)c;
c >>= 32;
c += (z[zOff + 2] & M) - (x[xOff + 2] & M);
z[zOff + 2] = (int)c;
c >>= 32;
c += (z[zOff + 3] & M) - (x[xOff + 3] & M);
z[zOff + 3] = (int)c;
c >>= 32;
c += (z[zOff + 4] & M) - (x[xOff + 4] & M);
z[zOff + 4] = (int)c;
c >>= 32;
c += (z[zOff + 5] & M) - (x[xOff + 5] & M);
z[zOff + 5] = (int)c;
c >>= 32;
return (int)c;
}
public static BigInteger toBigInteger(int[] x)
{
byte[] bs = new byte[24];
for (int i = 0; i < 6; ++i)
{
int x_i = x[i];
if (x_i != 0)
{
Pack.intToBigEndian(x_i, bs, (5 - i) << 2);
}
}
return new BigInteger(1, bs);
}
public static BigInteger toBigInteger64(long[] x)
{
byte[] bs = new byte[24];
for (int i = 0; i < 3; ++i)
{
long x_i = x[i];
if (x_i != 0L)
{
Pack.longToBigEndian(x_i, bs, (2 - i) << 3);
}
}
return new BigInteger(1, bs);
}
public static void zero(int[] z)
{
z[0] = 0;
z[1] = 0;
z[2] = 0;
z[3] = 0;
z[4] = 0;
z[5] = 0;
}
}
| ./CrossVul/dataset_final_sorted/CWE-19/java/good_4757_2 |
crossvul-java_data_good_4952_0 | /*****************************************************************************
* 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. *
* *
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* Patrick Niemeyer (pat@pat.net) *
* Author of Learning Java, O'Reilly & Associates *
* *
*****************************************************************************/
package bsh;
import java.lang.reflect.*;
import java.lang.reflect.InvocationHandler;
import java.io.*;
import java.util.Hashtable;
/**
XThis is a dynamically loaded extension which extends This.java and adds
support for the generalized interface proxy mechanism introduced in
JDK1.3. XThis allows bsh scripted objects to implement arbitrary
interfaces (be arbitrary event listener types).
Note: This module relies on new features of JDK1.3 and will not compile
with JDK1.2 or lower. For those environments simply do not compile this
class.
Eventually XThis should become simply This, but for backward compatibility
we will maintain This without requiring support for the proxy mechanism.
XThis stands for "eXtended This" (I had to call it something).
@see JThis See also JThis with explicit JFC support for compatibility.
@see This
*/
public class XThis extends This
{
/**
A cache of proxy interface handlers.
Currently just one per interface.
*/
Hashtable interfaces;
transient InvocationHandler invocationHandler = new Handler();
public XThis( NameSpace namespace, Interpreter declaringInterp ) {
super( namespace, declaringInterp );
}
public String toString() {
return "'this' reference (XThis) to Bsh object: " + namespace;
}
/**
Get dynamic proxy for interface, caching those it creates.
*/
public Object getInterface( Class clas )
{
return getInterface( new Class[] { clas } );
}
/**
Get dynamic proxy for interface, caching those it creates.
*/
public Object getInterface( Class [] ca )
{
if ( interfaces == null )
interfaces = new Hashtable();
// Make a hash of the interface hashcodes in order to cache them
int hash = 21;
for(int i=0; i<ca.length; i++)
hash *= ca[i].hashCode() + 3;
Object hashKey = new Integer(hash);
Object interf = interfaces.get( hashKey );
if ( interf == null )
{
ClassLoader classLoader = ca[0].getClassLoader(); // ?
interf = Proxy.newProxyInstance(
classLoader, ca, invocationHandler );
interfaces.put( hashKey, interf );
}
return interf;
}
/**
This is the invocation handler for the dynamic proxy.
<p>
Notes:
Inner class for the invocation handler seems to shield this unavailable
interface from JDK1.2 VM...
I don't understand this. JThis works just fine even if those
classes aren't there (doesn't it?) This class shouldn't be loaded
if an XThis isn't instantiated in NameSpace.java, should it?
*/
class Handler implements InvocationHandler
{
private Object readResolve() throws ObjectStreamException {
throw new NotSerializableException();
}
public Object invoke( Object proxy, Method method, Object[] args )
throws Throwable
{
try {
return invokeImpl( proxy, method, args );
} catch ( TargetError te ) {
// Unwrap target exception. If the interface declares that
// it throws the ex it will be delivered. If not it will be
// wrapped in an UndeclaredThrowable
throw te.getTarget();
} catch ( EvalError ee ) {
// Ease debugging...
// XThis.this refers to the enclosing class instance
if ( Interpreter.DEBUG )
Interpreter.debug( "EvalError in scripted interface: "
+ XThis.this.toString() + ": "+ ee );
throw ee;
}
}
public Object invokeImpl( Object proxy, Method method, Object[] args )
throws EvalError
{
String methodName = method.getName();
CallStack callstack = new CallStack( namespace );
/*
If equals() is not explicitly defined we must override the
default implemented by the This object protocol for scripted
object. To support XThis equals() must test for equality with
the generated proxy object, not the scripted bsh This object;
otherwise callers from outside in Java will not see a the
proxy object as equal to itself.
*/
BshMethod equalsMethod = null;
try {
equalsMethod = namespace.getMethod(
"equals", new Class [] { Object.class } );
} catch ( UtilEvalError e ) {/*leave null*/ }
if ( methodName.equals("equals" ) && equalsMethod == null ) {
Object obj = args[0];
return proxy == obj ? Boolean.TRUE : Boolean.FALSE;
}
/*
If toString() is not explicitly defined override the default
to show the proxy interfaces.
*/
BshMethod toStringMethod = null;
try {
toStringMethod =
namespace.getMethod( "toString", new Class [] { } );
} catch ( UtilEvalError e ) {/*leave null*/ }
if ( methodName.equals("toString" ) && toStringMethod == null)
{
Class [] ints = proxy.getClass().getInterfaces();
// XThis.this refers to the enclosing class instance
StringBuffer sb = new StringBuffer(
XThis.this.toString() + "\nimplements:" );
for(int i=0; i<ints.length; i++)
sb.append( " "+ ints[i].getName()
+ ((ints.length > 1)?",":"") );
return sb.toString();
}
Class [] paramTypes = method.getParameterTypes();
return Primitive.unwrap(
invokeMethod( methodName, Primitive.wrap(args, paramTypes) ) );
}
};
}
| ./CrossVul/dataset_final_sorted/CWE-19/java/good_4952_0 |
crossvul-java_data_good_1927_2 | /*
* Copyright 2012 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 io.netty.handler.codec.http.multipart;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.HttpConstants;
import io.netty.util.internal.EmptyArrays;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import static io.netty.buffer.Unpooled.EMPTY_BUFFER;
import static io.netty.buffer.Unpooled.wrappedBuffer;
/**
* Abstract Disk HttpData implementation
*/
public abstract class AbstractDiskHttpData extends AbstractHttpData {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractDiskHttpData.class);
private File file;
private boolean isRenamed;
private FileChannel fileChannel;
protected AbstractDiskHttpData(String name, Charset charset, long size) {
super(name, charset, size);
}
/**
*
* @return the real DiskFilename (basename)
*/
protected abstract String getDiskFilename();
/**
*
* @return the default prefix
*/
protected abstract String getPrefix();
/**
*
* @return the default base Directory
*/
protected abstract String getBaseDirectory();
/**
*
* @return the default postfix
*/
protected abstract String getPostfix();
/**
*
* @return True if the file should be deleted on Exit by default
*/
protected abstract boolean deleteOnExit();
/**
* @return a new Temp File from getDiskFilename(), default prefix, postfix and baseDirectory
*/
private File tempFile() throws IOException {
String newpostfix;
String diskFilename = getDiskFilename();
if (diskFilename != null) {
newpostfix = '_' + diskFilename;
} else {
newpostfix = getPostfix();
}
File tmpFile;
if (getBaseDirectory() == null) {
// create a temporary file
tmpFile = PlatformDependent.createTempFile(getPrefix(), newpostfix, null);
} else {
tmpFile = PlatformDependent.createTempFile(getPrefix(), newpostfix, new File(
getBaseDirectory()));
}
if (deleteOnExit()) {
// See https://github.com/netty/netty/issues/10351
DeleteFileOnExitHook.add(tmpFile.getPath());
}
return tmpFile;
}
@Override
public void setContent(ByteBuf buffer) throws IOException {
ObjectUtil.checkNotNull(buffer, "buffer");
try {
size = buffer.readableBytes();
checkSize(size);
if (definedSize > 0 && definedSize < size) {
throw new IOException("Out of size: " + size + " > " + definedSize);
}
if (file == null) {
file = tempFile();
}
if (buffer.readableBytes() == 0) {
// empty file
if (!file.createNewFile()) {
if (file.length() == 0) {
return;
} else {
if (!file.delete() || !file.createNewFile()) {
throw new IOException("file exists already: " + file);
}
}
}
return;
}
RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
try {
accessFile.setLength(0);
FileChannel localfileChannel = accessFile.getChannel();
ByteBuffer byteBuffer = buffer.nioBuffer();
int written = 0;
while (written < size) {
written += localfileChannel.write(byteBuffer);
}
buffer.readerIndex(buffer.readerIndex() + written);
localfileChannel.force(false);
} finally {
accessFile.close();
}
setCompleted();
} finally {
// Release the buffer as it was retained before and we not need a reference to it at all
// See https://github.com/netty/netty/issues/1516
buffer.release();
}
}
@Override
public void addContent(ByteBuf buffer, boolean last)
throws IOException {
if (buffer != null) {
try {
int localsize = buffer.readableBytes();
checkSize(size + localsize);
if (definedSize > 0 && definedSize < size + localsize) {
throw new IOException("Out of size: " + (size + localsize) +
" > " + definedSize);
}
if (file == null) {
file = tempFile();
}
if (fileChannel == null) {
RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
fileChannel = accessFile.getChannel();
}
int remaining = localsize;
long position = fileChannel.position();
int index = buffer.readerIndex();
while (remaining > 0) {
int written = buffer.getBytes(index, fileChannel, position, remaining);
if (written < 0) {
break;
}
remaining -= written;
position += written;
index += written;
}
fileChannel.position(position);
buffer.readerIndex(index);
size += localsize - remaining;
} finally {
// Release the buffer as it was retained before and we not need a reference to it at all
// See https://github.com/netty/netty/issues/1516
buffer.release();
}
}
if (last) {
if (file == null) {
file = tempFile();
}
if (fileChannel == null) {
RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
fileChannel = accessFile.getChannel();
}
try {
fileChannel.force(false);
} finally {
fileChannel.close();
}
fileChannel = null;
setCompleted();
} else {
ObjectUtil.checkNotNull(buffer, "buffer");
}
}
@Override
public void setContent(File file) throws IOException {
long size = file.length();
checkSize(size);
this.size = size;
if (this.file != null) {
delete();
}
this.file = file;
isRenamed = true;
setCompleted();
}
@Override
public void setContent(InputStream inputStream) throws IOException {
ObjectUtil.checkNotNull(inputStream, "inputStream");
if (file != null) {
delete();
}
file = tempFile();
RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
int written = 0;
try {
accessFile.setLength(0);
FileChannel localfileChannel = accessFile.getChannel();
byte[] bytes = new byte[4096 * 4];
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
int read = inputStream.read(bytes);
while (read > 0) {
byteBuffer.position(read).flip();
written += localfileChannel.write(byteBuffer);
checkSize(written);
read = inputStream.read(bytes);
}
localfileChannel.force(false);
} finally {
accessFile.close();
}
size = written;
if (definedSize > 0 && definedSize < size) {
if (!file.delete()) {
logger.warn("Failed to delete: {}", file);
}
file = null;
throw new IOException("Out of size: " + size + " > " + definedSize);
}
isRenamed = true;
setCompleted();
}
@Override
public void delete() {
if (fileChannel != null) {
try {
fileChannel.force(false);
} catch (IOException e) {
logger.warn("Failed to force.", e);
} finally {
try {
fileChannel.close();
} catch (IOException e) {
logger.warn("Failed to close a file.", e);
}
}
fileChannel = null;
}
if (!isRenamed) {
String filePath = null;
if (file != null && file.exists()) {
filePath = file.getPath();
if (!file.delete()) {
filePath = null;
logger.warn("Failed to delete: {}", file);
}
}
// If you turn on deleteOnExit make sure it is executed.
if (deleteOnExit() && filePath != null) {
DeleteFileOnExitHook.remove(filePath);
}
file = null;
}
}
@Override
public byte[] get() throws IOException {
if (file == null) {
return EmptyArrays.EMPTY_BYTES;
}
return readFrom(file);
}
@Override
public ByteBuf getByteBuf() throws IOException {
if (file == null) {
return EMPTY_BUFFER;
}
byte[] array = readFrom(file);
return wrappedBuffer(array);
}
@Override
public ByteBuf getChunk(int length) throws IOException {
if (file == null || length == 0) {
return EMPTY_BUFFER;
}
if (fileChannel == null) {
RandomAccessFile accessFile = new RandomAccessFile(file, "r");
fileChannel = accessFile.getChannel();
}
int read = 0;
ByteBuffer byteBuffer = ByteBuffer.allocate(length);
try {
while (read < length) {
int readnow = fileChannel.read(byteBuffer);
if (readnow == -1) {
fileChannel.close();
fileChannel = null;
break;
}
read += readnow;
}
} catch (IOException e) {
fileChannel.close();
fileChannel = null;
throw e;
}
if (read == 0) {
return EMPTY_BUFFER;
}
byteBuffer.flip();
ByteBuf buffer = wrappedBuffer(byteBuffer);
buffer.readerIndex(0);
buffer.writerIndex(read);
return buffer;
}
@Override
public String getString() throws IOException {
return getString(HttpConstants.DEFAULT_CHARSET);
}
@Override
public String getString(Charset encoding) throws IOException {
if (file == null) {
return "";
}
if (encoding == null) {
byte[] array = readFrom(file);
return new String(array, HttpConstants.DEFAULT_CHARSET.name());
}
byte[] array = readFrom(file);
return new String(array, encoding.name());
}
@Override
public boolean isInMemory() {
return false;
}
@Override
public boolean renameTo(File dest) throws IOException {
ObjectUtil.checkNotNull(dest, "dest");
if (file == null) {
throw new IOException("No file defined so cannot be renamed");
}
if (!file.renameTo(dest)) {
// must copy
IOException exception = null;
RandomAccessFile inputAccessFile = null;
RandomAccessFile outputAccessFile = null;
long chunkSize = 8196;
long position = 0;
try {
inputAccessFile = new RandomAccessFile(file, "r");
outputAccessFile = new RandomAccessFile(dest, "rw");
FileChannel in = inputAccessFile.getChannel();
FileChannel out = outputAccessFile.getChannel();
while (position < size) {
if (chunkSize < size - position) {
chunkSize = size - position;
}
position += in.transferTo(position, chunkSize, out);
}
} catch (IOException e) {
exception = e;
} finally {
if (inputAccessFile != null) {
try {
inputAccessFile.close();
} catch (IOException e) {
if (exception == null) { // Choose to report the first exception
exception = e;
} else {
logger.warn("Multiple exceptions detected, the following will be suppressed {}", e);
}
}
}
if (outputAccessFile != null) {
try {
outputAccessFile.close();
} catch (IOException e) {
if (exception == null) { // Choose to report the first exception
exception = e;
} else {
logger.warn("Multiple exceptions detected, the following will be suppressed {}", e);
}
}
}
}
if (exception != null) {
throw exception;
}
if (position == size) {
if (!file.delete()) {
logger.warn("Failed to delete: {}", file);
}
file = dest;
isRenamed = true;
return true;
} else {
if (!dest.delete()) {
logger.warn("Failed to delete: {}", dest);
}
return false;
}
}
file = dest;
isRenamed = true;
return true;
}
/**
* Utility function
*
* @return the array of bytes
*/
private static byte[] readFrom(File src) throws IOException {
long srcsize = src.length();
if (srcsize > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"File too big to be loaded in memory");
}
RandomAccessFile accessFile = new RandomAccessFile(src, "r");
byte[] array = new byte[(int) srcsize];
try {
FileChannel fileChannel = accessFile.getChannel();
ByteBuffer byteBuffer = ByteBuffer.wrap(array);
int read = 0;
while (read < srcsize) {
read += fileChannel.read(byteBuffer);
}
} finally {
accessFile.close();
}
return array;
}
@Override
public File getFile() throws IOException {
return file;
}
@Override
public HttpData touch() {
return this;
}
@Override
public HttpData touch(Object hint) {
return this;
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_2 |
crossvul-java_data_good_1927_1 | /*
* Copyright 2013 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 io.netty.buffer;
import io.netty.util.internal.PlatformDependent;
import org.junit.Assert;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import java.nio.channels.FileChannel;
public class ReadOnlyDirectByteBufferBufTest {
protected ByteBuf buffer(ByteBuffer buffer) {
return new ReadOnlyByteBufferBuf(UnpooledByteBufAllocator.DEFAULT, buffer);
}
protected ByteBuffer allocate(int size) {
return ByteBuffer.allocateDirect(size);
}
@Test
public void testIsContiguous() {
ByteBuf buf = buffer(allocate(4).asReadOnlyBuffer());
Assert.assertTrue(buf.isContiguous());
buf.release();
}
@Test(expected = IllegalArgumentException.class)
public void testConstructWithWritable() {
buffer(allocate(1));
}
@Test
public void shouldIndicateNotWritable() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear();
try {
Assert.assertFalse(buf.isWritable());
} finally {
buf.release();
}
}
@Test
public void shouldIndicateNotWritableAnyNumber() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear();
try {
Assert.assertFalse(buf.isWritable(1));
} finally {
buf.release();
}
}
@Test
public void ensureWritableIntStatusShouldFailButNotThrow() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear();
try {
int result = buf.ensureWritable(1, false);
Assert.assertEquals(1, result);
} finally {
buf.release();
}
}
@Test
public void ensureWritableForceIntStatusShouldFailButNotThrow() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear();
try {
int result = buf.ensureWritable(1, true);
Assert.assertEquals(1, result);
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void ensureWritableShouldThrow() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear();
try {
buf.ensureWritable(1);
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetByte() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try {
buf.setByte(0, 1);
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetInt() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try {
buf.setInt(0, 1);
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetShort() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try {
buf.setShort(0, 1);
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetMedium() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try {
buf.setMedium(0, 1);
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetLong() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try {
buf.setLong(0, 1);
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetBytesViaArray() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try {
buf.setBytes(0, "test".getBytes());
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetBytesViaBuffer() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
ByteBuf copy = Unpooled.copyInt(1);
try {
buf.setBytes(0, copy);
} finally {
buf.release();
copy.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetBytesViaStream() throws IOException {
ByteBuf buf = buffer(ByteBuffer.allocateDirect(8).asReadOnlyBuffer());
try {
buf.setBytes(0, new ByteArrayInputStream("test".getBytes()), 2);
} finally {
buf.release();
}
}
@Test
public void testGetReadByte() {
ByteBuf buf = buffer(
((ByteBuffer) allocate(2).put(new byte[] { (byte) 1, (byte) 2 }).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.getByte(0));
Assert.assertEquals(2, buf.getByte(1));
Assert.assertEquals(1, buf.readByte());
Assert.assertEquals(2, buf.readByte());
Assert.assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testGetReadInt() {
ByteBuf buf = buffer(((ByteBuffer) allocate(8).putInt(1).putInt(2).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.getInt(0));
Assert.assertEquals(2, buf.getInt(4));
Assert.assertEquals(1, buf.readInt());
Assert.assertEquals(2, buf.readInt());
Assert.assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testGetReadShort() {
ByteBuf buf = buffer(((ByteBuffer) allocate(8)
.putShort((short) 1).putShort((short) 2).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.getShort(0));
Assert.assertEquals(2, buf.getShort(2));
Assert.assertEquals(1, buf.readShort());
Assert.assertEquals(2, buf.readShort());
Assert.assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testGetReadLong() {
ByteBuf buf = buffer(((ByteBuffer) allocate(16)
.putLong(1).putLong(2).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.getLong(0));
Assert.assertEquals(2, buf.getLong(8));
Assert.assertEquals(1, buf.readLong());
Assert.assertEquals(2, buf.readLong());
Assert.assertFalse(buf.isReadable());
buf.release();
}
@Test(expected = IndexOutOfBoundsException.class)
public void testGetBytesByteBuffer() {
byte[] bytes = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
// Ensure destination buffer is bigger then what is in the ByteBuf.
ByteBuffer nioBuffer = ByteBuffer.allocate(bytes.length + 1);
ByteBuf buffer = buffer(((ByteBuffer) allocate(bytes.length)
.put(bytes).flip()).asReadOnlyBuffer());
try {
buffer.getBytes(buffer.readerIndex(), nioBuffer);
} finally {
buffer.release();
}
}
@Test
public void testCopy() {
ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer());
ByteBuf copy = buf.copy();
Assert.assertEquals(buf, copy);
buf.release();
copy.release();
}
@Test
public void testCopyWithOffset() {
ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer());
ByteBuf copy = buf.copy(1, 9);
Assert.assertEquals(buf.slice(1, 9), copy);
buf.release();
copy.release();
}
// Test for https://github.com/netty/netty/issues/1708
@Test
public void testWrapBufferWithNonZeroPosition() {
ByteBuf buf = buffer(((ByteBuffer) allocate(16)
.putLong(1).flip().position(1)).asReadOnlyBuffer());
ByteBuf slice = buf.slice();
Assert.assertEquals(buf, slice);
buf.release();
}
@Test
public void testWrapBufferRoundTrip() {
ByteBuf buf = buffer(((ByteBuffer) allocate(16).putInt(1).putInt(2).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.readInt());
ByteBuffer nioBuffer = buf.nioBuffer();
// Ensure this can be accessed without throwing a BufferUnderflowException
Assert.assertEquals(2, nioBuffer.getInt());
buf.release();
}
@Test
public void testWrapMemoryMapped() throws Exception {
File file = PlatformDependent.createTempFile("netty-test", "tmp", null);
FileChannel output = null;
FileChannel input = null;
ByteBuf b1 = null;
ByteBuf b2 = null;
try {
output = new RandomAccessFile(file, "rw").getChannel();
byte[] bytes = new byte[1024];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
output.write(ByteBuffer.wrap(bytes));
input = new RandomAccessFile(file, "r").getChannel();
ByteBuffer m = input.map(FileChannel.MapMode.READ_ONLY, 0, input.size());
b1 = buffer(m);
ByteBuffer dup = m.duplicate();
dup.position(2);
dup.limit(4);
b2 = buffer(dup);
Assert.assertEquals(b2, b1.slice(2, 2));
} finally {
if (b1 != null) {
b1.release();
}
if (b2 != null) {
b2.release();
}
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
file.delete();
}
}
@Test
public void testMemoryAddress() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try {
Assert.assertFalse(buf.hasMemoryAddress());
try {
buf.memoryAddress();
Assert.fail();
} catch (UnsupportedOperationException expected) {
// expected
}
} finally {
buf.release();
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_1 |
crossvul-java_data_good_1927_12 | /*
* Copyright 2012 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 io.netty.testsuite.transport.socket;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.FileRegion;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.internal.PlatformDependent;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.WritableByteChannel;
import java.util.Random;
import java.util.concurrent.atomic.AtomicReference;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.*;
public class SocketFileRegionTest extends AbstractSocketTest {
static final byte[] data = new byte[1048576 * 10];
static {
PlatformDependent.threadLocalRandom().nextBytes(data);
}
@Test
public void testFileRegion() throws Throwable {
run();
}
@Test
public void testCustomFileRegion() throws Throwable {
run();
}
@Test
public void testFileRegionNotAutoRead() throws Throwable {
run();
}
@Test
public void testFileRegionVoidPromise() throws Throwable {
run();
}
@Test
public void testFileRegionVoidPromiseNotAutoRead() throws Throwable {
run();
}
@Test
public void testFileRegionCountLargerThenFile() throws Throwable {
run();
}
public void testFileRegion(ServerBootstrap sb, Bootstrap cb) throws Throwable {
testFileRegion0(sb, cb, false, true, true);
}
public void testCustomFileRegion(ServerBootstrap sb, Bootstrap cb) throws Throwable {
testFileRegion0(sb, cb, false, true, false);
}
public void testFileRegionVoidPromise(ServerBootstrap sb, Bootstrap cb) throws Throwable {
testFileRegion0(sb, cb, true, true, true);
}
public void testFileRegionNotAutoRead(ServerBootstrap sb, Bootstrap cb) throws Throwable {
testFileRegion0(sb, cb, false, false, true);
}
public void testFileRegionVoidPromiseNotAutoRead(ServerBootstrap sb, Bootstrap cb) throws Throwable {
testFileRegion0(sb, cb, true, false, true);
}
public void testFileRegionCountLargerThenFile(ServerBootstrap sb, Bootstrap cb) throws Throwable {
File file = PlatformDependent.createTempFile("netty-", ".tmp", null);
file.deleteOnExit();
final FileOutputStream out = new FileOutputStream(file);
out.write(data);
out.close();
sb.childHandler(new SimpleChannelInboundHandler<ByteBuf>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
// Just drop the message.
}
});
cb.handler(new ChannelInboundHandlerAdapter());
Channel sc = sb.bind().sync().channel();
Channel cc = cb.connect(sc.localAddress()).sync().channel();
// Request file region which is bigger then the underlying file.
FileRegion region = new DefaultFileRegion(
new RandomAccessFile(file, "r").getChannel(), 0, data.length + 1024);
assertThat(cc.writeAndFlush(region).await().cause(), CoreMatchers.<Throwable>instanceOf(IOException.class));
cc.close().sync();
sc.close().sync();
}
private static void testFileRegion0(
ServerBootstrap sb, Bootstrap cb, boolean voidPromise, final boolean autoRead, boolean defaultFileRegion)
throws Throwable {
sb.childOption(ChannelOption.AUTO_READ, autoRead);
cb.option(ChannelOption.AUTO_READ, autoRead);
final int bufferSize = 1024;
final File file = PlatformDependent.createTempFile("netty-", ".tmp", null);
file.deleteOnExit();
final FileOutputStream out = new FileOutputStream(file);
final Random random = PlatformDependent.threadLocalRandom();
// Prepend random data which will not be transferred, so that we can test non-zero start offset
final int startOffset = random.nextInt(8192);
for (int i = 0; i < startOffset; i ++) {
out.write(random.nextInt());
}
// .. and here comes the real data to transfer.
out.write(data, bufferSize, data.length - bufferSize);
// .. and then some extra data which is not supposed to be transferred.
for (int i = random.nextInt(8192); i > 0; i --) {
out.write(random.nextInt());
}
out.close();
ChannelInboundHandler ch = new SimpleChannelInboundHandler<Object>() {
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
if (!autoRead) {
ctx.read();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
};
TestHandler sh = new TestHandler(autoRead);
sb.childHandler(sh);
cb.handler(ch);
Channel sc = sb.bind().sync().channel();
Channel cc = cb.connect(sc.localAddress()).sync().channel();
FileRegion region = new DefaultFileRegion(
new RandomAccessFile(file, "r").getChannel(), startOffset, data.length - bufferSize);
FileRegion emptyRegion = new DefaultFileRegion(new RandomAccessFile(file, "r").getChannel(), 0, 0);
if (!defaultFileRegion) {
region = new FileRegionWrapper(region);
emptyRegion = new FileRegionWrapper(emptyRegion);
}
// Do write ByteBuf and then FileRegion to ensure that mixed writes work
// Also, write an empty FileRegion to test if writing an empty FileRegion does not cause any issues.
//
// See https://github.com/netty/netty/issues/2769
// https://github.com/netty/netty/issues/2964
if (voidPromise) {
assertEquals(cc.voidPromise(), cc.write(Unpooled.wrappedBuffer(data, 0, bufferSize), cc.voidPromise()));
assertEquals(cc.voidPromise(), cc.write(emptyRegion, cc.voidPromise()));
assertEquals(cc.voidPromise(), cc.writeAndFlush(region, cc.voidPromise()));
} else {
assertNotEquals(cc.voidPromise(), cc.write(Unpooled.wrappedBuffer(data, 0, bufferSize)));
assertNotEquals(cc.voidPromise(), cc.write(emptyRegion));
assertNotEquals(cc.voidPromise(), cc.writeAndFlush(region));
}
while (sh.counter < data.length) {
if (sh.exception.get() != null) {
break;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore.
}
}
sh.channel.close().sync();
cc.close().sync();
sc.close().sync();
if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
throw sh.exception.get();
}
if (sh.exception.get() != null) {
throw sh.exception.get();
}
// Make sure we did not receive more than we expected.
assertThat(sh.counter, is(data.length));
}
private static class TestHandler extends SimpleChannelInboundHandler<ByteBuf> {
private final boolean autoRead;
volatile Channel channel;
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
volatile int counter;
TestHandler(boolean autoRead) {
this.autoRead = autoRead;
}
@Override
public void channelActive(ChannelHandlerContext ctx)
throws Exception {
channel = ctx.channel();
if (!autoRead) {
ctx.read();
}
}
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
byte[] actual = new byte[in.readableBytes()];
in.readBytes(actual);
int lastIdx = counter;
for (int i = 0; i < actual.length; i ++) {
assertEquals(data[i + lastIdx], actual[i]);
}
counter += actual.length;
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
if (!autoRead) {
ctx.read();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) throws Exception {
if (exception.compareAndSet(null, cause)) {
ctx.close();
}
}
}
private static final class FileRegionWrapper implements FileRegion {
private final FileRegion region;
FileRegionWrapper(FileRegion region) {
this.region = region;
}
@Override
public int refCnt() {
return region.refCnt();
}
@Override
public long position() {
return region.position();
}
@Override
@Deprecated
public long transfered() {
return region.transferred();
}
@Override
public boolean release() {
return region.release();
}
@Override
public long transferred() {
return region.transferred();
}
@Override
public long count() {
return region.count();
}
@Override
public boolean release(int decrement) {
return region.release(decrement);
}
@Override
public long transferTo(WritableByteChannel target, long position) throws IOException {
return region.transferTo(target, position);
}
@Override
public FileRegion retain() {
region.retain();
return this;
}
@Override
public FileRegion retain(int increment) {
region.retain(increment);
return this;
}
@Override
public FileRegion touch() {
region.touch();
return this;
}
@Override
public FileRegion touch(Object hint) {
region.touch(hint);
return this;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_12 |
crossvul-java_data_good_1927_11 | /*
* Copyright 2020 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 io.netty.handler.traffic;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.PlatformDependent;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.SocketAddress;
import java.nio.charset.Charset;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import static org.junit.Assert.assertTrue;
public class FileRegionThrottleTest {
private static final byte[] BYTES = new byte[64 * 1024 * 4];
private static final long WRITE_LIMIT = 64 * 1024;
private static File tmp;
private EventLoopGroup group;
@BeforeClass
public static void beforeClass() throws IOException {
final Random r = new Random();
for (int i = 0; i < BYTES.length; i++) {
BYTES[i] = (byte) r.nextInt(255);
}
tmp = PlatformDependent.createTempFile("netty-traffic", ".tmp", null);
tmp.deleteOnExit();
FileOutputStream out = null;
try {
out = new FileOutputStream(tmp);
out.write(BYTES);
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignore
}
}
}
}
@Before
public void setUp() {
group = new NioEventLoopGroup();
}
@After
public void tearDown() {
group.shutdownGracefully();
}
@Test
public void testGlobalWriteThrottle() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final GlobalTrafficShapingHandler gtsh = new GlobalTrafficShapingHandler(group, WRITE_LIMIT, 0);
ServerBootstrap bs = new ServerBootstrap();
bs.group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new LineBasedFrameDecoder(Integer.MAX_VALUE));
ch.pipeline().addLast(new MessageDecoder());
ch.pipeline().addLast(gtsh);
}
});
Channel sc = bs.bind(0).sync().channel();
Channel cc = clientConnect(sc.localAddress(), new ReadHandler(latch)).channel();
long start = TrafficCounter.milliSecondFromNano();
cc.writeAndFlush(Unpooled.copiedBuffer("send-file\n", CharsetUtil.US_ASCII)).sync();
latch.await();
long timeTaken = TrafficCounter.milliSecondFromNano() - start;
assertTrue("Data streamed faster than expected", timeTaken > 3000);
sc.close().sync();
cc.close().sync();
}
private ChannelFuture clientConnect(final SocketAddress server, final ReadHandler readHandler) throws Exception {
Bootstrap bc = new Bootstrap();
bc.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(readHandler);
}
});
return bc.connect(server).sync();
}
private static final class MessageDecoder extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof ByteBuf) {
ByteBuf buf = (ByteBuf) msg;
String message = buf.toString(Charset.defaultCharset());
buf.release();
if (message.equals("send-file")) {
RandomAccessFile raf = new RandomAccessFile(tmp, "r");
ctx.channel().writeAndFlush(new DefaultFileRegion(raf.getChannel(), 0, tmp.length()));
}
}
}
}
private static final class ReadHandler extends ChannelInboundHandlerAdapter {
private long bytesTransferred;
private CountDownLatch latch;
ReadHandler(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof ByteBuf) {
ByteBuf buf = (ByteBuf) msg;
bytesTransferred += buf.readableBytes();
buf.release();
if (bytesTransferred == tmp.length()) {
latch.countDown();
}
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_11 |
crossvul-java_data_good_1927_4 | /*
* Copyright 2020 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 io.netty.handler.codec.http.multipart;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.UUID;
import static io.netty.util.CharsetUtil.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
/**
* {@link AbstractDiskHttpData} test cases
*/
public class AbstractDiskHttpDataTest {
@Test
public void testGetChunk() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), ".tmp", null);
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] bytes = new byte[4096];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
test.setContent(tmpFile);
ByteBuf buf1 = test.getChunk(1024);
assertEquals(buf1.readerIndex(), 0);
assertEquals(buf1.writerIndex(), 1024);
ByteBuf buf2 = test.getChunk(1024);
assertEquals(buf2.readerIndex(), 0);
assertEquals(buf2.writerIndex(), 1024);
assertFalse("Arrays should not be equal",
Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2)));
} finally {
test.delete();
}
}
private static final class TestHttpData extends AbstractDiskHttpData {
private TestHttpData(String name, Charset charset, long size) {
super(name, charset, size);
}
@Override
protected String getDiskFilename() {
return null;
}
@Override
protected String getPrefix() {
return null;
}
@Override
protected String getBaseDirectory() {
return null;
}
@Override
protected String getPostfix() {
return null;
}
@Override
protected boolean deleteOnExit() {
return false;
}
@Override
public HttpData copy() {
return null;
}
@Override
public HttpData duplicate() {
return null;
}
@Override
public HttpData retainedDuplicate() {
return null;
}
@Override
public HttpData replace(ByteBuf content) {
return null;
}
@Override
public HttpDataType getHttpDataType() {
return null;
}
@Override
public int compareTo(InterfaceHttpData o) {
return 0;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_4 |
crossvul-java_data_bad_1927_13 | /*
* Copyright 2015 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 io.netty.channel.epoll;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.unix.FileDescriptor;
import io.netty.util.NetUtil;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
public class EpollSpliceTest {
private static final int SPLICE_LEN = 32 * 1024;
private static final Random random = new Random();
private static final byte[] data = new byte[1048576];
static {
random.nextBytes(data);
}
@Test
public void spliceToSocket() throws Throwable {
final EchoHandler sh = new EchoHandler();
final EchoHandler ch = new EchoHandler();
EventLoopGroup group = new EpollEventLoopGroup(1);
ServerBootstrap bs = new ServerBootstrap();
bs.channel(EpollServerSocketChannel.class);
bs.group(group).childHandler(sh);
final Channel sc = bs.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel();
ServerBootstrap bs2 = new ServerBootstrap();
bs2.channel(EpollServerSocketChannel.class);
bs2.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
bs2.group(group).childHandler(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
ctx.channel().config().setAutoRead(false);
Bootstrap bs = new Bootstrap();
bs.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
bs.channel(EpollSocketChannel.class);
bs.group(ctx.channel().eventLoop()).handler(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(ChannelHandlerContext context) throws Exception {
final EpollSocketChannel ch = (EpollSocketChannel) ctx.channel();
final EpollSocketChannel ch2 = (EpollSocketChannel) context.channel();
// We are splicing two channels together, at this point we have a tcp proxy which handles all
// the data transfer only in kernel space!
// Integer.MAX_VALUE will splice infinitly.
ch.spliceTo(ch2, Integer.MAX_VALUE).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
future.channel().close();
}
}
});
// Trigger multiple splices to see if partial splicing works as well.
ch2.spliceTo(ch, SPLICE_LEN).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
future.channel().close();
} else {
ch2.spliceTo(ch, SPLICE_LEN).addListener(this);
}
}
});
ctx.channel().config().setAutoRead(true);
}
@Override
public void channelInactive(ChannelHandlerContext context) throws Exception {
context.close();
}
});
bs.connect(sc.localAddress()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
ctx.close();
} else {
future.channel().closeFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
ctx.close();
}
});
}
}
});
}
});
Channel pc = bs2.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel();
Bootstrap cb = new Bootstrap();
cb.group(group);
cb.channel(EpollSocketChannel.class);
cb.handler(ch);
Channel cc = cb.connect(pc.localAddress()).syncUninterruptibly().channel();
for (int i = 0; i < data.length;) {
int length = Math.min(random.nextInt(1024 * 64), data.length - i);
ByteBuf buf = Unpooled.wrappedBuffer(data, i, length);
cc.writeAndFlush(buf);
i += length;
}
while (ch.counter < data.length) {
if (sh.exception.get() != null) {
break;
}
if (ch.exception.get() != null) {
break;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore.
}
}
while (sh.counter < data.length) {
if (sh.exception.get() != null) {
break;
}
if (ch.exception.get() != null) {
break;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore.
}
}
sh.channel.close().sync();
ch.channel.close().sync();
sc.close().sync();
pc.close().sync();
group.shutdownGracefully();
if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
throw sh.exception.get();
}
if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
throw ch.exception.get();
}
if (sh.exception.get() != null) {
throw sh.exception.get();
}
if (ch.exception.get() != null) {
throw ch.exception.get();
}
}
@Test(timeout = 10000)
public void spliceToFile() throws Throwable {
EventLoopGroup group = new EpollEventLoopGroup(1);
File file = File.createTempFile("netty-splice", null);
file.deleteOnExit();
SpliceHandler sh = new SpliceHandler(file);
ServerBootstrap bs = new ServerBootstrap();
bs.channel(EpollServerSocketChannel.class);
bs.group(group).childHandler(sh);
bs.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
Channel sc = bs.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel();
Bootstrap cb = new Bootstrap();
cb.group(group);
cb.channel(EpollSocketChannel.class);
cb.handler(new ChannelInboundHandlerAdapter());
Channel cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
for (int i = 0; i < data.length;) {
int length = Math.min(random.nextInt(1024 * 64), data.length - i);
ByteBuf buf = Unpooled.wrappedBuffer(data, i, length);
cc.writeAndFlush(buf);
i += length;
}
while (sh.future2 == null || !sh.future2.isDone() || !sh.future.isDone()) {
if (sh.exception.get() != null) {
break;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore.
}
}
sc.close().sync();
cc.close().sync();
if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
throw sh.exception.get();
}
byte[] written = new byte[data.length];
FileInputStream in = new FileInputStream(file);
try {
Assert.assertEquals(written.length, in.read(written));
Assert.assertArrayEquals(data, written);
} finally {
in.close();
group.shutdownGracefully();
}
}
private static class EchoHandler extends SimpleChannelInboundHandler<ByteBuf> {
volatile Channel channel;
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
volatile int counter;
@Override
public void channelActive(ChannelHandlerContext ctx)
throws Exception {
channel = ctx.channel();
}
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
byte[] actual = new byte[in.readableBytes()];
in.readBytes(actual);
int lastIdx = counter;
for (int i = 0; i < actual.length; i ++) {
assertEquals(data[i + lastIdx], actual[i]);
}
if (channel.parent() != null) {
channel.write(Unpooled.wrappedBuffer(actual));
}
counter += actual.length;
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) throws Exception {
if (exception.compareAndSet(null, cause)) {
cause.printStackTrace();
ctx.close();
}
}
}
private static class SpliceHandler extends ChannelInboundHandlerAdapter {
private final File file;
volatile ChannelFuture future;
volatile ChannelFuture future2;
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
SpliceHandler(File file) {
this.file = file;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
final EpollSocketChannel ch = (EpollSocketChannel) ctx.channel();
final FileDescriptor fd = FileDescriptor.from(file);
// splice two halves separately to test starting offset
future = ch.spliceTo(fd, 0, data.length / 2);
future2 = ch.spliceTo(fd, data.length / 2, data.length / 2);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) throws Exception {
if (exception.compareAndSet(null, cause)) {
cause.printStackTrace();
ctx.close();
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_13 |
crossvul-java_data_bad_1927_4 | /*
* Copyright 2020 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 io.netty.handler.codec.http.multipart;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.UUID;
import static io.netty.util.CharsetUtil.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
/**
* {@link AbstractDiskHttpData} test cases
*/
public class AbstractDiskHttpDataTest {
@Test
public void testGetChunk() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] bytes = new byte[4096];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
test.setContent(tmpFile);
ByteBuf buf1 = test.getChunk(1024);
assertEquals(buf1.readerIndex(), 0);
assertEquals(buf1.writerIndex(), 1024);
ByteBuf buf2 = test.getChunk(1024);
assertEquals(buf2.readerIndex(), 0);
assertEquals(buf2.writerIndex(), 1024);
assertFalse("Arrays should not be equal",
Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2)));
} finally {
test.delete();
}
}
private static final class TestHttpData extends AbstractDiskHttpData {
private TestHttpData(String name, Charset charset, long size) {
super(name, charset, size);
}
@Override
protected String getDiskFilename() {
return null;
}
@Override
protected String getPrefix() {
return null;
}
@Override
protected String getBaseDirectory() {
return null;
}
@Override
protected String getPostfix() {
return null;
}
@Override
protected boolean deleteOnExit() {
return false;
}
@Override
public HttpData copy() {
return null;
}
@Override
public HttpData duplicate() {
return null;
}
@Override
public HttpData retainedDuplicate() {
return null;
}
@Override
public HttpData replace(ByteBuf content) {
return null;
}
@Override
public HttpDataType getHttpDataType() {
return null;
}
@Override
public int compareTo(InterfaceHttpData o) {
return 0;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_4 |
crossvul-java_data_good_1927_3 | /*
* 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 io.netty.handler.codec.http;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.stream.ChunkedFile;
import io.netty.handler.stream.ChunkedInput;
import io.netty.handler.stream.ChunkedNioFile;
import io.netty.handler.stream.ChunkedNioStream;
import io.netty.handler.stream.ChunkedStream;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import static org.junit.Assert.*;
public class HttpChunkedInputTest {
private static final byte[] BYTES = new byte[1024 * 64];
private static final File TMP;
static {
for (int i = 0; i < BYTES.length; i++) {
BYTES[i] = (byte) i;
}
FileOutputStream out = null;
try {
TMP = PlatformDependent.createTempFile("netty-chunk-", ".tmp", null);
TMP.deleteOnExit();
out = new FileOutputStream(TMP);
out.write(BYTES);
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignore
}
}
}
}
@Test
public void testChunkedStream() {
check(new HttpChunkedInput(new ChunkedStream(new ByteArrayInputStream(BYTES))));
}
@Test
public void testChunkedNioStream() {
check(new HttpChunkedInput(new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES)))));
}
@Test
public void testChunkedFile() throws IOException {
check(new HttpChunkedInput(new ChunkedFile(TMP)));
}
@Test
public void testChunkedNioFile() throws IOException {
check(new HttpChunkedInput(new ChunkedNioFile(TMP)));
}
@Test
public void testWrappedReturnNull() throws Exception {
HttpChunkedInput input = new HttpChunkedInput(new ChunkedInput<ByteBuf>() {
@Override
public boolean isEndOfInput() throws Exception {
return false;
}
@Override
public void close() throws Exception {
// NOOP
}
@Override
public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
return null;
}
@Override
public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {
return null;
}
@Override
public long length() {
return 0;
}
@Override
public long progress() {
return 0;
}
});
assertNull(input.readChunk(ByteBufAllocator.DEFAULT));
}
private static void check(ChunkedInput<?>... inputs) {
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
for (ChunkedInput<?> input : inputs) {
ch.writeOutbound(input);
}
assertTrue(ch.finish());
int i = 0;
int read = 0;
HttpContent lastHttpContent = null;
for (;;) {
HttpContent httpContent = ch.readOutbound();
if (httpContent == null) {
break;
}
if (lastHttpContent != null) {
assertTrue("Chunk must be DefaultHttpContent", lastHttpContent instanceof DefaultHttpContent);
}
ByteBuf buffer = httpContent.content();
while (buffer.isReadable()) {
assertEquals(BYTES[i++], buffer.readByte());
read++;
if (i == BYTES.length) {
i = 0;
}
}
buffer.release();
// Save last chunk
lastHttpContent = httpContent;
}
assertEquals(BYTES.length * inputs.length, read);
assertSame("Last chunk must be LastHttpContent.EMPTY_LAST_CONTENT",
LastHttpContent.EMPTY_LAST_CONTENT, lastHttpContent);
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_3 |
crossvul-java_data_good_1927_0 | /*
* Copyright 2012 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 io.netty.buffer;
import io.netty.util.ByteProcessor;
import io.netty.util.CharsetUtil;
import io.netty.util.IllegalReferenceCountException;
import io.netty.util.internal.PlatformDependent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.ReadOnlyBufferException;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ScatteringByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static io.netty.buffer.Unpooled.LITTLE_ENDIAN;
import static io.netty.buffer.Unpooled.buffer;
import static io.netty.buffer.Unpooled.copiedBuffer;
import static io.netty.buffer.Unpooled.directBuffer;
import static io.netty.buffer.Unpooled.unreleasableBuffer;
import static io.netty.buffer.Unpooled.wrappedBuffer;
import static io.netty.util.internal.EmptyArrays.EMPTY_BYTES;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
/**
* An abstract test class for channel buffers
*/
public abstract class AbstractByteBufTest {
private static final int CAPACITY = 4096; // Must be even
private static final int BLOCK_SIZE = 128;
private static final int JAVA_BYTEBUFFER_CONSISTENCY_ITERATIONS = 100;
private long seed;
private Random random;
private ByteBuf buffer;
protected final ByteBuf newBuffer(int capacity) {
return newBuffer(capacity, Integer.MAX_VALUE);
}
protected abstract ByteBuf newBuffer(int capacity, int maxCapacity);
protected boolean discardReadBytesDoesNotMoveWritableBytes() {
return true;
}
@Before
public void init() {
buffer = newBuffer(CAPACITY);
seed = System.currentTimeMillis();
random = new Random(seed);
}
@After
public void dispose() {
if (buffer != null) {
assertThat(buffer.release(), is(true));
assertThat(buffer.refCnt(), is(0));
try {
buffer.release();
} catch (Exception e) {
// Ignore.
}
buffer = null;
}
}
@Test
public void comparableInterfaceNotViolated() {
assumeFalse(buffer.isReadOnly());
buffer.writerIndex(buffer.readerIndex());
assumeTrue(buffer.writableBytes() >= 4);
buffer.writeLong(0);
ByteBuf buffer2 = newBuffer(CAPACITY);
assumeFalse(buffer2.isReadOnly());
buffer2.writerIndex(buffer2.readerIndex());
// Write an unsigned integer that will cause buffer.getUnsignedInt() - buffer2.getUnsignedInt() to underflow the
// int type and wrap around on the negative side.
buffer2.writeLong(0xF0000000L);
assertTrue(buffer.compareTo(buffer2) < 0);
assertTrue(buffer2.compareTo(buffer) > 0);
buffer2.release();
}
@Test
public void initialState() {
assertEquals(CAPACITY, buffer.capacity());
assertEquals(0, buffer.readerIndex());
}
@Test(expected = IndexOutOfBoundsException.class)
public void readerIndexBoundaryCheck1() {
try {
buffer.writerIndex(0);
} catch (IndexOutOfBoundsException e) {
fail();
}
buffer.readerIndex(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void readerIndexBoundaryCheck2() {
try {
buffer.writerIndex(buffer.capacity());
} catch (IndexOutOfBoundsException e) {
fail();
}
buffer.readerIndex(buffer.capacity() + 1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void readerIndexBoundaryCheck3() {
try {
buffer.writerIndex(CAPACITY / 2);
} catch (IndexOutOfBoundsException e) {
fail();
}
buffer.readerIndex(CAPACITY * 3 / 2);
}
@Test
public void readerIndexBoundaryCheck4() {
buffer.writerIndex(0);
buffer.readerIndex(0);
buffer.writerIndex(buffer.capacity());
buffer.readerIndex(buffer.capacity());
}
@Test(expected = IndexOutOfBoundsException.class)
public void writerIndexBoundaryCheck1() {
buffer.writerIndex(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void writerIndexBoundaryCheck2() {
try {
buffer.writerIndex(CAPACITY);
buffer.readerIndex(CAPACITY);
} catch (IndexOutOfBoundsException e) {
fail();
}
buffer.writerIndex(buffer.capacity() + 1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void writerIndexBoundaryCheck3() {
try {
buffer.writerIndex(CAPACITY);
buffer.readerIndex(CAPACITY / 2);
} catch (IndexOutOfBoundsException e) {
fail();
}
buffer.writerIndex(CAPACITY / 4);
}
@Test
public void writerIndexBoundaryCheck4() {
buffer.writerIndex(0);
buffer.readerIndex(0);
buffer.writerIndex(CAPACITY);
buffer.writeBytes(ByteBuffer.wrap(EMPTY_BYTES));
}
@Test(expected = IndexOutOfBoundsException.class)
public void getBooleanBoundaryCheck1() {
buffer.getBoolean(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getBooleanBoundaryCheck2() {
buffer.getBoolean(buffer.capacity());
}
@Test(expected = IndexOutOfBoundsException.class)
public void getByteBoundaryCheck1() {
buffer.getByte(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getByteBoundaryCheck2() {
buffer.getByte(buffer.capacity());
}
@Test(expected = IndexOutOfBoundsException.class)
public void getShortBoundaryCheck1() {
buffer.getShort(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getShortBoundaryCheck2() {
buffer.getShort(buffer.capacity() - 1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getMediumBoundaryCheck1() {
buffer.getMedium(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getMediumBoundaryCheck2() {
buffer.getMedium(buffer.capacity() - 2);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getIntBoundaryCheck1() {
buffer.getInt(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getIntBoundaryCheck2() {
buffer.getInt(buffer.capacity() - 3);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getLongBoundaryCheck1() {
buffer.getLong(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getLongBoundaryCheck2() {
buffer.getLong(buffer.capacity() - 7);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getByteArrayBoundaryCheck1() {
buffer.getBytes(-1, EMPTY_BYTES);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getByteArrayBoundaryCheck2() {
buffer.getBytes(-1, EMPTY_BYTES, 0, 0);
}
@Test
public void getByteArrayBoundaryCheck3() {
byte[] dst = new byte[4];
buffer.setInt(0, 0x01020304);
try {
buffer.getBytes(0, dst, -1, 4);
fail();
} catch (IndexOutOfBoundsException e) {
// Success
}
// No partial copy is expected.
assertEquals(0, dst[0]);
assertEquals(0, dst[1]);
assertEquals(0, dst[2]);
assertEquals(0, dst[3]);
}
@Test
public void getByteArrayBoundaryCheck4() {
byte[] dst = new byte[4];
buffer.setInt(0, 0x01020304);
try {
buffer.getBytes(0, dst, 1, 4);
fail();
} catch (IndexOutOfBoundsException e) {
// Success
}
// No partial copy is expected.
assertEquals(0, dst[0]);
assertEquals(0, dst[1]);
assertEquals(0, dst[2]);
assertEquals(0, dst[3]);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getByteBufferBoundaryCheck() {
buffer.getBytes(-1, ByteBuffer.allocate(0));
}
@Test(expected = IndexOutOfBoundsException.class)
public void copyBoundaryCheck1() {
buffer.copy(-1, 0);
}
@Test(expected = IndexOutOfBoundsException.class)
public void copyBoundaryCheck2() {
buffer.copy(0, buffer.capacity() + 1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void copyBoundaryCheck3() {
buffer.copy(buffer.capacity() + 1, 0);
}
@Test(expected = IndexOutOfBoundsException.class)
public void copyBoundaryCheck4() {
buffer.copy(buffer.capacity(), 1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void setIndexBoundaryCheck1() {
buffer.setIndex(-1, CAPACITY);
}
@Test(expected = IndexOutOfBoundsException.class)
public void setIndexBoundaryCheck2() {
buffer.setIndex(CAPACITY / 2, CAPACITY / 4);
}
@Test(expected = IndexOutOfBoundsException.class)
public void setIndexBoundaryCheck3() {
buffer.setIndex(0, CAPACITY + 1);
}
@Test
public void getByteBufferState() {
ByteBuffer dst = ByteBuffer.allocate(4);
dst.position(1);
dst.limit(3);
buffer.setByte(0, (byte) 1);
buffer.setByte(1, (byte) 2);
buffer.setByte(2, (byte) 3);
buffer.setByte(3, (byte) 4);
buffer.getBytes(1, dst);
assertEquals(3, dst.position());
assertEquals(3, dst.limit());
dst.clear();
assertEquals(0, dst.get(0));
assertEquals(2, dst.get(1));
assertEquals(3, dst.get(2));
assertEquals(0, dst.get(3));
}
@Test(expected = IndexOutOfBoundsException.class)
public void getDirectByteBufferBoundaryCheck() {
buffer.getBytes(-1, ByteBuffer.allocateDirect(0));
}
@Test
public void getDirectByteBufferState() {
ByteBuffer dst = ByteBuffer.allocateDirect(4);
dst.position(1);
dst.limit(3);
buffer.setByte(0, (byte) 1);
buffer.setByte(1, (byte) 2);
buffer.setByte(2, (byte) 3);
buffer.setByte(3, (byte) 4);
buffer.getBytes(1, dst);
assertEquals(3, dst.position());
assertEquals(3, dst.limit());
dst.clear();
assertEquals(0, dst.get(0));
assertEquals(2, dst.get(1));
assertEquals(3, dst.get(2));
assertEquals(0, dst.get(3));
}
@Test
public void testRandomByteAccess() {
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
buffer.setByte(i, value);
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
assertEquals(value, buffer.getByte(i));
}
}
@Test
public void testRandomUnsignedByteAccess() {
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
buffer.setByte(i, value);
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i ++) {
int value = random.nextInt() & 0xFF;
assertEquals(value, buffer.getUnsignedByte(i));
}
}
@Test
public void testRandomShortAccess() {
testRandomShortAccess(true);
}
@Test
public void testRandomShortLEAccess() {
testRandomShortAccess(false);
}
private void testRandomShortAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 1; i += 2) {
short value = (short) random.nextInt();
if (testBigEndian) {
buffer.setShort(i, value);
} else {
buffer.setShortLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 1; i += 2) {
short value = (short) random.nextInt();
if (testBigEndian) {
assertEquals(value, buffer.getShort(i));
} else {
assertEquals(value, buffer.getShortLE(i));
}
}
}
@Test
public void testShortConsistentWithByteBuffer() {
testShortConsistentWithByteBuffer(true, true);
testShortConsistentWithByteBuffer(true, false);
testShortConsistentWithByteBuffer(false, true);
testShortConsistentWithByteBuffer(false, false);
}
private void testShortConsistentWithByteBuffer(boolean direct, boolean testBigEndian) {
for (int i = 0; i < JAVA_BYTEBUFFER_CONSISTENCY_ITERATIONS; ++i) {
ByteBuffer javaBuffer = direct ? ByteBuffer.allocateDirect(buffer.capacity())
: ByteBuffer.allocate(buffer.capacity());
if (!testBigEndian) {
javaBuffer = javaBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
short expected = (short) (random.nextInt() & 0xFFFF);
javaBuffer.putShort(expected);
final int bufferIndex = buffer.capacity() - 2;
if (testBigEndian) {
buffer.setShort(bufferIndex, expected);
} else {
buffer.setShortLE(bufferIndex, expected);
}
javaBuffer.flip();
short javaActual = javaBuffer.getShort();
assertEquals(expected, javaActual);
assertEquals(javaActual, testBigEndian ? buffer.getShort(bufferIndex)
: buffer.getShortLE(bufferIndex));
}
}
@Test
public void testRandomUnsignedShortAccess() {
testRandomUnsignedShortAccess(true);
}
@Test
public void testRandomUnsignedShortLEAccess() {
testRandomUnsignedShortAccess(false);
}
private void testRandomUnsignedShortAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 1; i += 2) {
short value = (short) random.nextInt();
if (testBigEndian) {
buffer.setShort(i, value);
} else {
buffer.setShortLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 1; i += 2) {
int value = random.nextInt() & 0xFFFF;
if (testBigEndian) {
assertEquals(value, buffer.getUnsignedShort(i));
} else {
assertEquals(value, buffer.getUnsignedShortLE(i));
}
}
}
@Test
public void testRandomMediumAccess() {
testRandomMediumAccess(true);
}
@Test
public void testRandomMediumLEAccess() {
testRandomMediumAccess(false);
}
private void testRandomMediumAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 2; i += 3) {
int value = random.nextInt();
if (testBigEndian) {
buffer.setMedium(i, value);
} else {
buffer.setMediumLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 2; i += 3) {
int value = random.nextInt() << 8 >> 8;
if (testBigEndian) {
assertEquals(value, buffer.getMedium(i));
} else {
assertEquals(value, buffer.getMediumLE(i));
}
}
}
@Test
public void testRandomUnsignedMediumAccess() {
testRandomUnsignedMediumAccess(true);
}
@Test
public void testRandomUnsignedMediumLEAccess() {
testRandomUnsignedMediumAccess(false);
}
private void testRandomUnsignedMediumAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 2; i += 3) {
int value = random.nextInt();
if (testBigEndian) {
buffer.setMedium(i, value);
} else {
buffer.setMediumLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 2; i += 3) {
int value = random.nextInt() & 0x00FFFFFF;
if (testBigEndian) {
assertEquals(value, buffer.getUnsignedMedium(i));
} else {
assertEquals(value, buffer.getUnsignedMediumLE(i));
}
}
}
@Test
public void testMediumConsistentWithByteBuffer() {
testMediumConsistentWithByteBuffer(true, true);
testMediumConsistentWithByteBuffer(true, false);
testMediumConsistentWithByteBuffer(false, true);
testMediumConsistentWithByteBuffer(false, false);
}
private void testMediumConsistentWithByteBuffer(boolean direct, boolean testBigEndian) {
for (int i = 0; i < JAVA_BYTEBUFFER_CONSISTENCY_ITERATIONS; ++i) {
ByteBuffer javaBuffer = direct ? ByteBuffer.allocateDirect(buffer.capacity())
: ByteBuffer.allocate(buffer.capacity());
if (!testBigEndian) {
javaBuffer = javaBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
int expected = random.nextInt() & 0x00FFFFFF;
javaBuffer.putInt(expected);
final int bufferIndex = buffer.capacity() - 3;
if (testBigEndian) {
buffer.setMedium(bufferIndex, expected);
} else {
buffer.setMediumLE(bufferIndex, expected);
}
javaBuffer.flip();
int javaActual = javaBuffer.getInt();
assertEquals(expected, javaActual);
assertEquals(javaActual, testBigEndian ? buffer.getUnsignedMedium(bufferIndex)
: buffer.getUnsignedMediumLE(bufferIndex));
}
}
@Test
public void testRandomIntAccess() {
testRandomIntAccess(true);
}
@Test
public void testRandomIntLEAccess() {
testRandomIntAccess(false);
}
private void testRandomIntAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 3; i += 4) {
int value = random.nextInt();
if (testBigEndian) {
buffer.setInt(i, value);
} else {
buffer.setIntLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 3; i += 4) {
int value = random.nextInt();
if (testBigEndian) {
assertEquals(value, buffer.getInt(i));
} else {
assertEquals(value, buffer.getIntLE(i));
}
}
}
@Test
public void testIntConsistentWithByteBuffer() {
testIntConsistentWithByteBuffer(true, true);
testIntConsistentWithByteBuffer(true, false);
testIntConsistentWithByteBuffer(false, true);
testIntConsistentWithByteBuffer(false, false);
}
private void testIntConsistentWithByteBuffer(boolean direct, boolean testBigEndian) {
for (int i = 0; i < JAVA_BYTEBUFFER_CONSISTENCY_ITERATIONS; ++i) {
ByteBuffer javaBuffer = direct ? ByteBuffer.allocateDirect(buffer.capacity())
: ByteBuffer.allocate(buffer.capacity());
if (!testBigEndian) {
javaBuffer = javaBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
int expected = random.nextInt();
javaBuffer.putInt(expected);
final int bufferIndex = buffer.capacity() - 4;
if (testBigEndian) {
buffer.setInt(bufferIndex, expected);
} else {
buffer.setIntLE(bufferIndex, expected);
}
javaBuffer.flip();
int javaActual = javaBuffer.getInt();
assertEquals(expected, javaActual);
assertEquals(javaActual, testBigEndian ? buffer.getInt(bufferIndex)
: buffer.getIntLE(bufferIndex));
}
}
@Test
public void testRandomUnsignedIntAccess() {
testRandomUnsignedIntAccess(true);
}
@Test
public void testRandomUnsignedIntLEAccess() {
testRandomUnsignedIntAccess(false);
}
private void testRandomUnsignedIntAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 3; i += 4) {
int value = random.nextInt();
if (testBigEndian) {
buffer.setInt(i, value);
} else {
buffer.setIntLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 3; i += 4) {
long value = random.nextInt() & 0xFFFFFFFFL;
if (testBigEndian) {
assertEquals(value, buffer.getUnsignedInt(i));
} else {
assertEquals(value, buffer.getUnsignedIntLE(i));
}
}
}
@Test
public void testRandomLongAccess() {
testRandomLongAccess(true);
}
@Test
public void testRandomLongLEAccess() {
testRandomLongAccess(false);
}
private void testRandomLongAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 7; i += 8) {
long value = random.nextLong();
if (testBigEndian) {
buffer.setLong(i, value);
} else {
buffer.setLongLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 7; i += 8) {
long value = random.nextLong();
if (testBigEndian) {
assertEquals(value, buffer.getLong(i));
} else {
assertEquals(value, buffer.getLongLE(i));
}
}
}
@Test
public void testLongConsistentWithByteBuffer() {
testLongConsistentWithByteBuffer(true, true);
testLongConsistentWithByteBuffer(true, false);
testLongConsistentWithByteBuffer(false, true);
testLongConsistentWithByteBuffer(false, false);
}
private void testLongConsistentWithByteBuffer(boolean direct, boolean testBigEndian) {
for (int i = 0; i < JAVA_BYTEBUFFER_CONSISTENCY_ITERATIONS; ++i) {
ByteBuffer javaBuffer = direct ? ByteBuffer.allocateDirect(buffer.capacity())
: ByteBuffer.allocate(buffer.capacity());
if (!testBigEndian) {
javaBuffer = javaBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
long expected = random.nextLong();
javaBuffer.putLong(expected);
final int bufferIndex = buffer.capacity() - 8;
if (testBigEndian) {
buffer.setLong(bufferIndex, expected);
} else {
buffer.setLongLE(bufferIndex, expected);
}
javaBuffer.flip();
long javaActual = javaBuffer.getLong();
assertEquals(expected, javaActual);
assertEquals(javaActual, testBigEndian ? buffer.getLong(bufferIndex)
: buffer.getLongLE(bufferIndex));
}
}
@Test
public void testRandomFloatAccess() {
testRandomFloatAccess(true);
}
@Test
public void testRandomFloatLEAccess() {
testRandomFloatAccess(false);
}
private void testRandomFloatAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 7; i += 8) {
float value = random.nextFloat();
if (testBigEndian) {
buffer.setFloat(i, value);
} else {
buffer.setFloatLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 7; i += 8) {
float expected = random.nextFloat();
float actual = testBigEndian? buffer.getFloat(i) : buffer.getFloatLE(i);
assertEquals(expected, actual, 0.01);
}
}
@Test
public void testRandomDoubleAccess() {
testRandomDoubleAccess(true);
}
@Test
public void testRandomDoubleLEAccess() {
testRandomDoubleAccess(false);
}
private void testRandomDoubleAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 7; i += 8) {
double value = random.nextDouble();
if (testBigEndian) {
buffer.setDouble(i, value);
} else {
buffer.setDoubleLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 7; i += 8) {
double expected = random.nextDouble();
double actual = testBigEndian? buffer.getDouble(i) : buffer.getDoubleLE(i);
assertEquals(expected, actual, 0.01);
}
}
@Test
public void testSetZero() {
buffer.clear();
while (buffer.isWritable()) {
buffer.writeByte((byte) 0xFF);
}
for (int i = 0; i < buffer.capacity();) {
int length = Math.min(buffer.capacity() - i, random.nextInt(32));
buffer.setZero(i, length);
i += length;
}
for (int i = 0; i < buffer.capacity(); i ++) {
assertEquals(0, buffer.getByte(i));
}
}
@Test
public void testSequentialByteAccess() {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
buffer.writeByte(value);
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isWritable());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
assertEquals(value, buffer.readByte());
}
assertEquals(buffer.capacity(), buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isReadable());
assertFalse(buffer.isWritable());
}
@Test
public void testSequentialUnsignedByteAccess() {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
buffer.writeByte(value);
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isWritable());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i ++) {
int value = random.nextInt() & 0xFF;
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
assertEquals(value, buffer.readUnsignedByte());
}
assertEquals(buffer.capacity(), buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isReadable());
assertFalse(buffer.isWritable());
}
@Test
public void testSequentialShortAccess() {
testSequentialShortAccess(true);
}
@Test
public void testSequentialShortLEAccess() {
testSequentialShortAccess(false);
}
private void testSequentialShortAccess(boolean testBigEndian) {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i += 2) {
short value = (short) random.nextInt();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
if (testBigEndian) {
buffer.writeShort(value);
} else {
buffer.writeShortLE(value);
}
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isWritable());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i += 2) {
short value = (short) random.nextInt();
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
if (testBigEndian) {
assertEquals(value, buffer.readShort());
} else {
assertEquals(value, buffer.readShortLE());
}
}
assertEquals(buffer.capacity(), buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isReadable());
assertFalse(buffer.isWritable());
}
@Test
public void testSequentialUnsignedShortAccess() {
testSequentialUnsignedShortAccess(true);
}
@Test
public void testSequentialUnsignedShortLEAccess() {
testSequentialUnsignedShortAccess(true);
}
private void testSequentialUnsignedShortAccess(boolean testBigEndian) {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i += 2) {
short value = (short) random.nextInt();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
if (testBigEndian) {
buffer.writeShort(value);
} else {
buffer.writeShortLE(value);
}
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isWritable());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i += 2) {
int value = random.nextInt() & 0xFFFF;
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
if (testBigEndian) {
assertEquals(value, buffer.readUnsignedShort());
} else {
assertEquals(value, buffer.readUnsignedShortLE());
}
}
assertEquals(buffer.capacity(), buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isReadable());
assertFalse(buffer.isWritable());
}
@Test
public void testSequentialMediumAccess() {
testSequentialMediumAccess(true);
}
@Test
public void testSequentialMediumLEAccess() {
testSequentialMediumAccess(false);
}
private void testSequentialMediumAccess(boolean testBigEndian) {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() / 3 * 3; i += 3) {
int value = random.nextInt();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
if (testBigEndian) {
buffer.writeMedium(value);
} else {
buffer.writeMediumLE(value);
}
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity() / 3 * 3, buffer.writerIndex());
assertEquals(buffer.capacity() % 3, buffer.writableBytes());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() / 3 * 3; i += 3) {
int value = random.nextInt() << 8 >> 8;
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
if (testBigEndian) {
assertEquals(value, buffer.readMedium());
} else {
assertEquals(value, buffer.readMediumLE());
}
}
assertEquals(buffer.capacity() / 3 * 3, buffer.readerIndex());
assertEquals(buffer.capacity() / 3 * 3, buffer.writerIndex());
assertEquals(0, buffer.readableBytes());
assertEquals(buffer.capacity() % 3, buffer.writableBytes());
}
@Test
public void testSequentialUnsignedMediumAccess() {
testSequentialUnsignedMediumAccess(true);
}
@Test
public void testSequentialUnsignedMediumLEAccess() {
testSequentialUnsignedMediumAccess(false);
}
private void testSequentialUnsignedMediumAccess(boolean testBigEndian) {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() / 3 * 3; i += 3) {
int value = random.nextInt() & 0x00FFFFFF;
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
if (testBigEndian) {
buffer.writeMedium(value);
} else {
buffer.writeMediumLE(value);
}
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity() / 3 * 3, buffer.writerIndex());
assertEquals(buffer.capacity() % 3, buffer.writableBytes());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() / 3 * 3; i += 3) {
int value = random.nextInt() & 0x00FFFFFF;
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
if (testBigEndian) {
assertEquals(value, buffer.readUnsignedMedium());
} else {
assertEquals(value, buffer.readUnsignedMediumLE());
}
}
assertEquals(buffer.capacity() / 3 * 3, buffer.readerIndex());
assertEquals(buffer.capacity() / 3 * 3, buffer.writerIndex());
assertEquals(0, buffer.readableBytes());
assertEquals(buffer.capacity() % 3, buffer.writableBytes());
}
@Test
public void testSequentialIntAccess() {
testSequentialIntAccess(true);
}
@Test
public void testSequentialIntLEAccess() {
testSequentialIntAccess(false);
}
private void testSequentialIntAccess(boolean testBigEndian) {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i += 4) {
int value = random.nextInt();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
if (testBigEndian) {
buffer.writeInt(value);
} else {
buffer.writeIntLE(value);
}
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isWritable());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i += 4) {
int value = random.nextInt();
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
if (testBigEndian) {
assertEquals(value, buffer.readInt());
} else {
assertEquals(value, buffer.readIntLE());
}
}
assertEquals(buffer.capacity(), buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isReadable());
assertFalse(buffer.isWritable());
}
@Test
public void testSequentialUnsignedIntAccess() {
testSequentialUnsignedIntAccess(true);
}
@Test
public void testSequentialUnsignedIntLEAccess() {
testSequentialUnsignedIntAccess(false);
}
private void testSequentialUnsignedIntAccess(boolean testBigEndian) {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i += 4) {
int value = random.nextInt();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
if (testBigEndian) {
buffer.writeInt(value);
} else {
buffer.writeIntLE(value);
}
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isWritable());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i += 4) {
long value = random.nextInt() & 0xFFFFFFFFL;
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
if (testBigEndian) {
assertEquals(value, buffer.readUnsignedInt());
} else {
assertEquals(value, buffer.readUnsignedIntLE());
}
}
assertEquals(buffer.capacity(), buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isReadable());
assertFalse(buffer.isWritable());
}
@Test
public void testSequentialLongAccess() {
testSequentialLongAccess(true);
}
@Test
public void testSequentialLongLEAccess() {
testSequentialLongAccess(false);
}
private void testSequentialLongAccess(boolean testBigEndian) {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i += 8) {
long value = random.nextLong();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
if (testBigEndian) {
buffer.writeLong(value);
} else {
buffer.writeLongLE(value);
}
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isWritable());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i += 8) {
long value = random.nextLong();
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
if (testBigEndian) {
assertEquals(value, buffer.readLong());
} else {
assertEquals(value, buffer.readLongLE());
}
}
assertEquals(buffer.capacity(), buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isReadable());
assertFalse(buffer.isWritable());
}
@Test
public void testByteArrayTransfer() {
byte[] value = new byte[BLOCK_SIZE * 2];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(value);
buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE);
}
random.setSeed(seed);
byte[] expectedValue = new byte[BLOCK_SIZE * 2];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValue);
int valueOffset = random.nextInt(BLOCK_SIZE);
buffer.getBytes(i, value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue[j], value[j]);
}
}
}
@Test
public void testRandomByteArrayTransfer1() {
byte[] value = new byte[BLOCK_SIZE];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(value);
buffer.setBytes(i, value);
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
buffer.getBytes(i, value);
for (int j = 0; j < BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value[j]);
}
}
}
@Test
public void testRandomByteArrayTransfer2() {
byte[] value = new byte[BLOCK_SIZE * 2];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(value);
buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE);
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
buffer.getBytes(i, value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value[j]);
}
}
}
@Test
public void testRandomHeapBufferTransfer1() {
byte[] valueContent = new byte[BLOCK_SIZE];
ByteBuf value = wrappedBuffer(valueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
value.setIndex(0, BLOCK_SIZE);
buffer.setBytes(i, value);
assertEquals(BLOCK_SIZE, value.readerIndex());
assertEquals(BLOCK_SIZE, value.writerIndex());
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
value.clear();
buffer.getBytes(i, value);
assertEquals(0, value.readerIndex());
assertEquals(BLOCK_SIZE, value.writerIndex());
for (int j = 0; j < BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
}
}
@Test
public void testRandomHeapBufferTransfer2() {
byte[] valueContent = new byte[BLOCK_SIZE * 2];
ByteBuf value = wrappedBuffer(valueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE);
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
buffer.getBytes(i, value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
}
}
@Test
public void testRandomDirectBufferTransfer() {
byte[] tmp = new byte[BLOCK_SIZE * 2];
ByteBuf value = directBuffer(BLOCK_SIZE * 2);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(tmp);
value.setBytes(0, tmp, 0, value.capacity());
buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE);
}
random.setSeed(seed);
ByteBuf expectedValue = directBuffer(BLOCK_SIZE * 2);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(tmp);
expectedValue.setBytes(0, tmp, 0, expectedValue.capacity());
int valueOffset = random.nextInt(BLOCK_SIZE);
buffer.getBytes(i, value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
}
value.release();
expectedValue.release();
}
@Test
public void testRandomByteBufferTransfer() {
ByteBuffer value = ByteBuffer.allocate(BLOCK_SIZE * 2);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(value.array());
value.clear().position(random.nextInt(BLOCK_SIZE));
value.limit(value.position() + BLOCK_SIZE);
buffer.setBytes(i, value);
}
random.setSeed(seed);
ByteBuffer expectedValue = ByteBuffer.allocate(BLOCK_SIZE * 2);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValue.array());
int valueOffset = random.nextInt(BLOCK_SIZE);
value.clear().position(valueOffset).limit(valueOffset + BLOCK_SIZE);
buffer.getBytes(i, value);
assertEquals(valueOffset + BLOCK_SIZE, value.position());
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.get(j), value.get(j));
}
}
}
@Test
public void testSequentialByteArrayTransfer1() {
byte[] value = new byte[BLOCK_SIZE];
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(value);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
buffer.writeBytes(value);
}
random.setSeed(seed);
byte[] expectedValue = new byte[BLOCK_SIZE];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValue);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
buffer.readBytes(value);
for (int j = 0; j < BLOCK_SIZE; j ++) {
assertEquals(expectedValue[j], value[j]);
}
}
}
@Test
public void testSequentialByteArrayTransfer2() {
byte[] value = new byte[BLOCK_SIZE * 2];
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(value);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
int readerIndex = random.nextInt(BLOCK_SIZE);
buffer.writeBytes(value, readerIndex, BLOCK_SIZE);
}
random.setSeed(seed);
byte[] expectedValue = new byte[BLOCK_SIZE * 2];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValue);
int valueOffset = random.nextInt(BLOCK_SIZE);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
buffer.readBytes(value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue[j], value[j]);
}
}
}
@Test
public void testSequentialHeapBufferTransfer1() {
byte[] valueContent = new byte[BLOCK_SIZE * 2];
ByteBuf value = wrappedBuffer(valueContent);
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
buffer.writeBytes(value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE);
assertEquals(0, value.readerIndex());
assertEquals(valueContent.length, value.writerIndex());
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
buffer.readBytes(value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
assertEquals(0, value.readerIndex());
assertEquals(valueContent.length, value.writerIndex());
}
}
@Test
public void testSequentialHeapBufferTransfer2() {
byte[] valueContent = new byte[BLOCK_SIZE * 2];
ByteBuf value = wrappedBuffer(valueContent);
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
int readerIndex = random.nextInt(BLOCK_SIZE);
value.readerIndex(readerIndex);
value.writerIndex(readerIndex + BLOCK_SIZE);
buffer.writeBytes(value);
assertEquals(readerIndex + BLOCK_SIZE, value.writerIndex());
assertEquals(value.writerIndex(), value.readerIndex());
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
value.readerIndex(valueOffset);
value.writerIndex(valueOffset);
buffer.readBytes(value, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
assertEquals(valueOffset, value.readerIndex());
assertEquals(valueOffset + BLOCK_SIZE, value.writerIndex());
}
}
@Test
public void testSequentialDirectBufferTransfer1() {
byte[] valueContent = new byte[BLOCK_SIZE * 2];
ByteBuf value = directBuffer(BLOCK_SIZE * 2);
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
value.setBytes(0, valueContent);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
buffer.writeBytes(value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE);
assertEquals(0, value.readerIndex());
assertEquals(0, value.writerIndex());
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
value.setBytes(0, valueContent);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
buffer.readBytes(value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
assertEquals(0, value.readerIndex());
assertEquals(0, value.writerIndex());
}
value.release();
expectedValue.release();
}
@Test
public void testSequentialDirectBufferTransfer2() {
byte[] valueContent = new byte[BLOCK_SIZE * 2];
ByteBuf value = directBuffer(BLOCK_SIZE * 2);
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
value.setBytes(0, valueContent);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
int readerIndex = random.nextInt(BLOCK_SIZE);
value.readerIndex(0);
value.writerIndex(readerIndex + BLOCK_SIZE);
value.readerIndex(readerIndex);
buffer.writeBytes(value);
assertEquals(readerIndex + BLOCK_SIZE, value.writerIndex());
assertEquals(value.writerIndex(), value.readerIndex());
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
value.setBytes(0, valueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
value.readerIndex(valueOffset);
value.writerIndex(valueOffset);
buffer.readBytes(value, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
assertEquals(valueOffset, value.readerIndex());
assertEquals(valueOffset + BLOCK_SIZE, value.writerIndex());
}
value.release();
expectedValue.release();
}
@Test
public void testSequentialByteBufferBackedHeapBufferTransfer1() {
byte[] valueContent = new byte[BLOCK_SIZE * 2];
ByteBuf value = wrappedBuffer(ByteBuffer.allocate(BLOCK_SIZE * 2));
value.writerIndex(0);
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
value.setBytes(0, valueContent);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
buffer.writeBytes(value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE);
assertEquals(0, value.readerIndex());
assertEquals(0, value.writerIndex());
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
value.setBytes(0, valueContent);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
buffer.readBytes(value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
assertEquals(0, value.readerIndex());
assertEquals(0, value.writerIndex());
}
}
@Test
public void testSequentialByteBufferBackedHeapBufferTransfer2() {
byte[] valueContent = new byte[BLOCK_SIZE * 2];
ByteBuf value = wrappedBuffer(ByteBuffer.allocate(BLOCK_SIZE * 2));
value.writerIndex(0);
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
value.setBytes(0, valueContent);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
int readerIndex = random.nextInt(BLOCK_SIZE);
value.readerIndex(0);
value.writerIndex(readerIndex + BLOCK_SIZE);
value.readerIndex(readerIndex);
buffer.writeBytes(value);
assertEquals(readerIndex + BLOCK_SIZE, value.writerIndex());
assertEquals(value.writerIndex(), value.readerIndex());
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
value.setBytes(0, valueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
value.readerIndex(valueOffset);
value.writerIndex(valueOffset);
buffer.readBytes(value, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
assertEquals(valueOffset, value.readerIndex());
assertEquals(valueOffset + BLOCK_SIZE, value.writerIndex());
}
}
@Test
public void testSequentialByteBufferTransfer() {
buffer.writerIndex(0);
ByteBuffer value = ByteBuffer.allocate(BLOCK_SIZE * 2);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(value.array());
value.clear().position(random.nextInt(BLOCK_SIZE));
value.limit(value.position() + BLOCK_SIZE);
buffer.writeBytes(value);
}
random.setSeed(seed);
ByteBuffer expectedValue = ByteBuffer.allocate(BLOCK_SIZE * 2);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValue.array());
int valueOffset = random.nextInt(BLOCK_SIZE);
value.clear().position(valueOffset).limit(valueOffset + BLOCK_SIZE);
buffer.readBytes(value);
assertEquals(valueOffset + BLOCK_SIZE, value.position());
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.get(j), value.get(j));
}
}
}
@Test
public void testSequentialCopiedBufferTransfer1() {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
byte[] value = new byte[BLOCK_SIZE];
random.nextBytes(value);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
buffer.writeBytes(value);
}
random.setSeed(seed);
byte[] expectedValue = new byte[BLOCK_SIZE];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValue);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
ByteBuf actualValue = buffer.readBytes(BLOCK_SIZE);
assertEquals(wrappedBuffer(expectedValue), actualValue);
// Make sure if it is a copied buffer.
actualValue.setByte(0, (byte) (actualValue.getByte(0) + 1));
assertFalse(buffer.getByte(i) == actualValue.getByte(0));
actualValue.release();
}
}
@Test
public void testSequentialSlice1() {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
byte[] value = new byte[BLOCK_SIZE];
random.nextBytes(value);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
buffer.writeBytes(value);
}
random.setSeed(seed);
byte[] expectedValue = new byte[BLOCK_SIZE];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValue);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
ByteBuf actualValue = buffer.readSlice(BLOCK_SIZE);
assertEquals(buffer.order(), actualValue.order());
assertEquals(wrappedBuffer(expectedValue), actualValue);
// Make sure if it is a sliced buffer.
actualValue.setByte(0, (byte) (actualValue.getByte(0) + 1));
assertEquals(buffer.getByte(i), actualValue.getByte(0));
}
}
@Test
public void testWriteZero() {
try {
buffer.writeZero(-1);
fail();
} catch (IllegalArgumentException e) {
// Expected
}
buffer.clear();
while (buffer.isWritable()) {
buffer.writeByte((byte) 0xFF);
}
buffer.clear();
for (int i = 0; i < buffer.capacity();) {
int length = Math.min(buffer.capacity() - i, random.nextInt(32));
buffer.writeZero(length);
i += length;
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
for (int i = 0; i < buffer.capacity(); i ++) {
assertEquals(0, buffer.getByte(i));
}
}
@Test
public void testDiscardReadBytes() {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i += 4) {
buffer.writeInt(i);
}
ByteBuf copy = copiedBuffer(buffer);
// Make sure there's no effect if called when readerIndex is 0.
buffer.readerIndex(CAPACITY / 4);
buffer.markReaderIndex();
buffer.writerIndex(CAPACITY / 3);
buffer.markWriterIndex();
buffer.readerIndex(0);
buffer.writerIndex(CAPACITY / 2);
buffer.discardReadBytes();
assertEquals(0, buffer.readerIndex());
assertEquals(CAPACITY / 2, buffer.writerIndex());
assertEquals(copy.slice(0, CAPACITY / 2), buffer.slice(0, CAPACITY / 2));
buffer.resetReaderIndex();
assertEquals(CAPACITY / 4, buffer.readerIndex());
buffer.resetWriterIndex();
assertEquals(CAPACITY / 3, buffer.writerIndex());
// Make sure bytes after writerIndex is not copied.
buffer.readerIndex(1);
buffer.writerIndex(CAPACITY / 2);
buffer.discardReadBytes();
assertEquals(0, buffer.readerIndex());
assertEquals(CAPACITY / 2 - 1, buffer.writerIndex());
assertEquals(copy.slice(1, CAPACITY / 2 - 1), buffer.slice(0, CAPACITY / 2 - 1));
if (discardReadBytesDoesNotMoveWritableBytes()) {
// If writable bytes were copied, the test should fail to avoid unnecessary memory bandwidth consumption.
assertFalse(copy.slice(CAPACITY / 2, CAPACITY / 2).equals(buffer.slice(CAPACITY / 2 - 1, CAPACITY / 2)));
} else {
assertEquals(copy.slice(CAPACITY / 2, CAPACITY / 2), buffer.slice(CAPACITY / 2 - 1, CAPACITY / 2));
}
// Marks also should be relocated.
buffer.resetReaderIndex();
assertEquals(CAPACITY / 4 - 1, buffer.readerIndex());
buffer.resetWriterIndex();
assertEquals(CAPACITY / 3 - 1, buffer.writerIndex());
copy.release();
}
/**
* The similar test case with {@link #testDiscardReadBytes()} but this one
* discards a large chunk at once.
*/
@Test
public void testDiscardReadBytes2() {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i ++) {
buffer.writeByte((byte) i);
}
ByteBuf copy = copiedBuffer(buffer);
// Discard the first (CAPACITY / 2 - 1) bytes.
buffer.setIndex(CAPACITY / 2 - 1, CAPACITY - 1);
buffer.discardReadBytes();
assertEquals(0, buffer.readerIndex());
assertEquals(CAPACITY / 2, buffer.writerIndex());
for (int i = 0; i < CAPACITY / 2; i ++) {
assertEquals(copy.slice(CAPACITY / 2 - 1 + i, CAPACITY / 2 - i), buffer.slice(i, CAPACITY / 2 - i));
}
copy.release();
}
@Test
public void testStreamTransfer1() throws Exception {
byte[] expected = new byte[buffer.capacity()];
random.nextBytes(expected);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
ByteArrayInputStream in = new ByteArrayInputStream(expected, i, BLOCK_SIZE);
assertEquals(BLOCK_SIZE, buffer.setBytes(i, in, BLOCK_SIZE));
assertEquals(-1, buffer.setBytes(i, in, 0));
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
buffer.getBytes(i, out, BLOCK_SIZE);
}
assertTrue(Arrays.equals(expected, out.toByteArray()));
}
@Test
public void testStreamTransfer2() throws Exception {
byte[] expected = new byte[buffer.capacity()];
random.nextBytes(expected);
buffer.clear();
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
ByteArrayInputStream in = new ByteArrayInputStream(expected, i, BLOCK_SIZE);
assertEquals(i, buffer.writerIndex());
buffer.writeBytes(in, BLOCK_SIZE);
assertEquals(i + BLOCK_SIZE, buffer.writerIndex());
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
assertEquals(i, buffer.readerIndex());
buffer.readBytes(out, BLOCK_SIZE);
assertEquals(i + BLOCK_SIZE, buffer.readerIndex());
}
assertTrue(Arrays.equals(expected, out.toByteArray()));
}
@Test
public void testCopy() {
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
buffer.setByte(i, value);
}
final int readerIndex = CAPACITY / 3;
final int writerIndex = CAPACITY * 2 / 3;
buffer.setIndex(readerIndex, writerIndex);
// Make sure all properties are copied.
ByteBuf copy = buffer.copy();
assertEquals(0, copy.readerIndex());
assertEquals(buffer.readableBytes(), copy.writerIndex());
assertEquals(buffer.readableBytes(), copy.capacity());
assertSame(buffer.order(), copy.order());
for (int i = 0; i < copy.capacity(); i ++) {
assertEquals(buffer.getByte(i + readerIndex), copy.getByte(i));
}
// Make sure the buffer content is independent from each other.
buffer.setByte(readerIndex, (byte) (buffer.getByte(readerIndex) + 1));
assertTrue(buffer.getByte(readerIndex) != copy.getByte(0));
copy.setByte(1, (byte) (copy.getByte(1) + 1));
assertTrue(buffer.getByte(readerIndex + 1) != copy.getByte(1));
copy.release();
}
@Test
public void testDuplicate() {
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
buffer.setByte(i, value);
}
final int readerIndex = CAPACITY / 3;
final int writerIndex = CAPACITY * 2 / 3;
buffer.setIndex(readerIndex, writerIndex);
// Make sure all properties are copied.
ByteBuf duplicate = buffer.duplicate();
assertSame(buffer.order(), duplicate.order());
assertEquals(buffer.readableBytes(), duplicate.readableBytes());
assertEquals(0, buffer.compareTo(duplicate));
// Make sure the buffer content is shared.
buffer.setByte(readerIndex, (byte) (buffer.getByte(readerIndex) + 1));
assertEquals(buffer.getByte(readerIndex), duplicate.getByte(duplicate.readerIndex()));
duplicate.setByte(duplicate.readerIndex(), (byte) (duplicate.getByte(duplicate.readerIndex()) + 1));
assertEquals(buffer.getByte(readerIndex), duplicate.getByte(duplicate.readerIndex()));
}
@Test
public void testSliceEndianness() throws Exception {
assertEquals(buffer.order(), buffer.slice(0, buffer.capacity()).order());
assertEquals(buffer.order(), buffer.slice(0, buffer.capacity() - 1).order());
assertEquals(buffer.order(), buffer.slice(1, buffer.capacity() - 1).order());
assertEquals(buffer.order(), buffer.slice(1, buffer.capacity() - 2).order());
}
@Test
public void testSliceIndex() throws Exception {
assertEquals(0, buffer.slice(0, buffer.capacity()).readerIndex());
assertEquals(0, buffer.slice(0, buffer.capacity() - 1).readerIndex());
assertEquals(0, buffer.slice(1, buffer.capacity() - 1).readerIndex());
assertEquals(0, buffer.slice(1, buffer.capacity() - 2).readerIndex());
assertEquals(buffer.capacity(), buffer.slice(0, buffer.capacity()).writerIndex());
assertEquals(buffer.capacity() - 1, buffer.slice(0, buffer.capacity() - 1).writerIndex());
assertEquals(buffer.capacity() - 1, buffer.slice(1, buffer.capacity() - 1).writerIndex());
assertEquals(buffer.capacity() - 2, buffer.slice(1, buffer.capacity() - 2).writerIndex());
}
@Test
public void testRetainedSliceIndex() throws Exception {
ByteBuf retainedSlice = buffer.retainedSlice(0, buffer.capacity());
assertEquals(0, retainedSlice.readerIndex());
retainedSlice.release();
retainedSlice = buffer.retainedSlice(0, buffer.capacity() - 1);
assertEquals(0, retainedSlice.readerIndex());
retainedSlice.release();
retainedSlice = buffer.retainedSlice(1, buffer.capacity() - 1);
assertEquals(0, retainedSlice.readerIndex());
retainedSlice.release();
retainedSlice = buffer.retainedSlice(1, buffer.capacity() - 2);
assertEquals(0, retainedSlice.readerIndex());
retainedSlice.release();
retainedSlice = buffer.retainedSlice(0, buffer.capacity());
assertEquals(buffer.capacity(), retainedSlice.writerIndex());
retainedSlice.release();
retainedSlice = buffer.retainedSlice(0, buffer.capacity() - 1);
assertEquals(buffer.capacity() - 1, retainedSlice.writerIndex());
retainedSlice.release();
retainedSlice = buffer.retainedSlice(1, buffer.capacity() - 1);
assertEquals(buffer.capacity() - 1, retainedSlice.writerIndex());
retainedSlice.release();
retainedSlice = buffer.retainedSlice(1, buffer.capacity() - 2);
assertEquals(buffer.capacity() - 2, retainedSlice.writerIndex());
retainedSlice.release();
}
@Test
@SuppressWarnings("ObjectEqualsNull")
public void testEquals() {
assertFalse(buffer.equals(null));
assertFalse(buffer.equals(new Object()));
byte[] value = new byte[32];
buffer.setIndex(0, value.length);
random.nextBytes(value);
buffer.setBytes(0, value);
assertEquals(buffer, wrappedBuffer(value));
assertEquals(buffer, wrappedBuffer(value).order(LITTLE_ENDIAN));
value[0] ++;
assertFalse(buffer.equals(wrappedBuffer(value)));
assertFalse(buffer.equals(wrappedBuffer(value).order(LITTLE_ENDIAN)));
}
@Test
public void testCompareTo() {
try {
buffer.compareTo(null);
fail();
} catch (NullPointerException e) {
// Expected
}
// Fill the random stuff
byte[] value = new byte[32];
random.nextBytes(value);
// Prevent overflow / underflow
if (value[0] == 0) {
value[0] ++;
} else if (value[0] == -1) {
value[0] --;
}
buffer.setIndex(0, value.length);
buffer.setBytes(0, value);
assertEquals(0, buffer.compareTo(wrappedBuffer(value)));
assertEquals(0, buffer.compareTo(wrappedBuffer(value).order(LITTLE_ENDIAN)));
value[0] ++;
assertTrue(buffer.compareTo(wrappedBuffer(value)) < 0);
assertTrue(buffer.compareTo(wrappedBuffer(value).order(LITTLE_ENDIAN)) < 0);
value[0] -= 2;
assertTrue(buffer.compareTo(wrappedBuffer(value)) > 0);
assertTrue(buffer.compareTo(wrappedBuffer(value).order(LITTLE_ENDIAN)) > 0);
value[0] ++;
assertTrue(buffer.compareTo(wrappedBuffer(value, 0, 31)) > 0);
assertTrue(buffer.compareTo(wrappedBuffer(value, 0, 31).order(LITTLE_ENDIAN)) > 0);
assertTrue(buffer.slice(0, 31).compareTo(wrappedBuffer(value)) < 0);
assertTrue(buffer.slice(0, 31).compareTo(wrappedBuffer(value).order(LITTLE_ENDIAN)) < 0);
ByteBuf retainedSlice = buffer.retainedSlice(0, 31);
assertTrue(retainedSlice.compareTo(wrappedBuffer(value)) < 0);
retainedSlice.release();
retainedSlice = buffer.retainedSlice(0, 31);
assertTrue(retainedSlice.compareTo(wrappedBuffer(value).order(LITTLE_ENDIAN)) < 0);
retainedSlice.release();
}
@Test
public void testCompareTo2() {
byte[] bytes = {1, 2, 3, 4};
byte[] bytesReversed = {4, 3, 2, 1};
ByteBuf buf1 = newBuffer(4).clear().writeBytes(bytes).order(ByteOrder.LITTLE_ENDIAN);
ByteBuf buf2 = newBuffer(4).clear().writeBytes(bytesReversed).order(ByteOrder.LITTLE_ENDIAN);
ByteBuf buf3 = newBuffer(4).clear().writeBytes(bytes).order(ByteOrder.BIG_ENDIAN);
ByteBuf buf4 = newBuffer(4).clear().writeBytes(bytesReversed).order(ByteOrder.BIG_ENDIAN);
try {
assertEquals(buf1.compareTo(buf2), buf3.compareTo(buf4));
assertEquals(buf2.compareTo(buf1), buf4.compareTo(buf3));
assertEquals(buf1.compareTo(buf3), buf2.compareTo(buf4));
assertEquals(buf3.compareTo(buf1), buf4.compareTo(buf2));
} finally {
buf1.release();
buf2.release();
buf3.release();
buf4.release();
}
}
@Test
public void testToString() {
ByteBuf copied = copiedBuffer("Hello, World!", CharsetUtil.ISO_8859_1);
buffer.clear();
buffer.writeBytes(copied);
assertEquals("Hello, World!", buffer.toString(CharsetUtil.ISO_8859_1));
copied.release();
}
@Test(timeout = 10000)
public void testToStringMultipleThreads() throws Throwable {
buffer.clear();
buffer.writeBytes("Hello, World!".getBytes(CharsetUtil.ISO_8859_1));
final AtomicInteger counter = new AtomicInteger(30000);
final AtomicReference<Throwable> errorRef = new AtomicReference<Throwable>();
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
while (errorRef.get() == null && counter.decrementAndGet() > 0) {
assertEquals("Hello, World!", buffer.toString(CharsetUtil.ISO_8859_1));
}
} catch (Throwable cause) {
errorRef.compareAndSet(null, cause);
}
}
});
threads.add(thread);
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
Throwable error = errorRef.get();
if (error != null) {
throw error;
}
}
@Test
public void testSWARIndexOf() {
ByteBuf buffer = newBuffer(16);
buffer.clear();
// Ensure the buffer is completely zero'ed.
buffer.setZero(0, buffer.capacity());
buffer.writeByte((byte) 0); // 0
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0); // 7
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 1); // 11
buffer.writeByte((byte) 2);
buffer.writeByte((byte) 3);
buffer.writeByte((byte) 4);
buffer.writeByte((byte) 1);
assertEquals(11, buffer.indexOf(0, 12, (byte) 1));
assertEquals(12, buffer.indexOf(0, 16, (byte) 2));
assertEquals(-1, buffer.indexOf(0, 11, (byte) 1));
assertEquals(11, buffer.indexOf(0, 16, (byte) 1));
buffer.release();
}
@Test
public void testIndexOf() {
buffer.clear();
// Ensure the buffer is completely zero'ed.
buffer.setZero(0, buffer.capacity());
buffer.writeByte((byte) 1);
buffer.writeByte((byte) 2);
buffer.writeByte((byte) 3);
buffer.writeByte((byte) 2);
buffer.writeByte((byte) 1);
assertEquals(-1, buffer.indexOf(1, 4, (byte) 1));
assertEquals(-1, buffer.indexOf(4, 1, (byte) 1));
assertEquals(1, buffer.indexOf(1, 4, (byte) 2));
assertEquals(3, buffer.indexOf(4, 1, (byte) 2));
try {
buffer.indexOf(0, buffer.capacity() + 1, (byte) 0);
fail();
} catch (IndexOutOfBoundsException expected) {
// expected
}
try {
buffer.indexOf(buffer.capacity(), -1, (byte) 0);
fail();
} catch (IndexOutOfBoundsException expected) {
// expected
}
assertEquals(4, buffer.indexOf(buffer.capacity() + 1, 0, (byte) 1));
assertEquals(0, buffer.indexOf(-1, buffer.capacity(), (byte) 1));
}
@Test
public void testIndexOfReleaseBuffer() {
ByteBuf buffer = releasedBuffer();
if (buffer.capacity() != 0) {
try {
buffer.indexOf(0, 1, (byte) 1);
fail();
} catch (IllegalReferenceCountException expected) {
// expected
}
} else {
assertEquals(-1, buffer.indexOf(0, 1, (byte) 1));
}
}
@Test
public void testNioBuffer1() {
assumeTrue(buffer.nioBufferCount() == 1);
byte[] value = new byte[buffer.capacity()];
random.nextBytes(value);
buffer.clear();
buffer.writeBytes(value);
assertRemainingEquals(ByteBuffer.wrap(value), buffer.nioBuffer());
}
@Test
public void testToByteBuffer2() {
assumeTrue(buffer.nioBufferCount() == 1);
byte[] value = new byte[buffer.capacity()];
random.nextBytes(value);
buffer.clear();
buffer.writeBytes(value);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
assertRemainingEquals(ByteBuffer.wrap(value, i, BLOCK_SIZE), buffer.nioBuffer(i, BLOCK_SIZE));
}
}
private static void assertRemainingEquals(ByteBuffer expected, ByteBuffer actual) {
int remaining = expected.remaining();
int remaining2 = actual.remaining();
assertEquals(remaining, remaining2);
byte[] array1 = new byte[remaining];
byte[] array2 = new byte[remaining2];
expected.get(array1);
actual.get(array2);
assertArrayEquals(array1, array2);
}
@Test
public void testToByteBuffer3() {
assumeTrue(buffer.nioBufferCount() == 1);
assertEquals(buffer.order(), buffer.nioBuffer().order());
}
@Test
public void testSkipBytes1() {
buffer.setIndex(CAPACITY / 4, CAPACITY / 2);
buffer.skipBytes(CAPACITY / 4);
assertEquals(CAPACITY / 4 * 2, buffer.readerIndex());
try {
buffer.skipBytes(CAPACITY / 4 + 1);
fail();
} catch (IndexOutOfBoundsException e) {
// Expected
}
// Should remain unchanged.
assertEquals(CAPACITY / 4 * 2, buffer.readerIndex());
}
@Test
public void testHashCode() {
ByteBuf elemA = buffer(15);
ByteBuf elemB = directBuffer(15);
elemA.writeBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5 });
elemB.writeBytes(new byte[] { 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9 });
Set<ByteBuf> set = new HashSet<ByteBuf>();
set.add(elemA);
set.add(elemB);
assertEquals(2, set.size());
ByteBuf elemACopy = elemA.copy();
assertTrue(set.contains(elemACopy));
ByteBuf elemBCopy = elemB.copy();
assertTrue(set.contains(elemBCopy));
buffer.clear();
buffer.writeBytes(elemA.duplicate());
assertTrue(set.remove(buffer));
assertFalse(set.contains(elemA));
assertEquals(1, set.size());
buffer.clear();
buffer.writeBytes(elemB.duplicate());
assertTrue(set.remove(buffer));
assertFalse(set.contains(elemB));
assertEquals(0, set.size());
elemA.release();
elemB.release();
elemACopy.release();
elemBCopy.release();
}
// Test case for https://github.com/netty/netty/issues/325
@Test
public void testDiscardAllReadBytes() {
buffer.writerIndex(buffer.capacity());
buffer.readerIndex(buffer.writerIndex());
buffer.discardReadBytes();
}
@Test
public void testForEachByte() {
buffer.clear();
for (int i = 0; i < CAPACITY; i ++) {
buffer.writeByte(i + 1);
}
final AtomicInteger lastIndex = new AtomicInteger();
buffer.setIndex(CAPACITY / 4, CAPACITY * 3 / 4);
assertThat(buffer.forEachByte(new ByteProcessor() {
int i = CAPACITY / 4;
@Override
public boolean process(byte value) throws Exception {
assertThat(value, is((byte) (i + 1)));
lastIndex.set(i);
i ++;
return true;
}
}), is(-1));
assertThat(lastIndex.get(), is(CAPACITY * 3 / 4 - 1));
}
@Test
public void testForEachByteAbort() {
buffer.clear();
for (int i = 0; i < CAPACITY; i ++) {
buffer.writeByte(i + 1);
}
final int stop = CAPACITY / 2;
assertThat(buffer.forEachByte(CAPACITY / 3, CAPACITY / 3, new ByteProcessor() {
int i = CAPACITY / 3;
@Override
public boolean process(byte value) throws Exception {
assertThat(value, is((byte) (i + 1)));
if (i == stop) {
return false;
}
i++;
return true;
}
}), is(stop));
}
@Test
public void testForEachByteDesc() {
buffer.clear();
for (int i = 0; i < CAPACITY; i ++) {
buffer.writeByte(i + 1);
}
final AtomicInteger lastIndex = new AtomicInteger();
assertThat(buffer.forEachByteDesc(CAPACITY / 4, CAPACITY * 2 / 4, new ByteProcessor() {
int i = CAPACITY * 3 / 4 - 1;
@Override
public boolean process(byte value) throws Exception {
assertThat(value, is((byte) (i + 1)));
lastIndex.set(i);
i --;
return true;
}
}), is(-1));
assertThat(lastIndex.get(), is(CAPACITY / 4));
}
@Test
public void testInternalNioBuffer() {
testInternalNioBuffer(128);
testInternalNioBuffer(1024);
testInternalNioBuffer(4 * 1024);
testInternalNioBuffer(64 * 1024);
testInternalNioBuffer(32 * 1024 * 1024);
testInternalNioBuffer(64 * 1024 * 1024);
}
private void testInternalNioBuffer(int a) {
ByteBuf buffer = newBuffer(2);
ByteBuffer buf = buffer.internalNioBuffer(buffer.readerIndex(), 1);
assertEquals(1, buf.remaining());
byte[] data = new byte[a];
PlatformDependent.threadLocalRandom().nextBytes(data);
buffer.writeBytes(data);
buf = buffer.internalNioBuffer(buffer.readerIndex(), a);
assertEquals(a, buf.remaining());
for (int i = 0; i < a; i++) {
assertEquals(data[i], buf.get());
}
assertFalse(buf.hasRemaining());
buffer.release();
}
@Test
public void testDuplicateReadGatheringByteChannelMultipleThreads() throws Exception {
testReadGatheringByteChannelMultipleThreads(false);
}
@Test
public void testSliceReadGatheringByteChannelMultipleThreads() throws Exception {
testReadGatheringByteChannelMultipleThreads(true);
}
private void testReadGatheringByteChannelMultipleThreads(final boolean slice) throws Exception {
final byte[] bytes = new byte[8];
random.nextBytes(bytes);
final ByteBuf buffer = newBuffer(8);
buffer.writeBytes(bytes);
final CountDownLatch latch = new CountDownLatch(60000);
final CyclicBarrier barrier = new CyclicBarrier(11);
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (latch.getCount() > 0) {
ByteBuf buf;
if (slice) {
buf = buffer.slice();
} else {
buf = buffer.duplicate();
}
TestGatheringByteChannel channel = new TestGatheringByteChannel();
while (buf.isReadable()) {
try {
buf.readBytes(channel, buf.readableBytes());
} catch (IOException e) {
// Never happens
return;
}
}
assertArrayEquals(bytes, channel.writtenBytes());
latch.countDown();
}
try {
barrier.await();
} catch (Exception e) {
// ignore
}
}
}).start();
}
latch.await(10, TimeUnit.SECONDS);
barrier.await(5, TimeUnit.SECONDS);
buffer.release();
}
@Test
public void testDuplicateReadOutputStreamMultipleThreads() throws Exception {
testReadOutputStreamMultipleThreads(false);
}
@Test
public void testSliceReadOutputStreamMultipleThreads() throws Exception {
testReadOutputStreamMultipleThreads(true);
}
private void testReadOutputStreamMultipleThreads(final boolean slice) throws Exception {
final byte[] bytes = new byte[8];
random.nextBytes(bytes);
final ByteBuf buffer = newBuffer(8);
buffer.writeBytes(bytes);
final CountDownLatch latch = new CountDownLatch(60000);
final CyclicBarrier barrier = new CyclicBarrier(11);
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (latch.getCount() > 0) {
ByteBuf buf;
if (slice) {
buf = buffer.slice();
} else {
buf = buffer.duplicate();
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
while (buf.isReadable()) {
try {
buf.readBytes(out, buf.readableBytes());
} catch (IOException e) {
// Never happens
return;
}
}
assertArrayEquals(bytes, out.toByteArray());
latch.countDown();
}
try {
barrier.await();
} catch (Exception e) {
// ignore
}
}
}).start();
}
latch.await(10, TimeUnit.SECONDS);
barrier.await(5, TimeUnit.SECONDS);
buffer.release();
}
@Test
public void testDuplicateBytesInArrayMultipleThreads() throws Exception {
testBytesInArrayMultipleThreads(false);
}
@Test
public void testSliceBytesInArrayMultipleThreads() throws Exception {
testBytesInArrayMultipleThreads(true);
}
private void testBytesInArrayMultipleThreads(final boolean slice) throws Exception {
final byte[] bytes = new byte[8];
random.nextBytes(bytes);
final ByteBuf buffer = newBuffer(8);
buffer.writeBytes(bytes);
final AtomicReference<Throwable> cause = new AtomicReference<Throwable>();
final CountDownLatch latch = new CountDownLatch(60000);
final CyclicBarrier barrier = new CyclicBarrier(11);
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (cause.get() == null && latch.getCount() > 0) {
ByteBuf buf;
if (slice) {
buf = buffer.slice();
} else {
buf = buffer.duplicate();
}
byte[] array = new byte[8];
buf.readBytes(array);
assertArrayEquals(bytes, array);
Arrays.fill(array, (byte) 0);
buf.getBytes(0, array);
assertArrayEquals(bytes, array);
latch.countDown();
}
try {
barrier.await();
} catch (Exception e) {
// ignore
}
}
}).start();
}
latch.await(10, TimeUnit.SECONDS);
barrier.await(5, TimeUnit.SECONDS);
assertNull(cause.get());
buffer.release();
}
@Test(expected = IndexOutOfBoundsException.class)
public void readByteThrowsIndexOutOfBoundsException() {
final ByteBuf buffer = newBuffer(8);
try {
buffer.writeByte(0);
assertEquals((byte) 0, buffer.readByte());
buffer.readByte();
} finally {
buffer.release();
}
}
@Test
@SuppressWarnings("ForLoopThatDoesntUseLoopVariable")
public void testNioBufferExposeOnlyRegion() {
final ByteBuf buffer = newBuffer(8);
byte[] data = new byte[8];
random.nextBytes(data);
buffer.writeBytes(data);
ByteBuffer nioBuf = buffer.nioBuffer(1, data.length - 2);
assertEquals(0, nioBuf.position());
assertEquals(6, nioBuf.remaining());
for (int i = 1; nioBuf.hasRemaining(); i++) {
assertEquals(data[i], nioBuf.get());
}
buffer.release();
}
@Test
public void ensureWritableWithForceDoesNotThrow() {
ensureWritableDoesNotThrow(true);
}
@Test
public void ensureWritableWithOutForceDoesNotThrow() {
ensureWritableDoesNotThrow(false);
}
private void ensureWritableDoesNotThrow(boolean force) {
final ByteBuf buffer = newBuffer(8);
buffer.writerIndex(buffer.capacity());
buffer.ensureWritable(8, force);
buffer.release();
}
// See:
// - https://github.com/netty/netty/issues/2587
// - https://github.com/netty/netty/issues/2580
@Test
public void testLittleEndianWithExpand() {
ByteBuf buffer = newBuffer(0).order(LITTLE_ENDIAN);
buffer.writeInt(0x12345678);
assertEquals("78563412", ByteBufUtil.hexDump(buffer));
buffer.release();
}
private ByteBuf releasedBuffer() {
ByteBuf buffer = newBuffer(8);
// Clear the buffer so we are sure the reader and writer indices are 0.
// This is important as we may return a slice from newBuffer(...).
buffer.clear();
assertTrue(buffer.release());
return buffer;
}
@Test(expected = IllegalReferenceCountException.class)
public void testDiscardReadBytesAfterRelease() {
releasedBuffer().discardReadBytes();
}
@Test(expected = IllegalReferenceCountException.class)
public void testDiscardSomeReadBytesAfterRelease() {
releasedBuffer().discardSomeReadBytes();
}
@Test(expected = IllegalReferenceCountException.class)
public void testEnsureWritableAfterRelease() {
releasedBuffer().ensureWritable(16);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBooleanAfterRelease() {
releasedBuffer().getBoolean(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetByteAfterRelease() {
releasedBuffer().getByte(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetUnsignedByteAfterRelease() {
releasedBuffer().getUnsignedByte(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetShortAfterRelease() {
releasedBuffer().getShort(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetShortLEAfterRelease() {
releasedBuffer().getShortLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetUnsignedShortAfterRelease() {
releasedBuffer().getUnsignedShort(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetUnsignedShortLEAfterRelease() {
releasedBuffer().getUnsignedShortLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetMediumAfterRelease() {
releasedBuffer().getMedium(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetMediumLEAfterRelease() {
releasedBuffer().getMediumLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetUnsignedMediumAfterRelease() {
releasedBuffer().getUnsignedMedium(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetIntAfterRelease() {
releasedBuffer().getInt(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetIntLEAfterRelease() {
releasedBuffer().getIntLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetUnsignedIntAfterRelease() {
releasedBuffer().getUnsignedInt(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetUnsignedIntLEAfterRelease() {
releasedBuffer().getUnsignedIntLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetLongAfterRelease() {
releasedBuffer().getLong(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetLongLEAfterRelease() {
releasedBuffer().getLongLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetCharAfterRelease() {
releasedBuffer().getChar(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetFloatAfterRelease() {
releasedBuffer().getFloat(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetFloatLEAfterRelease() {
releasedBuffer().getFloatLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetDoubleAfterRelease() {
releasedBuffer().getDouble(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetDoubleLEAfterRelease() {
releasedBuffer().getDoubleLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease() {
ByteBuf buffer = buffer(8);
try {
releasedBuffer().getBytes(0, buffer);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease2() {
ByteBuf buffer = buffer();
try {
releasedBuffer().getBytes(0, buffer, 1);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease3() {
ByteBuf buffer = buffer();
try {
releasedBuffer().getBytes(0, buffer, 0, 1);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease4() {
releasedBuffer().getBytes(0, new byte[8]);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease5() {
releasedBuffer().getBytes(0, new byte[8], 0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease6() {
releasedBuffer().getBytes(0, ByteBuffer.allocate(8));
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease7() throws IOException {
releasedBuffer().getBytes(0, new ByteArrayOutputStream(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease8() throws IOException {
releasedBuffer().getBytes(0, new DevNullGatheringByteChannel(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBooleanAfterRelease() {
releasedBuffer().setBoolean(0, true);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetByteAfterRelease() {
releasedBuffer().setByte(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetShortAfterRelease() {
releasedBuffer().setShort(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetShortLEAfterRelease() {
releasedBuffer().setShortLE(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetMediumAfterRelease() {
releasedBuffer().setMedium(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetMediumLEAfterRelease() {
releasedBuffer().setMediumLE(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetIntAfterRelease() {
releasedBuffer().setInt(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetIntLEAfterRelease() {
releasedBuffer().setIntLE(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetLongAfterRelease() {
releasedBuffer().setLong(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetLongLEAfterRelease() {
releasedBuffer().setLongLE(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetCharAfterRelease() {
releasedBuffer().setChar(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetFloatAfterRelease() {
releasedBuffer().setFloat(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetDoubleAfterRelease() {
releasedBuffer().setDouble(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease() {
ByteBuf buffer = buffer();
try {
releasedBuffer().setBytes(0, buffer);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease2() {
ByteBuf buffer = buffer();
try {
releasedBuffer().setBytes(0, buffer, 1);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease3() {
ByteBuf buffer = buffer();
try {
releasedBuffer().setBytes(0, buffer, 0, 1);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetUsAsciiCharSequenceAfterRelease() {
testSetCharSequenceAfterRelease0(CharsetUtil.US_ASCII);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetIso88591CharSequenceAfterRelease() {
testSetCharSequenceAfterRelease0(CharsetUtil.ISO_8859_1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetUtf8CharSequenceAfterRelease() {
testSetCharSequenceAfterRelease0(CharsetUtil.UTF_8);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetUtf16CharSequenceAfterRelease() {
testSetCharSequenceAfterRelease0(CharsetUtil.UTF_16);
}
private void testSetCharSequenceAfterRelease0(Charset charset) {
releasedBuffer().setCharSequence(0, "x", charset);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease4() {
releasedBuffer().setBytes(0, new byte[8]);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease5() {
releasedBuffer().setBytes(0, new byte[8], 0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease6() {
releasedBuffer().setBytes(0, ByteBuffer.allocate(8));
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease7() throws IOException {
releasedBuffer().setBytes(0, new ByteArrayInputStream(new byte[8]), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease8() throws IOException {
releasedBuffer().setBytes(0, new TestScatteringByteChannel(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetZeroAfterRelease() {
releasedBuffer().setZero(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBooleanAfterRelease() {
releasedBuffer().readBoolean();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadByteAfterRelease() {
releasedBuffer().readByte();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadUnsignedByteAfterRelease() {
releasedBuffer().readUnsignedByte();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadShortAfterRelease() {
releasedBuffer().readShort();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadShortLEAfterRelease() {
releasedBuffer().readShortLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadUnsignedShortAfterRelease() {
releasedBuffer().readUnsignedShort();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadUnsignedShortLEAfterRelease() {
releasedBuffer().readUnsignedShortLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadMediumAfterRelease() {
releasedBuffer().readMedium();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadMediumLEAfterRelease() {
releasedBuffer().readMediumLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadUnsignedMediumAfterRelease() {
releasedBuffer().readUnsignedMedium();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadUnsignedMediumLEAfterRelease() {
releasedBuffer().readUnsignedMediumLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadIntAfterRelease() {
releasedBuffer().readInt();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadIntLEAfterRelease() {
releasedBuffer().readIntLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadUnsignedIntAfterRelease() {
releasedBuffer().readUnsignedInt();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadUnsignedIntLEAfterRelease() {
releasedBuffer().readUnsignedIntLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadLongAfterRelease() {
releasedBuffer().readLong();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadLongLEAfterRelease() {
releasedBuffer().readLongLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadCharAfterRelease() {
releasedBuffer().readChar();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadFloatAfterRelease() {
releasedBuffer().readFloat();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadFloatLEAfterRelease() {
releasedBuffer().readFloatLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadDoubleAfterRelease() {
releasedBuffer().readDouble();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadDoubleLEAfterRelease() {
releasedBuffer().readDoubleLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease() {
releasedBuffer().readBytes(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease2() {
ByteBuf buffer = buffer(8);
try {
releasedBuffer().readBytes(buffer);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease3() {
ByteBuf buffer = buffer(8);
try {
releasedBuffer().readBytes(buffer);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease4() {
ByteBuf buffer = buffer(8);
try {
releasedBuffer().readBytes(buffer, 0, 1);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease5() {
releasedBuffer().readBytes(new byte[8]);
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease6() {
releasedBuffer().readBytes(new byte[8], 0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease7() {
releasedBuffer().readBytes(ByteBuffer.allocate(8));
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease8() throws IOException {
releasedBuffer().readBytes(new ByteArrayOutputStream(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease9() throws IOException {
releasedBuffer().readBytes(new ByteArrayOutputStream(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease10() throws IOException {
releasedBuffer().readBytes(new DevNullGatheringByteChannel(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBooleanAfterRelease() {
releasedBuffer().writeBoolean(true);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteByteAfterRelease() {
releasedBuffer().writeByte(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteShortAfterRelease() {
releasedBuffer().writeShort(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteShortLEAfterRelease() {
releasedBuffer().writeShortLE(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteMediumAfterRelease() {
releasedBuffer().writeMedium(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteMediumLEAfterRelease() {
releasedBuffer().writeMediumLE(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteIntAfterRelease() {
releasedBuffer().writeInt(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteIntLEAfterRelease() {
releasedBuffer().writeIntLE(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteLongAfterRelease() {
releasedBuffer().writeLong(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteLongLEAfterRelease() {
releasedBuffer().writeLongLE(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteCharAfterRelease() {
releasedBuffer().writeChar(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteFloatAfterRelease() {
releasedBuffer().writeFloat(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteFloatLEAfterRelease() {
releasedBuffer().writeFloatLE(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteDoubleAfterRelease() {
releasedBuffer().writeDouble(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteDoubleLEAfterRelease() {
releasedBuffer().writeDoubleLE(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease() {
ByteBuf buffer = buffer(8);
try {
releasedBuffer().writeBytes(buffer);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease2() {
ByteBuf buffer = copiedBuffer(new byte[8]);
try {
releasedBuffer().writeBytes(buffer, 1);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease3() {
ByteBuf buffer = buffer(8);
try {
releasedBuffer().writeBytes(buffer, 0, 1);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease4() {
releasedBuffer().writeBytes(new byte[8]);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease5() {
releasedBuffer().writeBytes(new byte[8], 0 , 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease6() {
releasedBuffer().writeBytes(ByteBuffer.allocate(8));
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease7() throws IOException {
releasedBuffer().writeBytes(new ByteArrayInputStream(new byte[8]), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease8() throws IOException {
releasedBuffer().writeBytes(new TestScatteringByteChannel(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteZeroAfterRelease() throws IOException {
releasedBuffer().writeZero(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteUsAsciiCharSequenceAfterRelease() {
testWriteCharSequenceAfterRelease0(CharsetUtil.US_ASCII);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteIso88591CharSequenceAfterRelease() {
testWriteCharSequenceAfterRelease0(CharsetUtil.ISO_8859_1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteUtf8CharSequenceAfterRelease() {
testWriteCharSequenceAfterRelease0(CharsetUtil.UTF_8);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteUtf16CharSequenceAfterRelease() {
testWriteCharSequenceAfterRelease0(CharsetUtil.UTF_16);
}
private void testWriteCharSequenceAfterRelease0(Charset charset) {
releasedBuffer().writeCharSequence("x", charset);
}
@Test(expected = IllegalReferenceCountException.class)
public void testForEachByteAfterRelease() {
releasedBuffer().forEachByte(new TestByteProcessor());
}
@Test(expected = IllegalReferenceCountException.class)
public void testForEachByteAfterRelease1() {
releasedBuffer().forEachByte(0, 1, new TestByteProcessor());
}
@Test(expected = IllegalReferenceCountException.class)
public void testForEachByteDescAfterRelease() {
releasedBuffer().forEachByteDesc(new TestByteProcessor());
}
@Test(expected = IllegalReferenceCountException.class)
public void testForEachByteDescAfterRelease1() {
releasedBuffer().forEachByteDesc(0, 1, new TestByteProcessor());
}
@Test(expected = IllegalReferenceCountException.class)
public void testCopyAfterRelease() {
releasedBuffer().copy();
}
@Test(expected = IllegalReferenceCountException.class)
public void testCopyAfterRelease1() {
releasedBuffer().copy();
}
@Test(expected = IllegalReferenceCountException.class)
public void testNioBufferAfterRelease() {
releasedBuffer().nioBuffer();
}
@Test(expected = IllegalReferenceCountException.class)
public void testNioBufferAfterRelease1() {
releasedBuffer().nioBuffer(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testInternalNioBufferAfterRelease() {
ByteBuf releasedBuffer = releasedBuffer();
releasedBuffer.internalNioBuffer(releasedBuffer.readerIndex(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testNioBuffersAfterRelease() {
releasedBuffer().nioBuffers();
}
@Test(expected = IllegalReferenceCountException.class)
public void testNioBuffersAfterRelease2() {
releasedBuffer().nioBuffers(0, 1);
}
@Test
public void testArrayAfterRelease() {
ByteBuf buf = releasedBuffer();
if (buf.hasArray()) {
try {
buf.array();
fail();
} catch (IllegalReferenceCountException e) {
// expected
}
}
}
@Test
public void testMemoryAddressAfterRelease() {
ByteBuf buf = releasedBuffer();
if (buf.hasMemoryAddress()) {
try {
buf.memoryAddress();
fail();
} catch (IllegalReferenceCountException e) {
// expected
}
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testSliceAfterRelease() {
releasedBuffer().slice();
}
@Test(expected = IllegalReferenceCountException.class)
public void testSliceAfterRelease2() {
releasedBuffer().slice(0, 1);
}
private static void assertSliceFailAfterRelease(ByteBuf... bufs) {
for (ByteBuf buf : bufs) {
if (buf.refCnt() > 0) {
buf.release();
}
}
for (ByteBuf buf : bufs) {
try {
assertEquals(0, buf.refCnt());
buf.slice();
fail();
} catch (IllegalReferenceCountException ignored) {
// as expected
}
}
}
@Test
public void testSliceAfterReleaseRetainedSlice() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
assertSliceFailAfterRelease(buf, buf2);
}
@Test
public void testSliceAfterReleaseRetainedSliceDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
ByteBuf buf3 = buf2.duplicate();
assertSliceFailAfterRelease(buf, buf2, buf3);
}
@Test
public void testSliceAfterReleaseRetainedSliceRetainedDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
ByteBuf buf3 = buf2.retainedDuplicate();
assertSliceFailAfterRelease(buf, buf2, buf3);
}
@Test
public void testSliceAfterReleaseRetainedDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedDuplicate();
assertSliceFailAfterRelease(buf, buf2);
}
@Test
public void testSliceAfterReleaseRetainedDuplicateSlice() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedDuplicate();
ByteBuf buf3 = buf2.slice(0, 1);
assertSliceFailAfterRelease(buf, buf2, buf3);
}
@Test(expected = IllegalReferenceCountException.class)
public void testRetainedSliceAfterRelease() {
releasedBuffer().retainedSlice();
}
@Test(expected = IllegalReferenceCountException.class)
public void testRetainedSliceAfterRelease2() {
releasedBuffer().retainedSlice(0, 1);
}
private static void assertRetainedSliceFailAfterRelease(ByteBuf... bufs) {
for (ByteBuf buf : bufs) {
if (buf.refCnt() > 0) {
buf.release();
}
}
for (ByteBuf buf : bufs) {
try {
assertEquals(0, buf.refCnt());
buf.retainedSlice();
fail();
} catch (IllegalReferenceCountException ignored) {
// as expected
}
}
}
@Test
public void testRetainedSliceAfterReleaseRetainedSlice() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
assertRetainedSliceFailAfterRelease(buf, buf2);
}
@Test
public void testRetainedSliceAfterReleaseRetainedSliceDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
ByteBuf buf3 = buf2.duplicate();
assertRetainedSliceFailAfterRelease(buf, buf2, buf3);
}
@Test
public void testRetainedSliceAfterReleaseRetainedSliceRetainedDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
ByteBuf buf3 = buf2.retainedDuplicate();
assertRetainedSliceFailAfterRelease(buf, buf2, buf3);
}
@Test
public void testRetainedSliceAfterReleaseRetainedDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedDuplicate();
assertRetainedSliceFailAfterRelease(buf, buf2);
}
@Test
public void testRetainedSliceAfterReleaseRetainedDuplicateSlice() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedDuplicate();
ByteBuf buf3 = buf2.slice(0, 1);
assertRetainedSliceFailAfterRelease(buf, buf2, buf3);
}
@Test(expected = IllegalReferenceCountException.class)
public void testDuplicateAfterRelease() {
releasedBuffer().duplicate();
}
@Test(expected = IllegalReferenceCountException.class)
public void testRetainedDuplicateAfterRelease() {
releasedBuffer().retainedDuplicate();
}
private static void assertDuplicateFailAfterRelease(ByteBuf... bufs) {
for (ByteBuf buf : bufs) {
if (buf.refCnt() > 0) {
buf.release();
}
}
for (ByteBuf buf : bufs) {
try {
assertEquals(0, buf.refCnt());
buf.duplicate();
fail();
} catch (IllegalReferenceCountException ignored) {
// as expected
}
}
}
@Test
public void testDuplicateAfterReleaseRetainedSliceDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
ByteBuf buf3 = buf2.duplicate();
assertDuplicateFailAfterRelease(buf, buf2, buf3);
}
@Test
public void testDuplicateAfterReleaseRetainedDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedDuplicate();
assertDuplicateFailAfterRelease(buf, buf2);
}
@Test
public void testDuplicateAfterReleaseRetainedDuplicateSlice() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedDuplicate();
ByteBuf buf3 = buf2.slice(0, 1);
assertDuplicateFailAfterRelease(buf, buf2, buf3);
}
private static void assertRetainedDuplicateFailAfterRelease(ByteBuf... bufs) {
for (ByteBuf buf : bufs) {
if (buf.refCnt() > 0) {
buf.release();
}
}
for (ByteBuf buf : bufs) {
try {
assertEquals(0, buf.refCnt());
buf.retainedDuplicate();
fail();
} catch (IllegalReferenceCountException ignored) {
// as expected
}
}
}
@Test
public void testRetainedDuplicateAfterReleaseRetainedDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedDuplicate();
assertRetainedDuplicateFailAfterRelease(buf, buf2);
}
@Test
public void testRetainedDuplicateAfterReleaseDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.duplicate();
assertRetainedDuplicateFailAfterRelease(buf, buf2);
}
@Test
public void testRetainedDuplicateAfterReleaseRetainedSlice() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
assertRetainedDuplicateFailAfterRelease(buf, buf2);
}
@Test
public void testSliceRelease() {
ByteBuf buf = newBuffer(8);
assertEquals(1, buf.refCnt());
assertTrue(buf.slice().release());
assertEquals(0, buf.refCnt());
}
@Test(expected = IndexOutOfBoundsException.class)
public void testReadSliceOutOfBounds() {
testReadSliceOutOfBounds(false);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testReadRetainedSliceOutOfBounds() {
testReadSliceOutOfBounds(true);
}
private void testReadSliceOutOfBounds(boolean retainedSlice) {
ByteBuf buf = newBuffer(100);
try {
buf.writeZero(50);
if (retainedSlice) {
buf.readRetainedSlice(51);
} else {
buf.readSlice(51);
}
fail();
} finally {
buf.release();
}
}
@Test
public void testWriteUsAsciiCharSequenceExpand() {
testWriteCharSequenceExpand(CharsetUtil.US_ASCII);
}
@Test
public void testWriteUtf8CharSequenceExpand() {
testWriteCharSequenceExpand(CharsetUtil.UTF_8);
}
@Test
public void testWriteIso88591CharSequenceExpand() {
testWriteCharSequenceExpand(CharsetUtil.ISO_8859_1);
}
@Test
public void testWriteUtf16CharSequenceExpand() {
testWriteCharSequenceExpand(CharsetUtil.UTF_16);
}
private void testWriteCharSequenceExpand(Charset charset) {
ByteBuf buf = newBuffer(1);
try {
int writerIndex = buf.capacity() - 1;
buf.writerIndex(writerIndex);
int written = buf.writeCharSequence("AB", charset);
assertEquals(writerIndex, buf.writerIndex() - written);
} finally {
buf.release();
}
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSetUsAsciiCharSequenceNoExpand() {
testSetCharSequenceNoExpand(CharsetUtil.US_ASCII);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSetUtf8CharSequenceNoExpand() {
testSetCharSequenceNoExpand(CharsetUtil.UTF_8);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSetIso88591CharSequenceNoExpand() {
testSetCharSequenceNoExpand(CharsetUtil.ISO_8859_1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSetUtf16CharSequenceNoExpand() {
testSetCharSequenceNoExpand(CharsetUtil.UTF_16);
}
private void testSetCharSequenceNoExpand(Charset charset) {
ByteBuf buf = newBuffer(1);
try {
buf.setCharSequence(0, "AB", charset);
} finally {
buf.release();
}
}
@Test
public void testSetUsAsciiCharSequence() {
testSetGetCharSequence(CharsetUtil.US_ASCII);
}
@Test
public void testSetUtf8CharSequence() {
testSetGetCharSequence(CharsetUtil.UTF_8);
}
@Test
public void testSetIso88591CharSequence() {
testSetGetCharSequence(CharsetUtil.ISO_8859_1);
}
@Test
public void testSetUtf16CharSequence() {
testSetGetCharSequence(CharsetUtil.UTF_16);
}
private static final CharBuffer EXTENDED_ASCII_CHARS, ASCII_CHARS;
static {
char[] chars = new char[256];
for (char c = 0; c < chars.length; c++) {
chars[c] = c;
}
EXTENDED_ASCII_CHARS = CharBuffer.wrap(chars);
ASCII_CHARS = CharBuffer.wrap(chars, 0, 128);
}
private void testSetGetCharSequence(Charset charset) {
ByteBuf buf = newBuffer(1024);
CharBuffer sequence = CharsetUtil.US_ASCII.equals(charset)
? ASCII_CHARS : EXTENDED_ASCII_CHARS;
int bytes = buf.setCharSequence(1, sequence, charset);
assertEquals(sequence, CharBuffer.wrap(buf.getCharSequence(1, bytes, charset)));
buf.release();
}
@Test
public void testWriteReadUsAsciiCharSequence() {
testWriteReadCharSequence(CharsetUtil.US_ASCII);
}
@Test
public void testWriteReadUtf8CharSequence() {
testWriteReadCharSequence(CharsetUtil.UTF_8);
}
@Test
public void testWriteReadIso88591CharSequence() {
testWriteReadCharSequence(CharsetUtil.ISO_8859_1);
}
@Test
public void testWriteReadUtf16CharSequence() {
testWriteReadCharSequence(CharsetUtil.UTF_16);
}
private void testWriteReadCharSequence(Charset charset) {
ByteBuf buf = newBuffer(1024);
CharBuffer sequence = CharsetUtil.US_ASCII.equals(charset)
? ASCII_CHARS : EXTENDED_ASCII_CHARS;
buf.writerIndex(1);
int bytes = buf.writeCharSequence(sequence, charset);
buf.readerIndex(1);
assertEquals(sequence, CharBuffer.wrap(buf.readCharSequence(bytes, charset)));
buf.release();
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRetainedSliceIndexOutOfBounds() {
testSliceOutOfBounds(true, true, true);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRetainedSliceLengthOutOfBounds() {
testSliceOutOfBounds(true, true, false);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testMixedSliceAIndexOutOfBounds() {
testSliceOutOfBounds(true, false, true);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testMixedSliceALengthOutOfBounds() {
testSliceOutOfBounds(true, false, false);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testMixedSliceBIndexOutOfBounds() {
testSliceOutOfBounds(false, true, true);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testMixedSliceBLengthOutOfBounds() {
testSliceOutOfBounds(false, true, false);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSliceIndexOutOfBounds() {
testSliceOutOfBounds(false, false, true);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSliceLengthOutOfBounds() {
testSliceOutOfBounds(false, false, false);
}
@Test
public void testRetainedSliceAndRetainedDuplicateContentIsExpected() {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected1 = newBuffer(6).resetWriterIndex();
ByteBuf expected2 = newBuffer(5).resetWriterIndex();
ByteBuf expected3 = newBuffer(4).resetWriterIndex();
ByteBuf expected4 = newBuffer(3).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected1.writeBytes(new byte[] {2, 3, 4, 5, 6, 7});
expected2.writeBytes(new byte[] {3, 4, 5, 6, 7});
expected3.writeBytes(new byte[] {4, 5, 6, 7});
expected4.writeBytes(new byte[] {5, 6, 7});
ByteBuf slice1 = buf.retainedSlice(buf.readerIndex() + 1, 6);
assertEquals(0, slice1.compareTo(expected1));
assertEquals(0, slice1.compareTo(buf.slice(buf.readerIndex() + 1, 6)));
// Simulate a handler that releases the original buffer, and propagates a slice.
buf.release();
// Advance the reader index on the slice.
slice1.readByte();
ByteBuf dup1 = slice1.retainedDuplicate();
assertEquals(0, dup1.compareTo(expected2));
assertEquals(0, dup1.compareTo(slice1.duplicate()));
// Advance the reader index on dup1.
dup1.readByte();
ByteBuf dup2 = dup1.duplicate();
assertEquals(0, dup2.compareTo(expected3));
// Advance the reader index on dup2.
dup2.readByte();
ByteBuf slice2 = dup2.retainedSlice(dup2.readerIndex(), 3);
assertEquals(0, slice2.compareTo(expected4));
assertEquals(0, slice2.compareTo(dup2.slice(dup2.readerIndex(), 3)));
// Cleanup the expected buffers used for testing.
assertTrue(expected1.release());
assertTrue(expected2.release());
assertTrue(expected3.release());
assertTrue(expected4.release());
slice2.release();
dup2.release();
assertEquals(slice2.refCnt(), dup2.refCnt());
assertEquals(dup2.refCnt(), dup1.refCnt());
// The handler is now done with the original slice
assertTrue(slice1.release());
// Reference counting may be shared, or may be independently tracked, but at this point all buffers should
// be deallocated and have a reference count of 0.
assertEquals(0, buf.refCnt());
assertEquals(0, slice1.refCnt());
assertEquals(0, slice2.refCnt());
assertEquals(0, dup1.refCnt());
assertEquals(0, dup2.refCnt());
}
@Test
public void testRetainedDuplicateAndRetainedSliceContentIsExpected() {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected1 = newBuffer(6).resetWriterIndex();
ByteBuf expected2 = newBuffer(5).resetWriterIndex();
ByteBuf expected3 = newBuffer(4).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected1.writeBytes(new byte[] {2, 3, 4, 5, 6, 7});
expected2.writeBytes(new byte[] {3, 4, 5, 6, 7});
expected3.writeBytes(new byte[] {5, 6, 7});
ByteBuf dup1 = buf.retainedDuplicate();
assertEquals(0, dup1.compareTo(buf));
assertEquals(0, dup1.compareTo(buf.slice()));
// Simulate a handler that releases the original buffer, and propagates a slice.
buf.release();
// Advance the reader index on the dup.
dup1.readByte();
ByteBuf slice1 = dup1.retainedSlice(dup1.readerIndex(), 6);
assertEquals(0, slice1.compareTo(expected1));
assertEquals(0, slice1.compareTo(slice1.duplicate()));
// Advance the reader index on slice1.
slice1.readByte();
ByteBuf dup2 = slice1.duplicate();
assertEquals(0, dup2.compareTo(slice1));
// Advance the reader index on dup2.
dup2.readByte();
ByteBuf slice2 = dup2.retainedSlice(dup2.readerIndex() + 1, 3);
assertEquals(0, slice2.compareTo(expected3));
assertEquals(0, slice2.compareTo(dup2.slice(dup2.readerIndex() + 1, 3)));
// Cleanup the expected buffers used for testing.
assertTrue(expected1.release());
assertTrue(expected2.release());
assertTrue(expected3.release());
slice2.release();
slice1.release();
assertEquals(slice2.refCnt(), dup2.refCnt());
assertEquals(dup2.refCnt(), slice1.refCnt());
// The handler is now done with the original slice
assertTrue(dup1.release());
// Reference counting may be shared, or may be independently tracked, but at this point all buffers should
// be deallocated and have a reference count of 0.
assertEquals(0, buf.refCnt());
assertEquals(0, slice1.refCnt());
assertEquals(0, slice2.refCnt());
assertEquals(0, dup1.refCnt());
assertEquals(0, dup2.refCnt());
}
@Test
public void testRetainedSliceContents() {
testSliceContents(true);
}
@Test
public void testMultipleLevelRetainedSlice1() {
testMultipleLevelRetainedSliceWithNonRetained(true, true);
}
@Test
public void testMultipleLevelRetainedSlice2() {
testMultipleLevelRetainedSliceWithNonRetained(true, false);
}
@Test
public void testMultipleLevelRetainedSlice3() {
testMultipleLevelRetainedSliceWithNonRetained(false, true);
}
@Test
public void testMultipleLevelRetainedSlice4() {
testMultipleLevelRetainedSliceWithNonRetained(false, false);
}
@Test
public void testRetainedSliceReleaseOriginal1() {
testSliceReleaseOriginal(true, true);
}
@Test
public void testRetainedSliceReleaseOriginal2() {
testSliceReleaseOriginal(true, false);
}
@Test
public void testRetainedSliceReleaseOriginal3() {
testSliceReleaseOriginal(false, true);
}
@Test
public void testRetainedSliceReleaseOriginal4() {
testSliceReleaseOriginal(false, false);
}
@Test
public void testRetainedDuplicateReleaseOriginal1() {
testDuplicateReleaseOriginal(true, true);
}
@Test
public void testRetainedDuplicateReleaseOriginal2() {
testDuplicateReleaseOriginal(true, false);
}
@Test
public void testRetainedDuplicateReleaseOriginal3() {
testDuplicateReleaseOriginal(false, true);
}
@Test
public void testRetainedDuplicateReleaseOriginal4() {
testDuplicateReleaseOriginal(false, false);
}
@Test
public void testMultipleRetainedSliceReleaseOriginal1() {
testMultipleRetainedSliceReleaseOriginal(true, true);
}
@Test
public void testMultipleRetainedSliceReleaseOriginal2() {
testMultipleRetainedSliceReleaseOriginal(true, false);
}
@Test
public void testMultipleRetainedSliceReleaseOriginal3() {
testMultipleRetainedSliceReleaseOriginal(false, true);
}
@Test
public void testMultipleRetainedSliceReleaseOriginal4() {
testMultipleRetainedSliceReleaseOriginal(false, false);
}
@Test
public void testMultipleRetainedDuplicateReleaseOriginal1() {
testMultipleRetainedDuplicateReleaseOriginal(true, true);
}
@Test
public void testMultipleRetainedDuplicateReleaseOriginal2() {
testMultipleRetainedDuplicateReleaseOriginal(true, false);
}
@Test
public void testMultipleRetainedDuplicateReleaseOriginal3() {
testMultipleRetainedDuplicateReleaseOriginal(false, true);
}
@Test
public void testMultipleRetainedDuplicateReleaseOriginal4() {
testMultipleRetainedDuplicateReleaseOriginal(false, false);
}
@Test
public void testSliceContents() {
testSliceContents(false);
}
@Test
public void testRetainedDuplicateContents() {
testDuplicateContents(true);
}
@Test
public void testDuplicateContents() {
testDuplicateContents(false);
}
@Test
public void testDuplicateCapacityChange() {
testDuplicateCapacityChange(false);
}
@Test
public void testRetainedDuplicateCapacityChange() {
testDuplicateCapacityChange(true);
}
@Test(expected = UnsupportedOperationException.class)
public void testSliceCapacityChange() {
testSliceCapacityChange(false);
}
@Test(expected = UnsupportedOperationException.class)
public void testRetainedSliceCapacityChange() {
testSliceCapacityChange(true);
}
@Test
public void testRetainedSliceUnreleasable1() {
testRetainedSliceUnreleasable(true, true);
}
@Test
public void testRetainedSliceUnreleasable2() {
testRetainedSliceUnreleasable(true, false);
}
@Test
public void testRetainedSliceUnreleasable3() {
testRetainedSliceUnreleasable(false, true);
}
@Test
public void testRetainedSliceUnreleasable4() {
testRetainedSliceUnreleasable(false, false);
}
@Test
public void testReadRetainedSliceUnreleasable1() {
testReadRetainedSliceUnreleasable(true, true);
}
@Test
public void testReadRetainedSliceUnreleasable2() {
testReadRetainedSliceUnreleasable(true, false);
}
@Test
public void testReadRetainedSliceUnreleasable3() {
testReadRetainedSliceUnreleasable(false, true);
}
@Test
public void testReadRetainedSliceUnreleasable4() {
testReadRetainedSliceUnreleasable(false, false);
}
@Test
public void testRetainedDuplicateUnreleasable1() {
testRetainedDuplicateUnreleasable(true, true);
}
@Test
public void testRetainedDuplicateUnreleasable2() {
testRetainedDuplicateUnreleasable(true, false);
}
@Test
public void testRetainedDuplicateUnreleasable3() {
testRetainedDuplicateUnreleasable(false, true);
}
@Test
public void testRetainedDuplicateUnreleasable4() {
testRetainedDuplicateUnreleasable(false, false);
}
private void testRetainedSliceUnreleasable(boolean initRetainedSlice, boolean finalRetainedSlice) {
ByteBuf buf = newBuffer(8);
ByteBuf buf1 = initRetainedSlice ? buf.retainedSlice() : buf.slice().retain();
ByteBuf buf2 = unreleasableBuffer(buf1);
ByteBuf buf3 = finalRetainedSlice ? buf2.retainedSlice() : buf2.slice().retain();
assertFalse(buf3.release());
assertFalse(buf2.release());
buf1.release();
assertTrue(buf.release());
assertEquals(0, buf1.refCnt());
assertEquals(0, buf.refCnt());
}
private void testReadRetainedSliceUnreleasable(boolean initRetainedSlice, boolean finalRetainedSlice) {
ByteBuf buf = newBuffer(8);
ByteBuf buf1 = initRetainedSlice ? buf.retainedSlice() : buf.slice().retain();
ByteBuf buf2 = unreleasableBuffer(buf1);
ByteBuf buf3 = finalRetainedSlice ? buf2.readRetainedSlice(buf2.readableBytes())
: buf2.readSlice(buf2.readableBytes()).retain();
assertFalse(buf3.release());
assertFalse(buf2.release());
buf1.release();
assertTrue(buf.release());
assertEquals(0, buf1.refCnt());
assertEquals(0, buf.refCnt());
}
private void testRetainedDuplicateUnreleasable(boolean initRetainedDuplicate, boolean finalRetainedDuplicate) {
ByteBuf buf = newBuffer(8);
ByteBuf buf1 = initRetainedDuplicate ? buf.retainedDuplicate() : buf.duplicate().retain();
ByteBuf buf2 = unreleasableBuffer(buf1);
ByteBuf buf3 = finalRetainedDuplicate ? buf2.retainedDuplicate() : buf2.duplicate().retain();
assertFalse(buf3.release());
assertFalse(buf2.release());
buf1.release();
assertTrue(buf.release());
assertEquals(0, buf1.refCnt());
assertEquals(0, buf.refCnt());
}
private void testDuplicateCapacityChange(boolean retainedDuplicate) {
ByteBuf buf = newBuffer(8);
ByteBuf dup = retainedDuplicate ? buf.retainedDuplicate() : buf.duplicate();
try {
dup.capacity(10);
assertEquals(buf.capacity(), dup.capacity());
dup.capacity(5);
assertEquals(buf.capacity(), dup.capacity());
} finally {
if (retainedDuplicate) {
dup.release();
}
buf.release();
}
}
private void testSliceCapacityChange(boolean retainedSlice) {
ByteBuf buf = newBuffer(8);
ByteBuf slice = retainedSlice ? buf.retainedSlice(buf.readerIndex() + 1, 3)
: buf.slice(buf.readerIndex() + 1, 3);
try {
slice.capacity(10);
} finally {
if (retainedSlice) {
slice.release();
}
buf.release();
}
}
private void testSliceOutOfBounds(boolean initRetainedSlice, boolean finalRetainedSlice, boolean indexOutOfBounds) {
ByteBuf buf = newBuffer(8);
ByteBuf slice = initRetainedSlice ? buf.retainedSlice(buf.readerIndex() + 1, 2)
: buf.slice(buf.readerIndex() + 1, 2);
try {
assertEquals(2, slice.capacity());
assertEquals(2, slice.maxCapacity());
final int index = indexOutOfBounds ? 3 : 0;
final int length = indexOutOfBounds ? 0 : 3;
if (finalRetainedSlice) {
// This is expected to fail ... so no need to release.
slice.retainedSlice(index, length);
} else {
slice.slice(index, length);
}
} finally {
if (initRetainedSlice) {
slice.release();
}
buf.release();
}
}
private void testSliceContents(boolean retainedSlice) {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected = newBuffer(3).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected.writeBytes(new byte[] {4, 5, 6});
ByteBuf slice = retainedSlice ? buf.retainedSlice(buf.readerIndex() + 3, 3)
: buf.slice(buf.readerIndex() + 3, 3);
try {
assertEquals(0, slice.compareTo(expected));
assertEquals(0, slice.compareTo(slice.duplicate()));
ByteBuf b = slice.retainedDuplicate();
assertEquals(0, slice.compareTo(b));
b.release();
assertEquals(0, slice.compareTo(slice.slice(0, slice.capacity())));
} finally {
if (retainedSlice) {
slice.release();
}
buf.release();
expected.release();
}
}
private void testSliceReleaseOriginal(boolean retainedSlice1, boolean retainedSlice2) {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected1 = newBuffer(3).resetWriterIndex();
ByteBuf expected2 = newBuffer(2).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected1.writeBytes(new byte[] {6, 7, 8});
expected2.writeBytes(new byte[] {7, 8});
ByteBuf slice1 = retainedSlice1 ? buf.retainedSlice(buf.readerIndex() + 5, 3)
: buf.slice(buf.readerIndex() + 5, 3).retain();
assertEquals(0, slice1.compareTo(expected1));
// Simulate a handler that releases the original buffer, and propagates a slice.
buf.release();
ByteBuf slice2 = retainedSlice2 ? slice1.retainedSlice(slice1.readerIndex() + 1, 2)
: slice1.slice(slice1.readerIndex() + 1, 2).retain();
assertEquals(0, slice2.compareTo(expected2));
// Cleanup the expected buffers used for testing.
assertTrue(expected1.release());
assertTrue(expected2.release());
// The handler created a slice of the slice and is now done with it.
slice2.release();
// The handler is now done with the original slice
assertTrue(slice1.release());
// Reference counting may be shared, or may be independently tracked, but at this point all buffers should
// be deallocated and have a reference count of 0.
assertEquals(0, buf.refCnt());
assertEquals(0, slice1.refCnt());
assertEquals(0, slice2.refCnt());
}
private void testMultipleLevelRetainedSliceWithNonRetained(boolean doSlice1, boolean doSlice2) {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected1 = newBuffer(6).resetWriterIndex();
ByteBuf expected2 = newBuffer(4).resetWriterIndex();
ByteBuf expected3 = newBuffer(2).resetWriterIndex();
ByteBuf expected4SliceSlice = newBuffer(1).resetWriterIndex();
ByteBuf expected4DupSlice = newBuffer(1).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected1.writeBytes(new byte[] {2, 3, 4, 5, 6, 7});
expected2.writeBytes(new byte[] {3, 4, 5, 6});
expected3.writeBytes(new byte[] {4, 5});
expected4SliceSlice.writeBytes(new byte[] {5});
expected4DupSlice.writeBytes(new byte[] {4});
ByteBuf slice1 = buf.retainedSlice(buf.readerIndex() + 1, 6);
assertEquals(0, slice1.compareTo(expected1));
// Simulate a handler that releases the original buffer, and propagates a slice.
buf.release();
ByteBuf slice2 = slice1.retainedSlice(slice1.readerIndex() + 1, 4);
assertEquals(0, slice2.compareTo(expected2));
assertEquals(0, slice2.compareTo(slice2.duplicate()));
assertEquals(0, slice2.compareTo(slice2.slice()));
ByteBuf tmpBuf = slice2.retainedDuplicate();
assertEquals(0, slice2.compareTo(tmpBuf));
tmpBuf.release();
tmpBuf = slice2.retainedSlice();
assertEquals(0, slice2.compareTo(tmpBuf));
tmpBuf.release();
ByteBuf slice3 = doSlice1 ? slice2.slice(slice2.readerIndex() + 1, 2) : slice2.duplicate();
if (doSlice1) {
assertEquals(0, slice3.compareTo(expected3));
} else {
assertEquals(0, slice3.compareTo(expected2));
}
ByteBuf slice4 = doSlice2 ? slice3.slice(slice3.readerIndex() + 1, 1) : slice3.duplicate();
if (doSlice1 && doSlice2) {
assertEquals(0, slice4.compareTo(expected4SliceSlice));
} else if (doSlice2) {
assertEquals(0, slice4.compareTo(expected4DupSlice));
} else {
assertEquals(0, slice3.compareTo(slice4));
}
// Cleanup the expected buffers used for testing.
assertTrue(expected1.release());
assertTrue(expected2.release());
assertTrue(expected3.release());
assertTrue(expected4SliceSlice.release());
assertTrue(expected4DupSlice.release());
// Slice 4, 3, and 2 should effectively "share" a reference count.
slice4.release();
assertEquals(slice3.refCnt(), slice2.refCnt());
assertEquals(slice3.refCnt(), slice4.refCnt());
// Slice 1 should also release the original underlying buffer without throwing exceptions
assertTrue(slice1.release());
// Reference counting may be shared, or may be independently tracked, but at this point all buffers should
// be deallocated and have a reference count of 0.
assertEquals(0, buf.refCnt());
assertEquals(0, slice1.refCnt());
assertEquals(0, slice2.refCnt());
assertEquals(0, slice3.refCnt());
}
private void testDuplicateReleaseOriginal(boolean retainedDuplicate1, boolean retainedDuplicate2) {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected = newBuffer(8).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected.writeBytes(buf, buf.readerIndex(), buf.readableBytes());
ByteBuf dup1 = retainedDuplicate1 ? buf.retainedDuplicate()
: buf.duplicate().retain();
assertEquals(0, dup1.compareTo(expected));
// Simulate a handler that releases the original buffer, and propagates a slice.
buf.release();
ByteBuf dup2 = retainedDuplicate2 ? dup1.retainedDuplicate()
: dup1.duplicate().retain();
assertEquals(0, dup2.compareTo(expected));
// Cleanup the expected buffers used for testing.
assertTrue(expected.release());
// The handler created a slice of the slice and is now done with it.
dup2.release();
// The handler is now done with the original slice
assertTrue(dup1.release());
// Reference counting may be shared, or may be independently tracked, but at this point all buffers should
// be deallocated and have a reference count of 0.
assertEquals(0, buf.refCnt());
assertEquals(0, dup1.refCnt());
assertEquals(0, dup2.refCnt());
}
private void testMultipleRetainedSliceReleaseOriginal(boolean retainedSlice1, boolean retainedSlice2) {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected1 = newBuffer(3).resetWriterIndex();
ByteBuf expected2 = newBuffer(2).resetWriterIndex();
ByteBuf expected3 = newBuffer(2).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected1.writeBytes(new byte[] {6, 7, 8});
expected2.writeBytes(new byte[] {7, 8});
expected3.writeBytes(new byte[] {6, 7});
ByteBuf slice1 = retainedSlice1 ? buf.retainedSlice(buf.readerIndex() + 5, 3)
: buf.slice(buf.readerIndex() + 5, 3).retain();
assertEquals(0, slice1.compareTo(expected1));
// Simulate a handler that releases the original buffer, and propagates a slice.
buf.release();
ByteBuf slice2 = retainedSlice2 ? slice1.retainedSlice(slice1.readerIndex() + 1, 2)
: slice1.slice(slice1.readerIndex() + 1, 2).retain();
assertEquals(0, slice2.compareTo(expected2));
// The handler created a slice of the slice and is now done with it.
slice2.release();
ByteBuf slice3 = slice1.retainedSlice(slice1.readerIndex(), 2);
assertEquals(0, slice3.compareTo(expected3));
// The handler created another slice of the slice and is now done with it.
slice3.release();
// The handler is now done with the original slice
assertTrue(slice1.release());
// Cleanup the expected buffers used for testing.
assertTrue(expected1.release());
assertTrue(expected2.release());
assertTrue(expected3.release());
// Reference counting may be shared, or may be independently tracked, but at this point all buffers should
// be deallocated and have a reference count of 0.
assertEquals(0, buf.refCnt());
assertEquals(0, slice1.refCnt());
assertEquals(0, slice2.refCnt());
assertEquals(0, slice3.refCnt());
}
private void testMultipleRetainedDuplicateReleaseOriginal(boolean retainedDuplicate1, boolean retainedDuplicate2) {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected = newBuffer(8).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected.writeBytes(buf, buf.readerIndex(), buf.readableBytes());
ByteBuf dup1 = retainedDuplicate1 ? buf.retainedDuplicate()
: buf.duplicate().retain();
assertEquals(0, dup1.compareTo(expected));
// Simulate a handler that releases the original buffer, and propagates a slice.
buf.release();
ByteBuf dup2 = retainedDuplicate2 ? dup1.retainedDuplicate()
: dup1.duplicate().retain();
assertEquals(0, dup2.compareTo(expected));
assertEquals(0, dup2.compareTo(dup2.duplicate()));
assertEquals(0, dup2.compareTo(dup2.slice()));
ByteBuf tmpBuf = dup2.retainedDuplicate();
assertEquals(0, dup2.compareTo(tmpBuf));
tmpBuf.release();
tmpBuf = dup2.retainedSlice();
assertEquals(0, dup2.compareTo(tmpBuf));
tmpBuf.release();
// The handler created a slice of the slice and is now done with it.
dup2.release();
ByteBuf dup3 = dup1.retainedDuplicate();
assertEquals(0, dup3.compareTo(expected));
// The handler created another slice of the slice and is now done with it.
dup3.release();
// The handler is now done with the original slice
assertTrue(dup1.release());
// Cleanup the expected buffers used for testing.
assertTrue(expected.release());
// Reference counting may be shared, or may be independently tracked, but at this point all buffers should
// be deallocated and have a reference count of 0.
assertEquals(0, buf.refCnt());
assertEquals(0, dup1.refCnt());
assertEquals(0, dup2.refCnt());
assertEquals(0, dup3.refCnt());
}
private void testDuplicateContents(boolean retainedDuplicate) {
ByteBuf buf = newBuffer(8).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
ByteBuf dup = retainedDuplicate ? buf.retainedDuplicate() : buf.duplicate();
try {
assertEquals(0, dup.compareTo(buf));
assertEquals(0, dup.compareTo(dup.duplicate()));
ByteBuf b = dup.retainedDuplicate();
assertEquals(0, dup.compareTo(b));
b.release();
assertEquals(0, dup.compareTo(dup.slice(dup.readerIndex(), dup.readableBytes())));
} finally {
if (retainedDuplicate) {
dup.release();
}
buf.release();
}
}
@Test
public void testDuplicateRelease() {
ByteBuf buf = newBuffer(8);
assertEquals(1, buf.refCnt());
assertTrue(buf.duplicate().release());
assertEquals(0, buf.refCnt());
}
// Test-case trying to reproduce:
// https://github.com/netty/netty/issues/2843
@Test
public void testRefCnt() throws Exception {
testRefCnt0(false);
}
// Test-case trying to reproduce:
// https://github.com/netty/netty/issues/2843
@Test
public void testRefCnt2() throws Exception {
testRefCnt0(true);
}
@Test
public void testEmptyNioBuffers() throws Exception {
ByteBuf buffer = newBuffer(8);
buffer.clear();
assertFalse(buffer.isReadable());
ByteBuffer[] nioBuffers = buffer.nioBuffers();
assertEquals(1, nioBuffers.length);
assertFalse(nioBuffers[0].hasRemaining());
buffer.release();
}
@Test
public void testGetReadOnlyDirectDst() {
testGetReadOnlyDst(true);
}
@Test
public void testGetReadOnlyHeapDst() {
testGetReadOnlyDst(false);
}
private void testGetReadOnlyDst(boolean direct) {
byte[] bytes = { 'a', 'b', 'c', 'd' };
ByteBuf buffer = newBuffer(bytes.length);
buffer.writeBytes(bytes);
ByteBuffer dst = direct ? ByteBuffer.allocateDirect(bytes.length) : ByteBuffer.allocate(bytes.length);
ByteBuffer readOnlyDst = dst.asReadOnlyBuffer();
try {
buffer.getBytes(0, readOnlyDst);
fail();
} catch (ReadOnlyBufferException e) {
// expected
}
assertEquals(0, readOnlyDst.position());
buffer.release();
}
@Test
public void testReadBytesAndWriteBytesWithFileChannel() throws IOException {
File file = PlatformDependent.createTempFile("file-channel", ".tmp", null);
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel channel = randomAccessFile.getChannel();
// channelPosition should never be changed
long channelPosition = channel.position();
byte[] bytes = {'a', 'b', 'c', 'd'};
int len = bytes.length;
ByteBuf buffer = newBuffer(len);
buffer.resetReaderIndex();
buffer.resetWriterIndex();
buffer.writeBytes(bytes);
int oldReaderIndex = buffer.readerIndex();
assertEquals(len, buffer.readBytes(channel, 10, len));
assertEquals(oldReaderIndex + len, buffer.readerIndex());
assertEquals(channelPosition, channel.position());
ByteBuf buffer2 = newBuffer(len);
buffer2.resetReaderIndex();
buffer2.resetWriterIndex();
int oldWriterIndex = buffer2.writerIndex();
assertEquals(len, buffer2.writeBytes(channel, 10, len));
assertEquals(channelPosition, channel.position());
assertEquals(oldWriterIndex + len, buffer2.writerIndex());
assertEquals('a', buffer2.getByte(0));
assertEquals('b', buffer2.getByte(1));
assertEquals('c', buffer2.getByte(2));
assertEquals('d', buffer2.getByte(3));
buffer.release();
buffer2.release();
} finally {
if (randomAccessFile != null) {
randomAccessFile.close();
}
file.delete();
}
}
@Test
public void testGetBytesAndSetBytesWithFileChannel() throws IOException {
File file = PlatformDependent.createTempFile("file-channel", ".tmp", null);
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel channel = randomAccessFile.getChannel();
// channelPosition should never be changed
long channelPosition = channel.position();
byte[] bytes = {'a', 'b', 'c', 'd'};
int len = bytes.length;
ByteBuf buffer = newBuffer(len);
buffer.resetReaderIndex();
buffer.resetWriterIndex();
buffer.writeBytes(bytes);
int oldReaderIndex = buffer.readerIndex();
assertEquals(len, buffer.getBytes(oldReaderIndex, channel, 10, len));
assertEquals(oldReaderIndex, buffer.readerIndex());
assertEquals(channelPosition, channel.position());
ByteBuf buffer2 = newBuffer(len);
buffer2.resetReaderIndex();
buffer2.resetWriterIndex();
int oldWriterIndex = buffer2.writerIndex();
assertEquals(buffer2.setBytes(oldWriterIndex, channel, 10, len), len);
assertEquals(channelPosition, channel.position());
assertEquals(oldWriterIndex, buffer2.writerIndex());
assertEquals('a', buffer2.getByte(oldWriterIndex));
assertEquals('b', buffer2.getByte(oldWriterIndex + 1));
assertEquals('c', buffer2.getByte(oldWriterIndex + 2));
assertEquals('d', buffer2.getByte(oldWriterIndex + 3));
buffer.release();
buffer2.release();
} finally {
if (randomAccessFile != null) {
randomAccessFile.close();
}
file.delete();
}
}
@Test
public void testReadBytes() {
ByteBuf buffer = newBuffer(8);
byte[] bytes = new byte[8];
buffer.writeBytes(bytes);
ByteBuf buffer2 = buffer.readBytes(4);
assertSame(buffer.alloc(), buffer2.alloc());
assertEquals(4, buffer.readerIndex());
assertTrue(buffer.release());
assertEquals(0, buffer.refCnt());
assertTrue(buffer2.release());
assertEquals(0, buffer2.refCnt());
}
@Test
public void testForEachByteDesc2() {
byte[] expected = {1, 2, 3, 4};
ByteBuf buf = newBuffer(expected.length);
try {
buf.writeBytes(expected);
final byte[] bytes = new byte[expected.length];
int i = buf.forEachByteDesc(new ByteProcessor() {
private int index = bytes.length - 1;
@Override
public boolean process(byte value) throws Exception {
bytes[index--] = value;
return true;
}
});
assertEquals(-1, i);
assertArrayEquals(expected, bytes);
} finally {
buf.release();
}
}
@Test
public void testForEachByte2() {
byte[] expected = {1, 2, 3, 4};
ByteBuf buf = newBuffer(expected.length);
try {
buf.writeBytes(expected);
final byte[] bytes = new byte[expected.length];
int i = buf.forEachByte(new ByteProcessor() {
private int index;
@Override
public boolean process(byte value) throws Exception {
bytes[index++] = value;
return true;
}
});
assertEquals(-1, i);
assertArrayEquals(expected, bytes);
} finally {
buf.release();
}
}
@Test(expected = IndexOutOfBoundsException.class)
public void testGetBytesByteBuffer() {
byte[] bytes = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
// Ensure destination buffer is bigger then what is in the ByteBuf.
ByteBuffer nioBuffer = ByteBuffer.allocate(bytes.length + 1);
ByteBuf buffer = newBuffer(bytes.length);
try {
buffer.writeBytes(bytes);
buffer.getBytes(buffer.readerIndex(), nioBuffer);
} finally {
buffer.release();
}
}
private void testRefCnt0(final boolean parameter) throws Exception {
for (int i = 0; i < 10; i++) {
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch innerLatch = new CountDownLatch(1);
final ByteBuf buffer = newBuffer(4);
assertEquals(1, buffer.refCnt());
final AtomicInteger cnt = new AtomicInteger(Integer.MAX_VALUE);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
boolean released;
if (parameter) {
released = buffer.release(buffer.refCnt());
} else {
released = buffer.release();
}
assertTrue(released);
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
cnt.set(buffer.refCnt());
latch.countDown();
}
});
t2.start();
try {
// Keep Thread alive a bit so the ThreadLocal caches are not freed
innerLatch.await();
} catch (InterruptedException ignore) {
// ignore
}
}
});
t1.start();
latch.await();
assertEquals(0, cnt.get());
innerLatch.countDown();
}
}
static final class TestGatheringByteChannel implements GatheringByteChannel {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
private final WritableByteChannel channel = Channels.newChannel(out);
private final int limit;
TestGatheringByteChannel(int limit) {
this.limit = limit;
}
TestGatheringByteChannel() {
this(Integer.MAX_VALUE);
}
@Override
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {
long written = 0;
for (; offset < length; offset++) {
written += write(srcs[offset]);
if (written >= limit) {
break;
}
}
return written;
}
@Override
public long write(ByteBuffer[] srcs) throws IOException {
return write(srcs, 0, srcs.length);
}
@Override
public int write(ByteBuffer src) throws IOException {
int oldLimit = src.limit();
if (limit < src.remaining()) {
src.limit(src.position() + limit);
}
int w = channel.write(src);
src.limit(oldLimit);
return w;
}
@Override
public boolean isOpen() {
return channel.isOpen();
}
@Override
public void close() throws IOException {
channel.close();
}
public byte[] writtenBytes() {
return out.toByteArray();
}
}
private static final class DevNullGatheringByteChannel implements GatheringByteChannel {
@Override
public long write(ByteBuffer[] srcs, int offset, int length) {
throw new UnsupportedOperationException();
}
@Override
public long write(ByteBuffer[] srcs) {
throw new UnsupportedOperationException();
}
@Override
public int write(ByteBuffer src) {
throw new UnsupportedOperationException();
}
@Override
public boolean isOpen() {
return false;
}
@Override
public void close() {
throw new UnsupportedOperationException();
}
}
private static final class TestScatteringByteChannel implements ScatteringByteChannel {
@Override
public long read(ByteBuffer[] dsts, int offset, int length) {
throw new UnsupportedOperationException();
}
@Override
public long read(ByteBuffer[] dsts) {
throw new UnsupportedOperationException();
}
@Override
public int read(ByteBuffer dst) {
throw new UnsupportedOperationException();
}
@Override
public boolean isOpen() {
return false;
}
@Override
public void close() {
throw new UnsupportedOperationException();
}
}
private static final class TestByteProcessor implements ByteProcessor {
@Override
public boolean process(byte value) throws Exception {
return true;
}
}
@Test(expected = IllegalArgumentException.class)
public void testCapacityEnforceMaxCapacity() {
ByteBuf buffer = newBuffer(3, 13);
assertEquals(13, buffer.maxCapacity());
assertEquals(3, buffer.capacity());
try {
buffer.capacity(14);
} finally {
buffer.release();
}
}
@Test(expected = IllegalArgumentException.class)
public void testCapacityNegative() {
ByteBuf buffer = newBuffer(3, 13);
assertEquals(13, buffer.maxCapacity());
assertEquals(3, buffer.capacity());
try {
buffer.capacity(-1);
} finally {
buffer.release();
}
}
@Test
public void testCapacityDecrease() {
ByteBuf buffer = newBuffer(3, 13);
assertEquals(13, buffer.maxCapacity());
assertEquals(3, buffer.capacity());
try {
buffer.capacity(2);
assertEquals(2, buffer.capacity());
assertEquals(13, buffer.maxCapacity());
} finally {
buffer.release();
}
}
@Test
public void testCapacityIncrease() {
ByteBuf buffer = newBuffer(3, 13);
assertEquals(13, buffer.maxCapacity());
assertEquals(3, buffer.capacity());
try {
buffer.capacity(4);
assertEquals(4, buffer.capacity());
assertEquals(13, buffer.maxCapacity());
} finally {
buffer.release();
}
}
@Test(expected = IndexOutOfBoundsException.class)
public void testReaderIndexLargerThanWriterIndex() {
String content1 = "hello";
String content2 = "world";
int length = content1.length() + content2.length();
ByteBuf buffer = newBuffer(length);
buffer.setIndex(0, 0);
buffer.writeCharSequence(content1, CharsetUtil.US_ASCII);
buffer.markWriterIndex();
buffer.skipBytes(content1.length());
buffer.writeCharSequence(content2, CharsetUtil.US_ASCII);
buffer.skipBytes(content2.length());
assertTrue(buffer.readerIndex() <= buffer.writerIndex());
try {
buffer.resetWriterIndex();
} finally {
buffer.release();
}
}
@Test
public void testMaxFastWritableBytes() {
ByteBuf buffer = newBuffer(150, 500).writerIndex(100);
assertEquals(50, buffer.writableBytes());
assertEquals(150, buffer.capacity());
assertEquals(500, buffer.maxCapacity());
assertEquals(400, buffer.maxWritableBytes());
// Default implementation has fast writable == writable
assertEquals(50, buffer.maxFastWritableBytes());
buffer.release();
}
@Test
public void testEnsureWritableIntegerOverflow() {
ByteBuf buffer = newBuffer(CAPACITY);
buffer.writerIndex(buffer.readerIndex());
buffer.writeByte(1);
try {
buffer.ensureWritable(Integer.MAX_VALUE);
fail();
} catch (IndexOutOfBoundsException e) {
// expected
} finally {
buffer.release();
}
}
@Test
public void testEndiannessIndexOf() {
buffer.clear();
final int v = 0x02030201;
buffer.writeIntLE(v);
buffer.writeByte(0x01);
assertEquals(-1, buffer.indexOf(1, 4, (byte) 1));
assertEquals(-1, buffer.indexOf(4, 1, (byte) 1));
assertEquals(1, buffer.indexOf(1, 4, (byte) 2));
assertEquals(3, buffer.indexOf(4, 1, (byte) 2));
}
@Test
public void explicitLittleEndianReadMethodsMustAlwaysUseLittleEndianByteOrder() {
buffer.clear();
buffer.writeBytes(new byte[] {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08});
assertEquals(0x0201, buffer.readShortLE());
buffer.readerIndex(0);
assertEquals(0x0201, buffer.readUnsignedShortLE());
buffer.readerIndex(0);
assertEquals(0x030201, buffer.readMediumLE());
buffer.readerIndex(0);
assertEquals(0x030201, buffer.readUnsignedMediumLE());
buffer.readerIndex(0);
assertEquals(0x04030201, buffer.readIntLE());
buffer.readerIndex(0);
assertEquals(0x04030201, buffer.readUnsignedIntLE());
buffer.readerIndex(0);
assertEquals(0x04030201, Float.floatToRawIntBits(buffer.readFloatLE()));
buffer.readerIndex(0);
assertEquals(0x0807060504030201L, buffer.readLongLE());
buffer.readerIndex(0);
assertEquals(0x0807060504030201L, Double.doubleToRawLongBits(buffer.readDoubleLE()));
buffer.readerIndex(0);
}
@Test
public void explicitLittleEndianWriteMethodsMustAlwaysUseLittleEndianByteOrder() {
buffer.clear();
buffer.writeShortLE(0x0102);
assertEquals(0x0102, buffer.readShortLE());
buffer.clear();
buffer.writeMediumLE(0x010203);
assertEquals(0x010203, buffer.readMediumLE());
buffer.clear();
buffer.writeIntLE(0x01020304);
assertEquals(0x01020304, buffer.readIntLE());
buffer.clear();
buffer.writeFloatLE(Float.intBitsToFloat(0x01020304));
assertEquals(0x01020304, Float.floatToRawIntBits(buffer.readFloatLE()));
buffer.clear();
buffer.writeLongLE(0x0102030405060708L);
assertEquals(0x0102030405060708L, buffer.readLongLE());
buffer.clear();
buffer.writeDoubleLE(Double.longBitsToDouble(0x0102030405060708L));
assertEquals(0x0102030405060708L, Double.doubleToRawLongBits(buffer.readDoubleLE()));
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_0 |
crossvul-java_data_bad_1927_15 | /*
* Copyright 2019 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 io.netty.channel;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class DefaultFileRegionTest {
private static final byte[] data = new byte[1048576 * 10];
static {
PlatformDependent.threadLocalRandom().nextBytes(data);
}
private static File newFile() throws IOException {
File file = File.createTempFile("netty-", ".tmp");
file.deleteOnExit();
final FileOutputStream out = new FileOutputStream(file);
out.write(data);
out.close();
return file;
}
@Test
public void testCreateFromFile() throws IOException {
File file = newFile();
try {
testFileRegion(new DefaultFileRegion(file, 0, data.length));
} finally {
file.delete();
}
}
@Test
public void testCreateFromFileChannel() throws IOException {
File file = newFile();
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
try {
testFileRegion(new DefaultFileRegion(randomAccessFile.getChannel(), 0, data.length));
} finally {
randomAccessFile.close();
file.delete();
}
}
private static void testFileRegion(FileRegion region) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
WritableByteChannel channel = Channels.newChannel(outputStream);
try {
assertEquals(data.length, region.count());
assertEquals(0, region.transferred());
assertEquals(data.length, region.transferTo(channel, 0));
assertEquals(data.length, region.count());
assertEquals(data.length, region.transferred());
assertArrayEquals(data, outputStream.toByteArray());
} finally {
channel.close();
}
}
@Test
public void testTruncated() throws IOException {
File file = newFile();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
WritableByteChannel channel = Channels.newChannel(outputStream);
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
try {
FileRegion region = new DefaultFileRegion(randomAccessFile.getChannel(), 0, data.length);
randomAccessFile.getChannel().truncate(data.length - 1024);
assertEquals(data.length, region.count());
assertEquals(0, region.transferred());
assertEquals(data.length - 1024, region.transferTo(channel, 0));
assertEquals(data.length, region.count());
assertEquals(data.length - 1024, region.transferred());
try {
region.transferTo(channel, data.length - 1024);
fail();
} catch (IOException expected) {
// expected
}
} finally {
channel.close();
randomAccessFile.close();
file.delete();
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_15 |
crossvul-java_data_good_1927_10 | /*
* Copyright 2012 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 io.netty.handler.stream;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.PlatformDependent;
import org.junit.Assert;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.Channels;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static java.util.concurrent.TimeUnit.*;
import static org.junit.Assert.*;
public class ChunkedWriteHandlerTest {
private static final byte[] BYTES = new byte[1024 * 64];
private static final File TMP;
static {
for (int i = 0; i < BYTES.length; i++) {
BYTES[i] = (byte) i;
}
FileOutputStream out = null;
try {
TMP = PlatformDependent.createTempFile("netty-chunk-", ".tmp", null);
TMP.deleteOnExit();
out = new FileOutputStream(TMP);
out.write(BYTES);
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignore
}
}
}
}
// See #310
@Test
public void testChunkedStream() {
check(new ChunkedStream(new ByteArrayInputStream(BYTES)));
check(new ChunkedStream(new ByteArrayInputStream(BYTES)),
new ChunkedStream(new ByteArrayInputStream(BYTES)),
new ChunkedStream(new ByteArrayInputStream(BYTES)));
}
@Test
public void testChunkedNioStream() {
check(new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))));
check(new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))),
new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))),
new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))));
}
@Test
public void testChunkedFile() throws IOException {
check(new ChunkedFile(TMP));
check(new ChunkedFile(TMP), new ChunkedFile(TMP), new ChunkedFile(TMP));
}
@Test
public void testChunkedNioFile() throws IOException {
check(new ChunkedNioFile(TMP));
check(new ChunkedNioFile(TMP), new ChunkedNioFile(TMP), new ChunkedNioFile(TMP));
}
@Test
public void testChunkedNioFileLeftPositionUnchanged() throws IOException {
FileChannel in = null;
final long expectedPosition = 10;
try {
in = new RandomAccessFile(TMP, "r").getChannel();
in.position(expectedPosition);
check(new ChunkedNioFile(in) {
@Override
public void close() throws Exception {
//no op
}
});
Assert.assertTrue(in.isOpen());
Assert.assertEquals(expectedPosition, in.position());
} finally {
if (in != null) {
in.close();
}
}
}
@Test(expected = ClosedChannelException.class)
public void testChunkedNioFileFailOnClosedFileChannel() throws IOException {
final FileChannel in = new RandomAccessFile(TMP, "r").getChannel();
in.close();
check(new ChunkedNioFile(in) {
@Override
public void close() throws Exception {
//no op
}
});
Assert.fail();
}
@Test
public void testUnchunkedData() throws IOException {
check(Unpooled.wrappedBuffer(BYTES));
check(Unpooled.wrappedBuffer(BYTES), Unpooled.wrappedBuffer(BYTES), Unpooled.wrappedBuffer(BYTES));
}
// Test case which shows that there is not a bug like stated here:
// https://stackoverflow.com/a/10426305
@Test
public void testListenerNotifiedWhenIsEnd() {
ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.ISO_8859_1);
ChunkedInput<ByteBuf> input = new ChunkedInput<ByteBuf>() {
private boolean done;
private final ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.ISO_8859_1);
@Override
public boolean isEndOfInput() throws Exception {
return done;
}
@Override
public void close() throws Exception {
buffer.release();
}
@Deprecated
@Override
public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
return readChunk(ctx.alloc());
}
@Override
public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {
if (done) {
return null;
}
done = true;
return buffer.retainedDuplicate();
}
@Override
public long length() {
return -1;
}
@Override
public long progress() {
return 1;
}
};
final AtomicBoolean listenerNotified = new AtomicBoolean(false);
final ChannelFutureListener listener = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
listenerNotified.set(true);
}
};
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
ch.writeAndFlush(input).addListener(listener).syncUninterruptibly();
assertTrue(ch.finish());
// the listener should have been notified
assertTrue(listenerNotified.get());
ByteBuf buffer2 = ch.readOutbound();
assertEquals(buffer, buffer2);
assertNull(ch.readOutbound());
buffer.release();
buffer2.release();
}
@Test
public void testChunkedMessageInput() {
ChunkedInput<Object> input = new ChunkedInput<Object>() {
private boolean done;
@Override
public boolean isEndOfInput() throws Exception {
return done;
}
@Override
public void close() throws Exception {
// NOOP
}
@Deprecated
@Override
public Object readChunk(ChannelHandlerContext ctx) throws Exception {
return readChunk(ctx.alloc());
}
@Override
public Object readChunk(ByteBufAllocator ctx) throws Exception {
if (done) {
return false;
}
done = true;
return 0;
}
@Override
public long length() {
return -1;
}
@Override
public long progress() {
return 1;
}
};
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
ch.writeAndFlush(input).syncUninterruptibly();
assertTrue(ch.finish());
assertEquals(0, ch.readOutbound());
assertNull(ch.readOutbound());
}
@Test
public void testWriteFailureChunkedStream() throws IOException {
checkFirstFailed(new ChunkedStream(new ByteArrayInputStream(BYTES)));
}
@Test
public void testWriteFailureChunkedNioStream() throws IOException {
checkFirstFailed(new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))));
}
@Test
public void testWriteFailureChunkedFile() throws IOException {
checkFirstFailed(new ChunkedFile(TMP));
}
@Test
public void testWriteFailureChunkedNioFile() throws IOException {
checkFirstFailed(new ChunkedNioFile(TMP));
}
@Test
public void testWriteFailureUnchunkedData() throws IOException {
checkFirstFailed(Unpooled.wrappedBuffer(BYTES));
}
@Test
public void testSkipAfterFailedChunkedStream() throws IOException {
checkSkipFailed(new ChunkedStream(new ByteArrayInputStream(BYTES)),
new ChunkedStream(new ByteArrayInputStream(BYTES)));
}
@Test
public void testSkipAfterFailedChunkedNioStream() throws IOException {
checkSkipFailed(new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))),
new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))));
}
@Test
public void testSkipAfterFailedChunkedFile() throws IOException {
checkSkipFailed(new ChunkedFile(TMP), new ChunkedFile(TMP));
}
@Test
public void testSkipAfterFailedChunkedNioFile() throws IOException {
checkSkipFailed(new ChunkedNioFile(TMP), new ChunkedFile(TMP));
}
// See https://github.com/netty/netty/issues/8700.
@Test
public void testFailureWhenLastChunkFailed() throws IOException {
ChannelOutboundHandlerAdapter failLast = new ChannelOutboundHandlerAdapter() {
private int passedWrites;
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
if (++this.passedWrites < 4) {
ctx.write(msg, promise);
} else {
ReferenceCountUtil.release(msg);
promise.tryFailure(new RuntimeException());
}
}
};
EmbeddedChannel ch = new EmbeddedChannel(failLast, new ChunkedWriteHandler());
ChannelFuture r = ch.writeAndFlush(new ChunkedFile(TMP, 1024 * 16)); // 4 chunks
assertTrue(ch.finish());
assertFalse(r.isSuccess());
assertTrue(r.cause() instanceof RuntimeException);
// 3 out of 4 chunks were already written
int read = 0;
for (;;) {
ByteBuf buffer = ch.readOutbound();
if (buffer == null) {
break;
}
read += buffer.readableBytes();
buffer.release();
}
assertEquals(1024 * 16 * 3, read);
}
@Test
public void testDiscardPendingWritesOnInactive() throws IOException {
final AtomicBoolean closeWasCalled = new AtomicBoolean(false);
ChunkedInput<ByteBuf> notifiableInput = new ChunkedInput<ByteBuf>() {
private boolean done;
private final ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.ISO_8859_1);
@Override
public boolean isEndOfInput() throws Exception {
return done;
}
@Override
public void close() throws Exception {
buffer.release();
closeWasCalled.set(true);
}
@Deprecated
@Override
public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
return readChunk(ctx.alloc());
}
@Override
public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {
if (done) {
return null;
}
done = true;
return buffer.retainedDuplicate();
}
@Override
public long length() {
return -1;
}
@Override
public long progress() {
return 1;
}
};
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
// Write 3 messages and close channel before flushing
ChannelFuture r1 = ch.write(new ChunkedFile(TMP));
ChannelFuture r2 = ch.write(new ChunkedNioFile(TMP));
ch.write(notifiableInput);
// Should be `false` as we do not expect any messages to be written
assertFalse(ch.finish());
assertFalse(r1.isSuccess());
assertFalse(r2.isSuccess());
assertTrue(closeWasCalled.get());
}
// See https://github.com/netty/netty/issues/8700.
@Test
public void testStopConsumingChunksWhenFailed() {
final ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.ISO_8859_1);
final AtomicInteger chunks = new AtomicInteger(0);
ChunkedInput<ByteBuf> nonClosableInput = new ChunkedInput<ByteBuf>() {
@Override
public boolean isEndOfInput() throws Exception {
return chunks.get() >= 5;
}
@Override
public void close() throws Exception {
// no-op
}
@Deprecated
@Override
public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
return readChunk(ctx.alloc());
}
@Override
public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {
chunks.incrementAndGet();
return buffer.retainedDuplicate();
}
@Override
public long length() {
return -1;
}
@Override
public long progress() {
return 1;
}
};
ChannelOutboundHandlerAdapter noOpWrites = new ChannelOutboundHandlerAdapter() {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
ReferenceCountUtil.release(msg);
promise.tryFailure(new RuntimeException());
}
};
EmbeddedChannel ch = new EmbeddedChannel(noOpWrites, new ChunkedWriteHandler());
ch.writeAndFlush(nonClosableInput).awaitUninterruptibly();
// Should be `false` as we do not expect any messages to be written
assertFalse(ch.finish());
buffer.release();
// We should expect only single chunked being read from the input.
// It's possible to get a race condition here between resolving a promise and
// allocating a new chunk, but should be fine when working with embedded channels.
assertEquals(1, chunks.get());
}
@Test
public void testCloseSuccessfulChunkedInput() {
int chunks = 10;
TestChunkedInput input = new TestChunkedInput(chunks);
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
assertTrue(ch.writeOutbound(input));
for (int i = 0; i < chunks; i++) {
ByteBuf buf = ch.readOutbound();
assertEquals(i, buf.readInt());
buf.release();
}
assertTrue(input.isClosed());
assertFalse(ch.finish());
}
@Test
public void testCloseFailedChunkedInput() {
Exception error = new Exception("Unable to produce a chunk");
ThrowingChunkedInput input = new ThrowingChunkedInput(error);
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
try {
ch.writeOutbound(input);
fail("Exception expected");
} catch (Exception e) {
assertEquals(error, e);
}
assertTrue(input.isClosed());
assertFalse(ch.finish());
}
@Test
public void testWriteListenerInvokedAfterSuccessfulChunkedInputClosed() throws Exception {
final TestChunkedInput input = new TestChunkedInput(2);
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
final AtomicBoolean inputClosedWhenListenerInvoked = new AtomicBoolean();
final CountDownLatch listenerInvoked = new CountDownLatch(1);
ChannelFuture writeFuture = ch.write(input);
writeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
inputClosedWhenListenerInvoked.set(input.isClosed());
listenerInvoked.countDown();
}
});
ch.flush();
assertTrue(listenerInvoked.await(10, SECONDS));
assertTrue(writeFuture.isSuccess());
assertTrue(inputClosedWhenListenerInvoked.get());
assertTrue(ch.finishAndReleaseAll());
}
@Test
public void testWriteListenerInvokedAfterFailedChunkedInputClosed() throws Exception {
final ThrowingChunkedInput input = new ThrowingChunkedInput(new RuntimeException());
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
final AtomicBoolean inputClosedWhenListenerInvoked = new AtomicBoolean();
final CountDownLatch listenerInvoked = new CountDownLatch(1);
ChannelFuture writeFuture = ch.write(input);
writeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
inputClosedWhenListenerInvoked.set(input.isClosed());
listenerInvoked.countDown();
}
});
ch.flush();
assertTrue(listenerInvoked.await(10, SECONDS));
assertFalse(writeFuture.isSuccess());
assertTrue(inputClosedWhenListenerInvoked.get());
assertFalse(ch.finish());
}
@Test
public void testWriteListenerInvokedAfterChannelClosedAndInputFullyConsumed() throws Exception {
// use empty input which has endOfInput = true
final TestChunkedInput input = new TestChunkedInput(0);
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
final AtomicBoolean inputClosedWhenListenerInvoked = new AtomicBoolean();
final CountDownLatch listenerInvoked = new CountDownLatch(1);
ChannelFuture writeFuture = ch.write(input);
writeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
inputClosedWhenListenerInvoked.set(input.isClosed());
listenerInvoked.countDown();
}
});
ch.close(); // close channel to make handler discard the input on subsequent flush
ch.flush();
assertTrue(listenerInvoked.await(10, SECONDS));
assertTrue(writeFuture.isSuccess());
assertTrue(inputClosedWhenListenerInvoked.get());
assertFalse(ch.finish());
}
@Test
public void testWriteListenerInvokedAfterChannelClosedAndInputNotFullyConsumed() throws Exception {
// use non-empty input which has endOfInput = false
final TestChunkedInput input = new TestChunkedInput(42);
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
final AtomicBoolean inputClosedWhenListenerInvoked = new AtomicBoolean();
final CountDownLatch listenerInvoked = new CountDownLatch(1);
ChannelFuture writeFuture = ch.write(input);
writeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
inputClosedWhenListenerInvoked.set(input.isClosed());
listenerInvoked.countDown();
}
});
ch.close(); // close channel to make handler discard the input on subsequent flush
ch.flush();
assertTrue(listenerInvoked.await(10, SECONDS));
assertFalse(writeFuture.isSuccess());
assertTrue(inputClosedWhenListenerInvoked.get());
assertFalse(ch.finish());
}
private static void check(Object... inputs) {
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
for (Object input: inputs) {
ch.writeOutbound(input);
}
assertTrue(ch.finish());
int i = 0;
int read = 0;
for (;;) {
ByteBuf buffer = ch.readOutbound();
if (buffer == null) {
break;
}
while (buffer.isReadable()) {
assertEquals(BYTES[i++], buffer.readByte());
read++;
if (i == BYTES.length) {
i = 0;
}
}
buffer.release();
}
assertEquals(BYTES.length * inputs.length, read);
}
private static void checkFirstFailed(Object input) {
ChannelOutboundHandlerAdapter noOpWrites = new ChannelOutboundHandlerAdapter() {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
ReferenceCountUtil.release(msg);
promise.tryFailure(new RuntimeException());
}
};
EmbeddedChannel ch = new EmbeddedChannel(noOpWrites, new ChunkedWriteHandler());
ChannelFuture r = ch.writeAndFlush(input);
// Should be `false` as we do not expect any messages to be written
assertFalse(ch.finish());
assertTrue(r.cause() instanceof RuntimeException);
}
private static void checkSkipFailed(Object input1, Object input2) {
ChannelOutboundHandlerAdapter failFirst = new ChannelOutboundHandlerAdapter() {
private boolean alreadyFailed;
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
if (alreadyFailed) {
ctx.write(msg, promise);
} else {
this.alreadyFailed = true;
ReferenceCountUtil.release(msg);
promise.tryFailure(new RuntimeException());
}
}
};
EmbeddedChannel ch = new EmbeddedChannel(failFirst, new ChunkedWriteHandler());
ChannelFuture r1 = ch.write(input1);
ChannelFuture r2 = ch.writeAndFlush(input2).awaitUninterruptibly();
assertTrue(ch.finish());
assertTrue(r1.cause() instanceof RuntimeException);
assertTrue(r2.isSuccess());
// note, that after we've "skipped" the first write,
// we expect to see the second message, chunk by chunk
int i = 0;
int read = 0;
for (;;) {
ByteBuf buffer = ch.readOutbound();
if (buffer == null) {
break;
}
while (buffer.isReadable()) {
assertEquals(BYTES[i++], buffer.readByte());
read++;
if (i == BYTES.length) {
i = 0;
}
}
buffer.release();
}
assertEquals(BYTES.length, read);
}
private static final class TestChunkedInput implements ChunkedInput<ByteBuf> {
private final int chunksToProduce;
private int chunksProduced;
private volatile boolean closed;
TestChunkedInput(int chunksToProduce) {
this.chunksToProduce = chunksToProduce;
}
@Override
public boolean isEndOfInput() {
return chunksProduced >= chunksToProduce;
}
@Override
public void close() {
closed = true;
}
@Override
public ByteBuf readChunk(ChannelHandlerContext ctx) {
return readChunk(ctx.alloc());
}
@Override
public ByteBuf readChunk(ByteBufAllocator allocator) {
ByteBuf buf = allocator.buffer();
buf.writeInt(chunksProduced);
chunksProduced++;
return buf;
}
@Override
public long length() {
return chunksToProduce;
}
@Override
public long progress() {
return chunksProduced;
}
boolean isClosed() {
return closed;
}
}
private static final class ThrowingChunkedInput implements ChunkedInput<ByteBuf> {
private final Exception error;
private volatile boolean closed;
ThrowingChunkedInput(Exception error) {
this.error = error;
}
@Override
public boolean isEndOfInput() {
return false;
}
@Override
public void close() {
closed = true;
}
@Override
public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
return readChunk(ctx.alloc());
}
@Override
public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {
throw error;
}
@Override
public long length() {
return -1;
}
@Override
public long progress() {
return -1;
}
boolean isClosed() {
return closed;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_10 |
crossvul-java_data_bad_1927_9 | /*
* 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 io.netty.handler.ssl.util;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.base64.Base64;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.ThrowableUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Date;
/**
* Generates a temporary self-signed certificate for testing purposes.
* <p>
* <strong>NOTE:</strong>
* Never use the certificate and private key generated by this class in production.
* It is purely for testing purposes, and thus it is very insecure.
* It even uses an insecure pseudo-random generator for faster generation internally.
* </p><p>
* An X.509 certificate file and a EC/RSA private key file are generated in a system's temporary directory using
* {@link java.io.File#createTempFile(String, String)}, and they are deleted when the JVM exits using
* {@link java.io.File#deleteOnExit()}.
* </p><p>
* At first, this method tries to use OpenJDK's X.509 implementation (the {@code sun.security.x509} package).
* If it fails, it tries to use <a href="https://www.bouncycastle.org/">Bouncy Castle</a> as a fallback.
* </p>
*/
public final class SelfSignedCertificate {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SelfSignedCertificate.class);
/** Current time minus 1 year, just in case software clock goes back due to time synchronization */
private static final Date DEFAULT_NOT_BEFORE = new Date(SystemPropertyUtil.getLong(
"io.netty.selfSignedCertificate.defaultNotBefore", System.currentTimeMillis() - 86400000L * 365));
/** The maximum possible value in X.509 specification: 9999-12-31 23:59:59 */
private static final Date DEFAULT_NOT_AFTER = new Date(SystemPropertyUtil.getLong(
"io.netty.selfSignedCertificate.defaultNotAfter", 253402300799000L));
/**
* FIPS 140-2 encryption requires the RSA key length to be 2048 bits or greater.
* Let's use that as a sane default but allow the default to be set dynamically
* for those that need more stringent security requirements.
*/
private static final int DEFAULT_KEY_LENGTH_BITS =
SystemPropertyUtil.getInt("io.netty.handler.ssl.util.selfSignedKeyStrength", 2048);
private final File certificate;
private final File privateKey;
private final X509Certificate cert;
private final PrivateKey key;
/**
* Creates a new instance.
* <p> Algorithm: RSA </p>
*/
public SelfSignedCertificate() throws CertificateException {
this(DEFAULT_NOT_BEFORE, DEFAULT_NOT_AFTER, "RSA", DEFAULT_KEY_LENGTH_BITS);
}
/**
* Creates a new instance.
* <p> Algorithm: RSA </p>
*
* @param notBefore Certificate is not valid before this time
* @param notAfter Certificate is not valid after this time
*/
public SelfSignedCertificate(Date notBefore, Date notAfter)
throws CertificateException {
this("localhost", notBefore, notAfter, "RSA", DEFAULT_KEY_LENGTH_BITS);
}
/**
* Creates a new instance.
*
* @param notBefore Certificate is not valid before this time
* @param notAfter Certificate is not valid after this time
* @param algorithm Key pair algorithm
* @param bits the number of bits of the generated private key
*/
public SelfSignedCertificate(Date notBefore, Date notAfter, String algorithm, int bits)
throws CertificateException {
this("localhost", notBefore, notAfter, algorithm, bits);
}
/**
* Creates a new instance.
* <p> Algorithm: RSA </p>
*
* @param fqdn a fully qualified domain name
*/
public SelfSignedCertificate(String fqdn) throws CertificateException {
this(fqdn, DEFAULT_NOT_BEFORE, DEFAULT_NOT_AFTER, "RSA", DEFAULT_KEY_LENGTH_BITS);
}
/**
* Creates a new instance.
*
* @param fqdn a fully qualified domain name
* @param algorithm Key pair algorithm
* @param bits the number of bits of the generated private key
*/
public SelfSignedCertificate(String fqdn, String algorithm, int bits) throws CertificateException {
this(fqdn, DEFAULT_NOT_BEFORE, DEFAULT_NOT_AFTER, algorithm, bits);
}
/**
* Creates a new instance.
* <p> Algorithm: RSA </p>
*
* @param fqdn a fully qualified domain name
* @param notBefore Certificate is not valid before this time
* @param notAfter Certificate is not valid after this time
*/
public SelfSignedCertificate(String fqdn, Date notBefore, Date notAfter) throws CertificateException {
// Bypass entropy collection by using insecure random generator.
// We just want to generate it without any delay because it's for testing purposes only.
this(fqdn, ThreadLocalInsecureRandom.current(), DEFAULT_KEY_LENGTH_BITS, notBefore, notAfter, "RSA");
}
/**
* Creates a new instance.
*
* @param fqdn a fully qualified domain name
* @param notBefore Certificate is not valid before this time
* @param notAfter Certificate is not valid after this time
* @param algorithm Key pair algorithm
* @param bits the number of bits of the generated private key
*/
public SelfSignedCertificate(String fqdn, Date notBefore, Date notAfter, String algorithm, int bits)
throws CertificateException {
// Bypass entropy collection by using insecure random generator.
// We just want to generate it without any delay because it's for testing purposes only.
this(fqdn, ThreadLocalInsecureRandom.current(), bits, notBefore, notAfter, algorithm);
}
/**
* Creates a new instance.
* <p> Algorithm: RSA </p>
*
* @param fqdn a fully qualified domain name
* @param random the {@link SecureRandom} to use
* @param bits the number of bits of the generated private key
*/
public SelfSignedCertificate(String fqdn, SecureRandom random, int bits)
throws CertificateException {
this(fqdn, random, bits, DEFAULT_NOT_BEFORE, DEFAULT_NOT_AFTER, "RSA");
}
/**
* Creates a new instance.
*
* @param fqdn a fully qualified domain name
* @param random the {@link SecureRandom} to use
* @param algorithm Key pair algorithm
* @param bits the number of bits of the generated private key
*/
public SelfSignedCertificate(String fqdn, SecureRandom random, String algorithm, int bits)
throws CertificateException {
this(fqdn, random, bits, DEFAULT_NOT_BEFORE, DEFAULT_NOT_AFTER, algorithm);
}
/**
* Creates a new instance.
* <p> Algorithm: RSA </p>
*
* @param fqdn a fully qualified domain name
* @param random the {@link SecureRandom} to use
* @param bits the number of bits of the generated private key
* @param notBefore Certificate is not valid before this time
* @param notAfter Certificate is not valid after this time
*/
public SelfSignedCertificate(String fqdn, SecureRandom random, int bits, Date notBefore, Date notAfter)
throws CertificateException {
this(fqdn, random, bits, notBefore, notAfter, "RSA");
}
/**
* Creates a new instance.
*
* @param fqdn a fully qualified domain name
* @param random the {@link SecureRandom} to use
* @param bits the number of bits of the generated private key
* @param notBefore Certificate is not valid before this time
* @param notAfter Certificate is not valid after this time
* @param algorithm Key pair algorithm
*/
public SelfSignedCertificate(String fqdn, SecureRandom random, int bits, Date notBefore, Date notAfter,
String algorithm) throws CertificateException {
if (!algorithm.equalsIgnoreCase("EC") && !algorithm.equalsIgnoreCase("RSA")) {
throw new IllegalArgumentException("Algorithm not valid: " + algorithm);
}
final KeyPair keypair;
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
keyGen.initialize(bits, random);
keypair = keyGen.generateKeyPair();
} catch (NoSuchAlgorithmException e) {
// Should not reach here because every Java implementation must have RSA and EC key pair generator.
throw new Error(e);
}
String[] paths;
try {
// Try the OpenJDK's proprietary implementation.
paths = OpenJdkSelfSignedCertGenerator.generate(fqdn, keypair, random, notBefore, notAfter, algorithm);
} catch (Throwable t) {
logger.debug("Failed to generate a self-signed X.509 certificate using sun.security.x509:", t);
try {
// Try Bouncy Castle if the current JVM didn't have sun.security.x509.
paths = BouncyCastleSelfSignedCertGenerator.generate(
fqdn, keypair, random, notBefore, notAfter, algorithm);
} catch (Throwable t2) {
logger.debug("Failed to generate a self-signed X.509 certificate using Bouncy Castle:", t2);
final CertificateException certificateException = new CertificateException(
"No provider succeeded to generate a self-signed certificate. " +
"See debug log for the root cause.", t2);
ThrowableUtil.addSuppressed(certificateException, t);
throw certificateException;
}
}
certificate = new File(paths[0]);
privateKey = new File(paths[1]);
key = keypair.getPrivate();
FileInputStream certificateInput = null;
try {
certificateInput = new FileInputStream(certificate);
cert = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(certificateInput);
} catch (Exception e) {
throw new CertificateEncodingException(e);
} finally {
if (certificateInput != null) {
try {
certificateInput.close();
} catch (IOException e) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a file: " + certificate, e);
}
}
}
}
}
/**
* Returns the generated X.509 certificate file in PEM format.
*/
public File certificate() {
return certificate;
}
/**
* Returns the generated RSA private key file in PEM format.
*/
public File privateKey() {
return privateKey;
}
/**
* Returns the generated X.509 certificate.
*/
public X509Certificate cert() {
return cert;
}
/**
* Returns the generated RSA private key.
*/
public PrivateKey key() {
return key;
}
/**
* Deletes the generated X.509 certificate file and RSA private key file.
*/
public void delete() {
safeDelete(certificate);
safeDelete(privateKey);
}
static String[] newSelfSignedCertificate(
String fqdn, PrivateKey key, X509Certificate cert) throws IOException, CertificateEncodingException {
// Encode the private key into a file.
ByteBuf wrappedBuf = Unpooled.wrappedBuffer(key.getEncoded());
ByteBuf encodedBuf;
final String keyText;
try {
encodedBuf = Base64.encode(wrappedBuf, true);
try {
keyText = "-----BEGIN PRIVATE KEY-----\n" +
encodedBuf.toString(CharsetUtil.US_ASCII) +
"\n-----END PRIVATE KEY-----\n";
} finally {
encodedBuf.release();
}
} finally {
wrappedBuf.release();
}
File keyFile = File.createTempFile("keyutil_" + fqdn + '_', ".key");
keyFile.deleteOnExit();
OutputStream keyOut = new FileOutputStream(keyFile);
try {
keyOut.write(keyText.getBytes(CharsetUtil.US_ASCII));
keyOut.close();
keyOut = null;
} finally {
if (keyOut != null) {
safeClose(keyFile, keyOut);
safeDelete(keyFile);
}
}
wrappedBuf = Unpooled.wrappedBuffer(cert.getEncoded());
final String certText;
try {
encodedBuf = Base64.encode(wrappedBuf, true);
try {
// Encode the certificate into a CRT file.
certText = "-----BEGIN CERTIFICATE-----\n" +
encodedBuf.toString(CharsetUtil.US_ASCII) +
"\n-----END CERTIFICATE-----\n";
} finally {
encodedBuf.release();
}
} finally {
wrappedBuf.release();
}
File certFile = File.createTempFile("keyutil_" + fqdn + '_', ".crt");
certFile.deleteOnExit();
OutputStream certOut = new FileOutputStream(certFile);
try {
certOut.write(certText.getBytes(CharsetUtil.US_ASCII));
certOut.close();
certOut = null;
} finally {
if (certOut != null) {
safeClose(certFile, certOut);
safeDelete(certFile);
safeDelete(keyFile);
}
}
return new String[] { certFile.getPath(), keyFile.getPath() };
}
private static void safeDelete(File certFile) {
if (!certFile.delete()) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to delete a file: " + certFile);
}
}
}
private static void safeClose(File keyFile, OutputStream keyOut) {
try {
keyOut.close();
} catch (IOException e) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a file: " + keyFile, e);
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_9 |
crossvul-java_data_bad_1927_1 | /*
* Copyright 2013 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 io.netty.buffer;
import io.netty.util.internal.PlatformDependent;
import org.junit.Assert;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import java.nio.channels.FileChannel;
public class ReadOnlyDirectByteBufferBufTest {
protected ByteBuf buffer(ByteBuffer buffer) {
return new ReadOnlyByteBufferBuf(UnpooledByteBufAllocator.DEFAULT, buffer);
}
protected ByteBuffer allocate(int size) {
return ByteBuffer.allocateDirect(size);
}
@Test
public void testIsContiguous() {
ByteBuf buf = buffer(allocate(4).asReadOnlyBuffer());
Assert.assertTrue(buf.isContiguous());
buf.release();
}
@Test(expected = IllegalArgumentException.class)
public void testConstructWithWritable() {
buffer(allocate(1));
}
@Test
public void shouldIndicateNotWritable() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear();
try {
Assert.assertFalse(buf.isWritable());
} finally {
buf.release();
}
}
@Test
public void shouldIndicateNotWritableAnyNumber() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear();
try {
Assert.assertFalse(buf.isWritable(1));
} finally {
buf.release();
}
}
@Test
public void ensureWritableIntStatusShouldFailButNotThrow() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear();
try {
int result = buf.ensureWritable(1, false);
Assert.assertEquals(1, result);
} finally {
buf.release();
}
}
@Test
public void ensureWritableForceIntStatusShouldFailButNotThrow() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear();
try {
int result = buf.ensureWritable(1, true);
Assert.assertEquals(1, result);
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void ensureWritableShouldThrow() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear();
try {
buf.ensureWritable(1);
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetByte() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try {
buf.setByte(0, 1);
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetInt() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try {
buf.setInt(0, 1);
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetShort() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try {
buf.setShort(0, 1);
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetMedium() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try {
buf.setMedium(0, 1);
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetLong() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try {
buf.setLong(0, 1);
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetBytesViaArray() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try {
buf.setBytes(0, "test".getBytes());
} finally {
buf.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetBytesViaBuffer() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
ByteBuf copy = Unpooled.copyInt(1);
try {
buf.setBytes(0, copy);
} finally {
buf.release();
copy.release();
}
}
@Test(expected = ReadOnlyBufferException.class)
public void testSetBytesViaStream() throws IOException {
ByteBuf buf = buffer(ByteBuffer.allocateDirect(8).asReadOnlyBuffer());
try {
buf.setBytes(0, new ByteArrayInputStream("test".getBytes()), 2);
} finally {
buf.release();
}
}
@Test
public void testGetReadByte() {
ByteBuf buf = buffer(
((ByteBuffer) allocate(2).put(new byte[] { (byte) 1, (byte) 2 }).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.getByte(0));
Assert.assertEquals(2, buf.getByte(1));
Assert.assertEquals(1, buf.readByte());
Assert.assertEquals(2, buf.readByte());
Assert.assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testGetReadInt() {
ByteBuf buf = buffer(((ByteBuffer) allocate(8).putInt(1).putInt(2).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.getInt(0));
Assert.assertEquals(2, buf.getInt(4));
Assert.assertEquals(1, buf.readInt());
Assert.assertEquals(2, buf.readInt());
Assert.assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testGetReadShort() {
ByteBuf buf = buffer(((ByteBuffer) allocate(8)
.putShort((short) 1).putShort((short) 2).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.getShort(0));
Assert.assertEquals(2, buf.getShort(2));
Assert.assertEquals(1, buf.readShort());
Assert.assertEquals(2, buf.readShort());
Assert.assertFalse(buf.isReadable());
buf.release();
}
@Test
public void testGetReadLong() {
ByteBuf buf = buffer(((ByteBuffer) allocate(16)
.putLong(1).putLong(2).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.getLong(0));
Assert.assertEquals(2, buf.getLong(8));
Assert.assertEquals(1, buf.readLong());
Assert.assertEquals(2, buf.readLong());
Assert.assertFalse(buf.isReadable());
buf.release();
}
@Test(expected = IndexOutOfBoundsException.class)
public void testGetBytesByteBuffer() {
byte[] bytes = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
// Ensure destination buffer is bigger then what is in the ByteBuf.
ByteBuffer nioBuffer = ByteBuffer.allocate(bytes.length + 1);
ByteBuf buffer = buffer(((ByteBuffer) allocate(bytes.length)
.put(bytes).flip()).asReadOnlyBuffer());
try {
buffer.getBytes(buffer.readerIndex(), nioBuffer);
} finally {
buffer.release();
}
}
@Test
public void testCopy() {
ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer());
ByteBuf copy = buf.copy();
Assert.assertEquals(buf, copy);
buf.release();
copy.release();
}
@Test
public void testCopyWithOffset() {
ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer());
ByteBuf copy = buf.copy(1, 9);
Assert.assertEquals(buf.slice(1, 9), copy);
buf.release();
copy.release();
}
// Test for https://github.com/netty/netty/issues/1708
@Test
public void testWrapBufferWithNonZeroPosition() {
ByteBuf buf = buffer(((ByteBuffer) allocate(16)
.putLong(1).flip().position(1)).asReadOnlyBuffer());
ByteBuf slice = buf.slice();
Assert.assertEquals(buf, slice);
buf.release();
}
@Test
public void testWrapBufferRoundTrip() {
ByteBuf buf = buffer(((ByteBuffer) allocate(16).putInt(1).putInt(2).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.readInt());
ByteBuffer nioBuffer = buf.nioBuffer();
// Ensure this can be accessed without throwing a BufferUnderflowException
Assert.assertEquals(2, nioBuffer.getInt());
buf.release();
}
@Test
public void testWrapMemoryMapped() throws Exception {
File file = File.createTempFile("netty-test", "tmp");
FileChannel output = null;
FileChannel input = null;
ByteBuf b1 = null;
ByteBuf b2 = null;
try {
output = new RandomAccessFile(file, "rw").getChannel();
byte[] bytes = new byte[1024];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
output.write(ByteBuffer.wrap(bytes));
input = new RandomAccessFile(file, "r").getChannel();
ByteBuffer m = input.map(FileChannel.MapMode.READ_ONLY, 0, input.size());
b1 = buffer(m);
ByteBuffer dup = m.duplicate();
dup.position(2);
dup.limit(4);
b2 = buffer(dup);
Assert.assertEquals(b2, b1.slice(2, 2));
} finally {
if (b1 != null) {
b1.release();
}
if (b2 != null) {
b2.release();
}
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
file.delete();
}
}
@Test
public void testMemoryAddress() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try {
Assert.assertFalse(buf.hasMemoryAddress());
try {
buf.memoryAddress();
Assert.fail();
} catch (UnsupportedOperationException expected) {
// expected
}
} finally {
buf.release();
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_1 |
crossvul-java_data_good_1927_5 | /*
* Copyright 2012 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 io.netty.handler.codec.http.multipart;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;
import java.util.UUID;
import static io.netty.util.CharsetUtil.*;
import static org.junit.Assert.*;
/** {@link AbstractMemoryHttpData} test cases. */
public class AbstractMemoryHttpDataTest {
@Test
public void testSetContentFromFile() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), ".tmp", null);
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] bytes = new byte[4096];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
test.setContent(tmpFile);
ByteBuf buf = test.getByteBuf();
assertEquals(buf.readerIndex(), 0);
assertEquals(buf.writerIndex(), bytes.length);
assertArrayEquals(bytes, test.get());
assertArrayEquals(bytes, ByteBufUtil.getBytes(buf));
} finally {
//release the ByteBuf
test.delete();
}
}
@Test
public void testRenameTo() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), ".tmp", null);
tmpFile.deleteOnExit();
final int totalByteCount = 4096;
byte[] bytes = new byte[totalByteCount];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ByteBuf content = Unpooled.wrappedBuffer(bytes);
test.setContent(content);
boolean succ = test.renameTo(tmpFile);
assertTrue(succ);
FileInputStream fis = new FileInputStream(tmpFile);
try {
byte[] buf = new byte[totalByteCount];
int count = 0;
int offset = 0;
int size = totalByteCount;
while ((count = fis.read(buf, offset, size)) > 0) {
offset += count;
size -= count;
if (offset >= totalByteCount || size <= 0) {
break;
}
}
assertArrayEquals(bytes, buf);
assertEquals(0, fis.available());
} finally {
fis.close();
}
} finally {
//release the ByteBuf in AbstractMemoryHttpData
test.delete();
}
}
/**
* Provide content into HTTP data with input stream.
*
* @throws Exception In case of any exception.
*/
@Test
public void testSetContentFromStream() throws Exception {
// definedSize=0
TestHttpData test = new TestHttpData("test", UTF_8, 0);
String contentStr = "foo_test";
ByteBuf buf = Unpooled.wrappedBuffer(contentStr.getBytes(UTF_8));
buf.markReaderIndex();
ByteBufInputStream is = new ByteBufInputStream(buf);
try {
test.setContent(is);
assertFalse(buf.isReadable());
assertEquals(test.getString(UTF_8), contentStr);
buf.resetReaderIndex();
assertTrue(ByteBufUtil.equals(buf, test.getByteBuf()));
} finally {
is.close();
}
Random random = new SecureRandom();
for (int i = 0; i < 20; i++) {
// Generate input data bytes.
int size = random.nextInt(Short.MAX_VALUE);
byte[] bytes = new byte[size];
random.nextBytes(bytes);
// Generate parsed HTTP data block.
TestHttpData data = new TestHttpData("name", UTF_8, 0);
data.setContent(new ByteArrayInputStream(bytes));
// Validate stored data.
ByteBuf buffer = data.getByteBuf();
assertEquals(0, buffer.readerIndex());
assertEquals(bytes.length, buffer.writerIndex());
assertArrayEquals(bytes, Arrays.copyOf(buffer.array(), bytes.length));
assertArrayEquals(bytes, data.get());
}
}
/** Memory-based HTTP data implementation for test purposes. */
private static final class TestHttpData extends AbstractMemoryHttpData {
/**
* Constructs HTTP data for tests.
*
* @param name Name of parsed data block.
* @param charset Used charset for data decoding.
* @param size Expected data block size.
*/
private TestHttpData(String name, Charset charset, long size) {
super(name, charset, size);
}
@Override
public InterfaceHttpData.HttpDataType getHttpDataType() {
throw reject();
}
@Override
public HttpData copy() {
throw reject();
}
@Override
public HttpData duplicate() {
throw reject();
}
@Override
public HttpData retainedDuplicate() {
throw reject();
}
@Override
public HttpData replace(ByteBuf content) {
return null;
}
@Override
public int compareTo(InterfaceHttpData o) {
throw reject();
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
private static UnsupportedOperationException reject() {
throw new UnsupportedOperationException("Should never be called.");
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_5 |
crossvul-java_data_bad_1927_12 | /*
* Copyright 2012 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 io.netty.testsuite.transport.socket;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.FileRegion;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.internal.PlatformDependent;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.WritableByteChannel;
import java.util.Random;
import java.util.concurrent.atomic.AtomicReference;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.*;
public class SocketFileRegionTest extends AbstractSocketTest {
static final byte[] data = new byte[1048576 * 10];
static {
PlatformDependent.threadLocalRandom().nextBytes(data);
}
@Test
public void testFileRegion() throws Throwable {
run();
}
@Test
public void testCustomFileRegion() throws Throwable {
run();
}
@Test
public void testFileRegionNotAutoRead() throws Throwable {
run();
}
@Test
public void testFileRegionVoidPromise() throws Throwable {
run();
}
@Test
public void testFileRegionVoidPromiseNotAutoRead() throws Throwable {
run();
}
@Test
public void testFileRegionCountLargerThenFile() throws Throwable {
run();
}
public void testFileRegion(ServerBootstrap sb, Bootstrap cb) throws Throwable {
testFileRegion0(sb, cb, false, true, true);
}
public void testCustomFileRegion(ServerBootstrap sb, Bootstrap cb) throws Throwable {
testFileRegion0(sb, cb, false, true, false);
}
public void testFileRegionVoidPromise(ServerBootstrap sb, Bootstrap cb) throws Throwable {
testFileRegion0(sb, cb, true, true, true);
}
public void testFileRegionNotAutoRead(ServerBootstrap sb, Bootstrap cb) throws Throwable {
testFileRegion0(sb, cb, false, false, true);
}
public void testFileRegionVoidPromiseNotAutoRead(ServerBootstrap sb, Bootstrap cb) throws Throwable {
testFileRegion0(sb, cb, true, false, true);
}
public void testFileRegionCountLargerThenFile(ServerBootstrap sb, Bootstrap cb) throws Throwable {
File file = File.createTempFile("netty-", ".tmp");
file.deleteOnExit();
final FileOutputStream out = new FileOutputStream(file);
out.write(data);
out.close();
sb.childHandler(new SimpleChannelInboundHandler<ByteBuf>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
// Just drop the message.
}
});
cb.handler(new ChannelInboundHandlerAdapter());
Channel sc = sb.bind().sync().channel();
Channel cc = cb.connect(sc.localAddress()).sync().channel();
// Request file region which is bigger then the underlying file.
FileRegion region = new DefaultFileRegion(
new RandomAccessFile(file, "r").getChannel(), 0, data.length + 1024);
assertThat(cc.writeAndFlush(region).await().cause(), CoreMatchers.<Throwable>instanceOf(IOException.class));
cc.close().sync();
sc.close().sync();
}
private static void testFileRegion0(
ServerBootstrap sb, Bootstrap cb, boolean voidPromise, final boolean autoRead, boolean defaultFileRegion)
throws Throwable {
sb.childOption(ChannelOption.AUTO_READ, autoRead);
cb.option(ChannelOption.AUTO_READ, autoRead);
final int bufferSize = 1024;
final File file = File.createTempFile("netty-", ".tmp");
file.deleteOnExit();
final FileOutputStream out = new FileOutputStream(file);
final Random random = PlatformDependent.threadLocalRandom();
// Prepend random data which will not be transferred, so that we can test non-zero start offset
final int startOffset = random.nextInt(8192);
for (int i = 0; i < startOffset; i ++) {
out.write(random.nextInt());
}
// .. and here comes the real data to transfer.
out.write(data, bufferSize, data.length - bufferSize);
// .. and then some extra data which is not supposed to be transferred.
for (int i = random.nextInt(8192); i > 0; i --) {
out.write(random.nextInt());
}
out.close();
ChannelInboundHandler ch = new SimpleChannelInboundHandler<Object>() {
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
if (!autoRead) {
ctx.read();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
};
TestHandler sh = new TestHandler(autoRead);
sb.childHandler(sh);
cb.handler(ch);
Channel sc = sb.bind().sync().channel();
Channel cc = cb.connect(sc.localAddress()).sync().channel();
FileRegion region = new DefaultFileRegion(
new RandomAccessFile(file, "r").getChannel(), startOffset, data.length - bufferSize);
FileRegion emptyRegion = new DefaultFileRegion(new RandomAccessFile(file, "r").getChannel(), 0, 0);
if (!defaultFileRegion) {
region = new FileRegionWrapper(region);
emptyRegion = new FileRegionWrapper(emptyRegion);
}
// Do write ByteBuf and then FileRegion to ensure that mixed writes work
// Also, write an empty FileRegion to test if writing an empty FileRegion does not cause any issues.
//
// See https://github.com/netty/netty/issues/2769
// https://github.com/netty/netty/issues/2964
if (voidPromise) {
assertEquals(cc.voidPromise(), cc.write(Unpooled.wrappedBuffer(data, 0, bufferSize), cc.voidPromise()));
assertEquals(cc.voidPromise(), cc.write(emptyRegion, cc.voidPromise()));
assertEquals(cc.voidPromise(), cc.writeAndFlush(region, cc.voidPromise()));
} else {
assertNotEquals(cc.voidPromise(), cc.write(Unpooled.wrappedBuffer(data, 0, bufferSize)));
assertNotEquals(cc.voidPromise(), cc.write(emptyRegion));
assertNotEquals(cc.voidPromise(), cc.writeAndFlush(region));
}
while (sh.counter < data.length) {
if (sh.exception.get() != null) {
break;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore.
}
}
sh.channel.close().sync();
cc.close().sync();
sc.close().sync();
if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
throw sh.exception.get();
}
if (sh.exception.get() != null) {
throw sh.exception.get();
}
// Make sure we did not receive more than we expected.
assertThat(sh.counter, is(data.length));
}
private static class TestHandler extends SimpleChannelInboundHandler<ByteBuf> {
private final boolean autoRead;
volatile Channel channel;
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
volatile int counter;
TestHandler(boolean autoRead) {
this.autoRead = autoRead;
}
@Override
public void channelActive(ChannelHandlerContext ctx)
throws Exception {
channel = ctx.channel();
if (!autoRead) {
ctx.read();
}
}
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
byte[] actual = new byte[in.readableBytes()];
in.readBytes(actual);
int lastIdx = counter;
for (int i = 0; i < actual.length; i ++) {
assertEquals(data[i + lastIdx], actual[i]);
}
counter += actual.length;
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
if (!autoRead) {
ctx.read();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) throws Exception {
if (exception.compareAndSet(null, cause)) {
ctx.close();
}
}
}
private static final class FileRegionWrapper implements FileRegion {
private final FileRegion region;
FileRegionWrapper(FileRegion region) {
this.region = region;
}
@Override
public int refCnt() {
return region.refCnt();
}
@Override
public long position() {
return region.position();
}
@Override
@Deprecated
public long transfered() {
return region.transferred();
}
@Override
public boolean release() {
return region.release();
}
@Override
public long transferred() {
return region.transferred();
}
@Override
public long count() {
return region.count();
}
@Override
public boolean release(int decrement) {
return region.release(decrement);
}
@Override
public long transferTo(WritableByteChannel target, long position) throws IOException {
return region.transferTo(target, position);
}
@Override
public FileRegion retain() {
region.retain();
return this;
}
@Override
public FileRegion retain(int increment) {
region.retain(increment);
return this;
}
@Override
public FileRegion touch() {
region.touch();
return this;
}
@Override
public FileRegion touch(Object hint) {
region.touch(hint);
return this;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_12 |
crossvul-java_data_bad_1927_11 | /*
* Copyright 2020 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 io.netty.handler.traffic;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.util.CharsetUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.SocketAddress;
import java.nio.charset.Charset;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import static org.junit.Assert.assertTrue;
public class FileRegionThrottleTest {
private static final byte[] BYTES = new byte[64 * 1024 * 4];
private static final long WRITE_LIMIT = 64 * 1024;
private static File tmp;
private EventLoopGroup group;
@BeforeClass
public static void beforeClass() throws IOException {
final Random r = new Random();
for (int i = 0; i < BYTES.length; i++) {
BYTES[i] = (byte) r.nextInt(255);
}
tmp = File.createTempFile("netty-traffic", ".tmp");
tmp.deleteOnExit();
FileOutputStream out = null;
try {
out = new FileOutputStream(tmp);
out.write(BYTES);
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignore
}
}
}
}
@Before
public void setUp() {
group = new NioEventLoopGroup();
}
@After
public void tearDown() {
group.shutdownGracefully();
}
@Test
public void testGlobalWriteThrottle() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final GlobalTrafficShapingHandler gtsh = new GlobalTrafficShapingHandler(group, WRITE_LIMIT, 0);
ServerBootstrap bs = new ServerBootstrap();
bs.group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new LineBasedFrameDecoder(Integer.MAX_VALUE));
ch.pipeline().addLast(new MessageDecoder());
ch.pipeline().addLast(gtsh);
}
});
Channel sc = bs.bind(0).sync().channel();
Channel cc = clientConnect(sc.localAddress(), new ReadHandler(latch)).channel();
long start = TrafficCounter.milliSecondFromNano();
cc.writeAndFlush(Unpooled.copiedBuffer("send-file\n", CharsetUtil.US_ASCII)).sync();
latch.await();
long timeTaken = TrafficCounter.milliSecondFromNano() - start;
assertTrue("Data streamed faster than expected", timeTaken > 3000);
sc.close().sync();
cc.close().sync();
}
private ChannelFuture clientConnect(final SocketAddress server, final ReadHandler readHandler) throws Exception {
Bootstrap bc = new Bootstrap();
bc.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(readHandler);
}
});
return bc.connect(server).sync();
}
private static final class MessageDecoder extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof ByteBuf) {
ByteBuf buf = (ByteBuf) msg;
String message = buf.toString(Charset.defaultCharset());
buf.release();
if (message.equals("send-file")) {
RandomAccessFile raf = new RandomAccessFile(tmp, "r");
ctx.channel().writeAndFlush(new DefaultFileRegion(raf.getChannel(), 0, tmp.length()));
}
}
}
}
private static final class ReadHandler extends ChannelInboundHandlerAdapter {
private long bytesTransferred;
private CountDownLatch latch;
ReadHandler(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof ByteBuf) {
ByteBuf buf = (ByteBuf) msg;
bytesTransferred += buf.readableBytes();
buf.release();
if (bytesTransferred == tmp.length()) {
latch.countDown();
}
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_11 |
crossvul-java_data_bad_1927_14 | /*
* Copyright 2016 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 io.netty.channel.unix.tests;
import io.netty.channel.unix.DomainSocketAddress;
import io.netty.channel.unix.Socket;
import java.io.File;
import java.io.IOException;
public final class UnixTestUtils {
public static DomainSocketAddress newSocketAddress() {
try {
File file;
do {
file = File.createTempFile("NETTY", "UDS");
if (!file.delete()) {
throw new IOException("failed to delete: " + file);
}
} while (file.getAbsolutePath().length() > 128);
return new DomainSocketAddress(file);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private UnixTestUtils() { }
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_14 |
crossvul-java_data_bad_1927_7 | /*
* 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 io.netty.util.internal;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
/**
* Helper class to load JNI resources.
*
*/
public final class NativeLibraryLoader {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(NativeLibraryLoader.class);
private static final String NATIVE_RESOURCE_HOME = "META-INF/native/";
private static final File WORKDIR;
private static final boolean DELETE_NATIVE_LIB_AFTER_LOADING;
private static final boolean TRY_TO_PATCH_SHADED_ID;
// Just use a-Z and numbers as valid ID bytes.
private static final byte[] UNIQUE_ID_BYTES =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(CharsetUtil.US_ASCII);
static {
String workdir = SystemPropertyUtil.get("io.netty.native.workdir");
if (workdir != null) {
File f = new File(workdir);
f.mkdirs();
try {
f = f.getAbsoluteFile();
} catch (Exception ignored) {
// Good to have an absolute path, but it's OK.
}
WORKDIR = f;
logger.debug("-Dio.netty.native.workdir: " + WORKDIR);
} else {
WORKDIR = PlatformDependent.tmpdir();
logger.debug("-Dio.netty.native.workdir: " + WORKDIR + " (io.netty.tmpdir)");
}
DELETE_NATIVE_LIB_AFTER_LOADING = SystemPropertyUtil.getBoolean(
"io.netty.native.deleteLibAfterLoading", true);
logger.debug("-Dio.netty.native.deleteLibAfterLoading: {}", DELETE_NATIVE_LIB_AFTER_LOADING);
TRY_TO_PATCH_SHADED_ID = SystemPropertyUtil.getBoolean(
"io.netty.native.tryPatchShadedId", true);
logger.debug("-Dio.netty.native.tryPatchShadedId: {}", TRY_TO_PATCH_SHADED_ID);
}
/**
* Loads the first available library in the collection with the specified
* {@link ClassLoader}.
*
* @throws IllegalArgumentException
* if none of the given libraries load successfully.
*/
public static void loadFirstAvailable(ClassLoader loader, String... names) {
List<Throwable> suppressed = new ArrayList<Throwable>();
for (String name : names) {
try {
load(name, loader);
return;
} catch (Throwable t) {
suppressed.add(t);
}
}
IllegalArgumentException iae =
new IllegalArgumentException("Failed to load any of the given libraries: " + Arrays.toString(names));
ThrowableUtil.addSuppressedAndClear(iae, suppressed);
throw iae;
}
/**
* The shading prefix added to this class's full name.
*
* @throws UnsatisfiedLinkError if the shader used something other than a prefix
*/
private static String calculatePackagePrefix() {
String maybeShaded = NativeLibraryLoader.class.getName();
// Use ! instead of . to avoid shading utilities from modifying the string
String expected = "io!netty!util!internal!NativeLibraryLoader".replace('!', '.');
if (!maybeShaded.endsWith(expected)) {
throw new UnsatisfiedLinkError(String.format(
"Could not find prefix added to %s to get %s. When shading, only adding a "
+ "package prefix is supported", expected, maybeShaded));
}
return maybeShaded.substring(0, maybeShaded.length() - expected.length());
}
/**
* Load the given library with the specified {@link ClassLoader}
*/
public static void load(String originalName, ClassLoader loader) {
// Adjust expected name to support shading of native libraries.
String packagePrefix = calculatePackagePrefix().replace('.', '_');
String name = packagePrefix + originalName;
List<Throwable> suppressed = new ArrayList<Throwable>();
try {
// first try to load from java.library.path
loadLibrary(loader, name, false);
return;
} catch (Throwable ex) {
suppressed.add(ex);
}
String libname = System.mapLibraryName(name);
String path = NATIVE_RESOURCE_HOME + libname;
InputStream in = null;
OutputStream out = null;
File tmpFile = null;
URL url;
if (loader == null) {
url = ClassLoader.getSystemResource(path);
} else {
url = loader.getResource(path);
}
try {
if (url == null) {
if (PlatformDependent.isOsx()) {
String fileName = path.endsWith(".jnilib") ? NATIVE_RESOURCE_HOME + "lib" + name + ".dynlib" :
NATIVE_RESOURCE_HOME + "lib" + name + ".jnilib";
if (loader == null) {
url = ClassLoader.getSystemResource(fileName);
} else {
url = loader.getResource(fileName);
}
if (url == null) {
FileNotFoundException fnf = new FileNotFoundException(fileName);
ThrowableUtil.addSuppressedAndClear(fnf, suppressed);
throw fnf;
}
} else {
FileNotFoundException fnf = new FileNotFoundException(path);
ThrowableUtil.addSuppressedAndClear(fnf, suppressed);
throw fnf;
}
}
int index = libname.lastIndexOf('.');
String prefix = libname.substring(0, index);
String suffix = libname.substring(index);
tmpFile = File.createTempFile(prefix, suffix, WORKDIR);
in = url.openStream();
out = new FileOutputStream(tmpFile);
if (shouldShadedLibraryIdBePatched(packagePrefix)) {
patchShadedLibraryId(in, out, originalName, name);
} else {
byte[] buffer = new byte[8192];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}
out.flush();
// Close the output stream before loading the unpacked library,
// because otherwise Windows will refuse to load it when it's in use by other process.
closeQuietly(out);
out = null;
loadLibrary(loader, tmpFile.getPath(), true);
} catch (UnsatisfiedLinkError e) {
try {
if (tmpFile != null && tmpFile.isFile() && tmpFile.canRead() &&
!NoexecVolumeDetector.canExecuteExecutable(tmpFile)) {
// Pass "io.netty.native.workdir" as an argument to allow shading tools to see
// the string. Since this is printed out to users to tell them what to do next,
// we want the value to be correct even when shading.
logger.info("{} exists but cannot be executed even when execute permissions set; " +
"check volume for \"noexec\" flag; use -D{}=[path] " +
"to set native working directory separately.",
tmpFile.getPath(), "io.netty.native.workdir");
}
} catch (Throwable t) {
suppressed.add(t);
logger.debug("Error checking if {} is on a file store mounted with noexec", tmpFile, t);
}
// Re-throw to fail the load
ThrowableUtil.addSuppressedAndClear(e, suppressed);
throw e;
} catch (Exception e) {
UnsatisfiedLinkError ule = new UnsatisfiedLinkError("could not load a native library: " + name);
ule.initCause(e);
ThrowableUtil.addSuppressedAndClear(ule, suppressed);
throw ule;
} finally {
closeQuietly(in);
closeQuietly(out);
// After we load the library it is safe to delete the file.
// We delete the file immediately to free up resources as soon as possible,
// and if this fails fallback to deleting on JVM exit.
if (tmpFile != null && (!DELETE_NATIVE_LIB_AFTER_LOADING || !tmpFile.delete())) {
tmpFile.deleteOnExit();
}
}
}
// Package-private for testing.
static boolean patchShadedLibraryId(InputStream in, OutputStream out, String originalName, String name)
throws IOException {
byte[] buffer = new byte[8192];
int length;
// We read the whole native lib into memory to make it easier to monkey-patch the id.
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(in.available());
while ((length = in.read(buffer)) > 0) {
byteArrayOutputStream.write(buffer, 0, length);
}
byteArrayOutputStream.flush();
byte[] bytes = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
final boolean patched;
// Try to patch the library id.
if (!patchShadedLibraryId(bytes, originalName, name)) {
// We did not find the Id, check if we used a originalName that has the os and arch as suffix.
// If this is the case we should also try to patch with the os and arch suffix removed.
String os = PlatformDependent.normalizedOs();
String arch = PlatformDependent.normalizedArch();
String osArch = "_" + os + "_" + arch;
if (originalName.endsWith(osArch)) {
patched = patchShadedLibraryId(bytes,
originalName.substring(0, originalName.length() - osArch.length()), name);
} else {
patched = false;
}
} else {
patched = true;
}
out.write(bytes, 0, bytes.length);
return patched;
}
private static boolean shouldShadedLibraryIdBePatched(String packagePrefix) {
return TRY_TO_PATCH_SHADED_ID && PlatformDependent.isOsx() && !packagePrefix.isEmpty();
}
/**
* Try to patch shaded library to ensure it uses a unique ID.
*/
private static boolean patchShadedLibraryId(byte[] bytes, String originalName, String name) {
// Our native libs always have the name as part of their id so we can search for it and replace it
// to make the ID unique if shading is used.
byte[] nameBytes = originalName.getBytes(CharsetUtil.UTF_8);
int idIdx = -1;
// Be aware this is a really raw way of patching a dylib but it does all we need without implementing
// a full mach-o parser and writer. Basically we just replace the the original bytes with some
// random bytes as part of the ID regeneration. The important thing here is that we need to use the same
// length to not corrupt the mach-o header.
outerLoop: for (int i = 0; i < bytes.length && bytes.length - i >= nameBytes.length; i++) {
int idx = i;
for (int j = 0; j < nameBytes.length;) {
if (bytes[idx++] != nameBytes[j++]) {
// Did not match the name, increase the index and try again.
break;
} else if (j == nameBytes.length) {
// We found the index within the id.
idIdx = i;
break outerLoop;
}
}
}
if (idIdx == -1) {
logger.debug("Was not able to find the ID of the shaded native library {}, can't adjust it.", name);
return false;
} else {
// We found our ID... now monkey-patch it!
for (int i = 0; i < nameBytes.length; i++) {
// We should only use bytes as replacement that are in our UNIQUE_ID_BYTES array.
bytes[idIdx + i] = UNIQUE_ID_BYTES[PlatformDependent.threadLocalRandom()
.nextInt(UNIQUE_ID_BYTES.length)];
}
if (logger.isDebugEnabled()) {
logger.debug(
"Found the ID of the shaded native library {}. Replacing ID part {} with {}",
name, originalName, new String(bytes, idIdx, nameBytes.length, CharsetUtil.UTF_8));
}
return true;
}
}
/**
* Loading the native library into the specified {@link ClassLoader}.
* @param loader - The {@link ClassLoader} where the native library will be loaded into
* @param name - The native library path or name
* @param absolute - Whether the native library will be loaded by path or by name
*/
private static void loadLibrary(final ClassLoader loader, final String name, final boolean absolute) {
Throwable suppressed = null;
try {
try {
// Make sure the helper is belong to the target ClassLoader.
final Class<?> newHelper = tryToLoadClass(loader, NativeLibraryUtil.class);
loadLibraryByHelper(newHelper, name, absolute);
logger.debug("Successfully loaded the library {}", name);
return;
} catch (UnsatisfiedLinkError e) { // Should by pass the UnsatisfiedLinkError here!
suppressed = e;
} catch (Exception e) {
suppressed = e;
}
NativeLibraryUtil.loadLibrary(name, absolute); // Fallback to local helper class.
logger.debug("Successfully loaded the library {}", name);
} catch (NoSuchMethodError nsme) {
if (suppressed != null) {
ThrowableUtil.addSuppressed(nsme, suppressed);
}
rethrowWithMoreDetailsIfPossible(name, nsme);
} catch (UnsatisfiedLinkError ule) {
if (suppressed != null) {
ThrowableUtil.addSuppressed(ule, suppressed);
}
throw ule;
}
}
@SuppressJava6Requirement(reason = "Guarded by version check")
private static void rethrowWithMoreDetailsIfPossible(String name, NoSuchMethodError error) {
if (PlatformDependent.javaVersion() >= 7) {
throw new LinkageError(
"Possible multiple incompatible native libraries on the classpath for '" + name + "'?", error);
}
throw error;
}
private static void loadLibraryByHelper(final Class<?> helper, final String name, final boolean absolute)
throws UnsatisfiedLinkError {
Object ret = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
// Invoke the helper to load the native library, if succeed, then the native
// library belong to the specified ClassLoader.
Method method = helper.getMethod("loadLibrary", String.class, boolean.class);
method.setAccessible(true);
return method.invoke(null, name, absolute);
} catch (Exception e) {
return e;
}
}
});
if (ret instanceof Throwable) {
Throwable t = (Throwable) ret;
assert !(t instanceof UnsatisfiedLinkError) : t + " should be a wrapper throwable";
Throwable cause = t.getCause();
if (cause instanceof UnsatisfiedLinkError) {
throw (UnsatisfiedLinkError) cause;
}
UnsatisfiedLinkError ule = new UnsatisfiedLinkError(t.getMessage());
ule.initCause(t);
throw ule;
}
}
/**
* Try to load the helper {@link Class} into specified {@link ClassLoader}.
* @param loader - The {@link ClassLoader} where to load the helper {@link Class}
* @param helper - The helper {@link Class}
* @return A new helper Class defined in the specified ClassLoader.
* @throws ClassNotFoundException Helper class not found or loading failed
*/
private static Class<?> tryToLoadClass(final ClassLoader loader, final Class<?> helper)
throws ClassNotFoundException {
try {
return Class.forName(helper.getName(), false, loader);
} catch (ClassNotFoundException e1) {
if (loader == null) {
// cannot defineClass inside bootstrap class loader
throw e1;
}
try {
// The helper class is NOT found in target ClassLoader, we have to define the helper class.
final byte[] classBinary = classToByteArray(helper);
return AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
@Override
public Class<?> run() {
try {
// Define the helper class in the target ClassLoader,
// then we can call the helper to load the native library.
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class,
byte[].class, int.class, int.class);
defineClass.setAccessible(true);
return (Class<?>) defineClass.invoke(loader, helper.getName(), classBinary, 0,
classBinary.length);
} catch (Exception e) {
throw new IllegalStateException("Define class failed!", e);
}
}
});
} catch (ClassNotFoundException e2) {
ThrowableUtil.addSuppressed(e2, e1);
throw e2;
} catch (RuntimeException e2) {
ThrowableUtil.addSuppressed(e2, e1);
throw e2;
} catch (Error e2) {
ThrowableUtil.addSuppressed(e2, e1);
throw e2;
}
}
}
/**
* Load the helper {@link Class} as a byte array, to be redefined in specified {@link ClassLoader}.
* @param clazz - The helper {@link Class} provided by this bundle
* @return The binary content of helper {@link Class}.
* @throws ClassNotFoundException Helper class not found or loading failed
*/
private static byte[] classToByteArray(Class<?> clazz) throws ClassNotFoundException {
String fileName = clazz.getName();
int lastDot = fileName.lastIndexOf('.');
if (lastDot > 0) {
fileName = fileName.substring(lastDot + 1);
}
URL classUrl = clazz.getResource(fileName + ".class");
if (classUrl == null) {
throw new ClassNotFoundException(clazz.getName());
}
byte[] buf = new byte[1024];
ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
InputStream in = null;
try {
in = classUrl.openStream();
for (int r; (r = in.read(buf)) != -1;) {
out.write(buf, 0, r);
}
return out.toByteArray();
} catch (IOException ex) {
throw new ClassNotFoundException(clazz.getName(), ex);
} finally {
closeQuietly(in);
closeQuietly(out);
}
}
private static void closeQuietly(Closeable c) {
if (c != null) {
try {
c.close();
} catch (IOException ignore) {
// ignore
}
}
}
private NativeLibraryLoader() {
// Utility
}
private static final class NoexecVolumeDetector {
@SuppressJava6Requirement(reason = "Usage guarded by java version check")
private static boolean canExecuteExecutable(File file) throws IOException {
if (PlatformDependent.javaVersion() < 7) {
// Pre-JDK7, the Java API did not directly support POSIX permissions; instead of implementing a custom
// work-around, assume true, which disables the check.
return true;
}
// If we can already execute, there is nothing to do.
if (file.canExecute()) {
return true;
}
// On volumes, with noexec set, even files with the executable POSIX permissions will fail to execute.
// The File#canExecute() method honors this behavior, probaby via parsing the noexec flag when initializing
// the UnixFileStore, though the flag is not exposed via a public API. To find out if library is being
// loaded off a volume with noexec, confirm or add executalbe permissions, then check File#canExecute().
// Note: We use FQCN to not break when netty is used in java6
Set<java.nio.file.attribute.PosixFilePermission> existingFilePermissions =
java.nio.file.Files.getPosixFilePermissions(file.toPath());
Set<java.nio.file.attribute.PosixFilePermission> executePermissions =
EnumSet.of(java.nio.file.attribute.PosixFilePermission.OWNER_EXECUTE,
java.nio.file.attribute.PosixFilePermission.GROUP_EXECUTE,
java.nio.file.attribute.PosixFilePermission.OTHERS_EXECUTE);
if (existingFilePermissions.containsAll(executePermissions)) {
return false;
}
Set<java.nio.file.attribute.PosixFilePermission> newPermissions = EnumSet.copyOf(existingFilePermissions);
newPermissions.addAll(executePermissions);
java.nio.file.Files.setPosixFilePermissions(file.toPath(), newPermissions);
return file.canExecute();
}
private NoexecVolumeDetector() {
// Utility
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_7 |
crossvul-java_data_bad_1927_8 | /*
* Copyright 2012 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 io.netty.util.internal;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.jctools.queues.MpscArrayQueue;
import org.jctools.queues.MpscChunkedArrayQueue;
import org.jctools.queues.MpscUnboundedArrayQueue;
import org.jctools.queues.SpscLinkedQueue;
import org.jctools.queues.atomic.MpscAtomicArrayQueue;
import org.jctools.queues.atomic.MpscChunkedAtomicArrayQueue;
import org.jctools.queues.atomic.MpscUnboundedAtomicArrayQueue;
import org.jctools.queues.atomic.SpscLinkedAtomicQueue;
import org.jctools.util.Pow2;
import org.jctools.util.UnsafeAccess;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.netty.util.internal.PlatformDependent0.HASH_CODE_ASCII_SEED;
import static io.netty.util.internal.PlatformDependent0.HASH_CODE_C1;
import static io.netty.util.internal.PlatformDependent0.HASH_CODE_C2;
import static io.netty.util.internal.PlatformDependent0.hashCodeAsciiSanitize;
import static io.netty.util.internal.PlatformDependent0.unalignedAccess;
import static java.lang.Math.max;
import static java.lang.Math.min;
/**
* Utility that detects various properties specific to the current runtime
* environment, such as Java version and the availability of the
* {@code sun.misc.Unsafe} object.
* <p>
* You can disable the use of {@code sun.misc.Unsafe} if you specify
* the system property <strong>io.netty.noUnsafe</strong>.
*/
public final class PlatformDependent {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(PlatformDependent.class);
private static final Pattern MAX_DIRECT_MEMORY_SIZE_ARG_PATTERN = Pattern.compile(
"\\s*-XX:MaxDirectMemorySize\\s*=\\s*([0-9]+)\\s*([kKmMgG]?)\\s*$");
private static final boolean IS_WINDOWS = isWindows0();
private static final boolean IS_OSX = isOsx0();
private static final boolean IS_J9_JVM = isJ9Jvm0();
private static final boolean IS_IVKVM_DOT_NET = isIkvmDotNet0();
private static final boolean MAYBE_SUPER_USER;
private static final boolean CAN_ENABLE_TCP_NODELAY_BY_DEFAULT = !isAndroid();
private static final Throwable UNSAFE_UNAVAILABILITY_CAUSE = unsafeUnavailabilityCause0();
private static final boolean DIRECT_BUFFER_PREFERRED;
private static final long MAX_DIRECT_MEMORY = maxDirectMemory0();
private static final int MPSC_CHUNK_SIZE = 1024;
private static final int MIN_MAX_MPSC_CAPACITY = MPSC_CHUNK_SIZE * 2;
private static final int MAX_ALLOWED_MPSC_CAPACITY = Pow2.MAX_POW2;
private static final long BYTE_ARRAY_BASE_OFFSET = byteArrayBaseOffset0();
private static final File TMPDIR = tmpdir0();
private static final int BIT_MODE = bitMode0();
private static final String NORMALIZED_ARCH = normalizeArch(SystemPropertyUtil.get("os.arch", ""));
private static final String NORMALIZED_OS = normalizeOs(SystemPropertyUtil.get("os.name", ""));
// keep in sync with maven's pom.xml via os.detection.classifierWithLikes!
private static final String[] ALLOWED_LINUX_OS_CLASSIFIERS = {"fedora", "suse", "arch"};
private static final Set<String> LINUX_OS_CLASSIFIERS;
private static final int ADDRESS_SIZE = addressSize0();
private static final boolean USE_DIRECT_BUFFER_NO_CLEANER;
private static final AtomicLong DIRECT_MEMORY_COUNTER;
private static final long DIRECT_MEMORY_LIMIT;
private static final ThreadLocalRandomProvider RANDOM_PROVIDER;
private static final Cleaner CLEANER;
private static final int UNINITIALIZED_ARRAY_ALLOCATION_THRESHOLD;
// For specifications, see https://www.freedesktop.org/software/systemd/man/os-release.html
private static final String[] OS_RELEASE_FILES = {"/etc/os-release", "/usr/lib/os-release"};
private static final String LINUX_ID_PREFIX = "ID=";
private static final String LINUX_ID_LIKE_PREFIX = "ID_LIKE=";
public static final boolean BIG_ENDIAN_NATIVE_ORDER = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN;
private static final Cleaner NOOP = new Cleaner() {
@Override
public void freeDirectBuffer(ByteBuffer buffer) {
// NOOP
}
};
static {
if (javaVersion() >= 7) {
RANDOM_PROVIDER = new ThreadLocalRandomProvider() {
@Override
@SuppressJava6Requirement(reason = "Usage guarded by java version check")
public Random current() {
return java.util.concurrent.ThreadLocalRandom.current();
}
};
} else {
RANDOM_PROVIDER = new ThreadLocalRandomProvider() {
@Override
public Random current() {
return ThreadLocalRandom.current();
}
};
}
// Here is how the system property is used:
//
// * < 0 - Don't use cleaner, and inherit max direct memory from java. In this case the
// "practical max direct memory" would be 2 * max memory as defined by the JDK.
// * == 0 - Use cleaner, Netty will not enforce max memory, and instead will defer to JDK.
// * > 0 - Don't use cleaner. This will limit Netty's total direct memory
// (note: that JDK's direct memory limit is independent of this).
long maxDirectMemory = SystemPropertyUtil.getLong("io.netty.maxDirectMemory", -1);
if (maxDirectMemory == 0 || !hasUnsafe() || !PlatformDependent0.hasDirectBufferNoCleanerConstructor()) {
USE_DIRECT_BUFFER_NO_CLEANER = false;
DIRECT_MEMORY_COUNTER = null;
} else {
USE_DIRECT_BUFFER_NO_CLEANER = true;
if (maxDirectMemory < 0) {
maxDirectMemory = MAX_DIRECT_MEMORY;
if (maxDirectMemory <= 0) {
DIRECT_MEMORY_COUNTER = null;
} else {
DIRECT_MEMORY_COUNTER = new AtomicLong();
}
} else {
DIRECT_MEMORY_COUNTER = new AtomicLong();
}
}
logger.debug("-Dio.netty.maxDirectMemory: {} bytes", maxDirectMemory);
DIRECT_MEMORY_LIMIT = maxDirectMemory >= 1 ? maxDirectMemory : MAX_DIRECT_MEMORY;
int tryAllocateUninitializedArray =
SystemPropertyUtil.getInt("io.netty.uninitializedArrayAllocationThreshold", 1024);
UNINITIALIZED_ARRAY_ALLOCATION_THRESHOLD = javaVersion() >= 9 && PlatformDependent0.hasAllocateArrayMethod() ?
tryAllocateUninitializedArray : -1;
logger.debug("-Dio.netty.uninitializedArrayAllocationThreshold: {}", UNINITIALIZED_ARRAY_ALLOCATION_THRESHOLD);
MAYBE_SUPER_USER = maybeSuperUser0();
if (!isAndroid()) {
// only direct to method if we are not running on android.
// See https://github.com/netty/netty/issues/2604
if (javaVersion() >= 9) {
CLEANER = CleanerJava9.isSupported() ? new CleanerJava9() : NOOP;
} else {
CLEANER = CleanerJava6.isSupported() ? new CleanerJava6() : NOOP;
}
} else {
CLEANER = NOOP;
}
// We should always prefer direct buffers by default if we can use a Cleaner to release direct buffers.
DIRECT_BUFFER_PREFERRED = CLEANER != NOOP
&& !SystemPropertyUtil.getBoolean("io.netty.noPreferDirect", false);
if (logger.isDebugEnabled()) {
logger.debug("-Dio.netty.noPreferDirect: {}", !DIRECT_BUFFER_PREFERRED);
}
/*
* We do not want to log this message if unsafe is explicitly disabled. Do not remove the explicit no unsafe
* guard.
*/
if (CLEANER == NOOP && !PlatformDependent0.isExplicitNoUnsafe()) {
logger.info(
"Your platform does not provide complete low-level API for accessing direct buffers reliably. " +
"Unless explicitly requested, heap buffer will always be preferred to avoid potential system " +
"instability.");
}
final Set<String> allowedClassifiers = Collections.unmodifiableSet(
new HashSet<String>(Arrays.asList(ALLOWED_LINUX_OS_CLASSIFIERS)));
final Set<String> availableClassifiers = new LinkedHashSet<String>();
for (final String osReleaseFileName : OS_RELEASE_FILES) {
final File file = new File(osReleaseFileName);
boolean found = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
try {
if (file.exists()) {
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(file), CharsetUtil.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith(LINUX_ID_PREFIX)) {
String id = normalizeOsReleaseVariableValue(
line.substring(LINUX_ID_PREFIX.length()));
addClassifier(allowedClassifiers, availableClassifiers, id);
} else if (line.startsWith(LINUX_ID_LIKE_PREFIX)) {
line = normalizeOsReleaseVariableValue(
line.substring(LINUX_ID_LIKE_PREFIX.length()));
addClassifier(allowedClassifiers, availableClassifiers, line.split("[ ]+"));
}
}
} catch (SecurityException e) {
logger.debug("Unable to read {}", osReleaseFileName, e);
} catch (IOException e) {
logger.debug("Error while reading content of {}", osReleaseFileName, e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
// Ignore
}
}
}
// specification states we should only fall back if /etc/os-release does not exist
return true;
}
} catch (SecurityException e) {
logger.debug("Unable to check if {} exists", osReleaseFileName, e);
}
return false;
}
});
if (found) {
break;
}
}
LINUX_OS_CLASSIFIERS = Collections.unmodifiableSet(availableClassifiers);
}
public static long byteArrayBaseOffset() {
return BYTE_ARRAY_BASE_OFFSET;
}
public static boolean hasDirectBufferNoCleanerConstructor() {
return PlatformDependent0.hasDirectBufferNoCleanerConstructor();
}
public static byte[] allocateUninitializedArray(int size) {
return UNINITIALIZED_ARRAY_ALLOCATION_THRESHOLD < 0 || UNINITIALIZED_ARRAY_ALLOCATION_THRESHOLD > size ?
new byte[size] : PlatformDependent0.allocateUninitializedArray(size);
}
/**
* Returns {@code true} if and only if the current platform is Android
*/
public static boolean isAndroid() {
return PlatformDependent0.isAndroid();
}
/**
* Return {@code true} if the JVM is running on Windows
*/
public static boolean isWindows() {
return IS_WINDOWS;
}
/**
* Return {@code true} if the JVM is running on OSX / MacOS
*/
public static boolean isOsx() {
return IS_OSX;
}
/**
* Return {@code true} if the current user may be a super-user. Be aware that this is just an hint and so it may
* return false-positives.
*/
public static boolean maybeSuperUser() {
return MAYBE_SUPER_USER;
}
/**
* Return the version of Java under which this library is used.
*/
public static int javaVersion() {
return PlatformDependent0.javaVersion();
}
/**
* Returns {@code true} if and only if it is fine to enable TCP_NODELAY socket option by default.
*/
public static boolean canEnableTcpNoDelayByDefault() {
return CAN_ENABLE_TCP_NODELAY_BY_DEFAULT;
}
/**
* Return {@code true} if {@code sun.misc.Unsafe} was found on the classpath and can be used for accelerated
* direct memory access.
*/
public static boolean hasUnsafe() {
return UNSAFE_UNAVAILABILITY_CAUSE == null;
}
/**
* Return the reason (if any) why {@code sun.misc.Unsafe} was not available.
*/
public static Throwable getUnsafeUnavailabilityCause() {
return UNSAFE_UNAVAILABILITY_CAUSE;
}
/**
* {@code true} if and only if the platform supports unaligned access.
*
* @see <a href="https://en.wikipedia.org/wiki/Segmentation_fault#Bus_error">Wikipedia on segfault</a>
*/
public static boolean isUnaligned() {
return PlatformDependent0.isUnaligned();
}
/**
* Returns {@code true} if the platform has reliable low-level direct buffer access API and a user has not specified
* {@code -Dio.netty.noPreferDirect} option.
*/
public static boolean directBufferPreferred() {
return DIRECT_BUFFER_PREFERRED;
}
/**
* Returns the maximum memory reserved for direct buffer allocation.
*/
public static long maxDirectMemory() {
return DIRECT_MEMORY_LIMIT;
}
/**
* Returns the current memory reserved for direct buffer allocation.
* This method returns -1 in case that a value is not available.
*
* @see #maxDirectMemory()
*/
public static long usedDirectMemory() {
return DIRECT_MEMORY_COUNTER != null ? DIRECT_MEMORY_COUNTER.get() : -1;
}
/**
* Returns the temporary directory.
*/
public static File tmpdir() {
return TMPDIR;
}
/**
* Returns the bit mode of the current VM (usually 32 or 64.)
*/
public static int bitMode() {
return BIT_MODE;
}
/**
* Return the address size of the OS.
* 4 (for 32 bits systems ) and 8 (for 64 bits systems).
*/
public static int addressSize() {
return ADDRESS_SIZE;
}
public static long allocateMemory(long size) {
return PlatformDependent0.allocateMemory(size);
}
public static void freeMemory(long address) {
PlatformDependent0.freeMemory(address);
}
public static long reallocateMemory(long address, long newSize) {
return PlatformDependent0.reallocateMemory(address, newSize);
}
/**
* Raises an exception bypassing compiler checks for checked exceptions.
*/
public static void throwException(Throwable t) {
if (hasUnsafe()) {
PlatformDependent0.throwException(t);
} else {
PlatformDependent.<RuntimeException>throwException0(t);
}
}
@SuppressWarnings("unchecked")
private static <E extends Throwable> void throwException0(Throwable t) throws E {
throw (E) t;
}
/**
* Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap() {
return new ConcurrentHashMap<K, V>();
}
/**
* Creates a new fastest {@link LongCounter} implementation for the current platform.
*/
public static LongCounter newLongCounter() {
if (javaVersion() >= 8) {
return new LongAdderCounter();
} else {
return new AtomicLongCounter();
}
}
/**
* Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(int initialCapacity) {
return new ConcurrentHashMap<K, V>(initialCapacity);
}
/**
* Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(int initialCapacity, float loadFactor) {
return new ConcurrentHashMap<K, V>(initialCapacity, loadFactor);
}
/**
* Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(
int initialCapacity, float loadFactor, int concurrencyLevel) {
return new ConcurrentHashMap<K, V>(initialCapacity, loadFactor, concurrencyLevel);
}
/**
* Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(Map<? extends K, ? extends V> map) {
return new ConcurrentHashMap<K, V>(map);
}
/**
* Try to deallocate the specified direct {@link ByteBuffer}. Please note this method does nothing if
* the current platform does not support this operation or the specified buffer is not a direct buffer.
*/
public static void freeDirectBuffer(ByteBuffer buffer) {
CLEANER.freeDirectBuffer(buffer);
}
public static long directBufferAddress(ByteBuffer buffer) {
return PlatformDependent0.directBufferAddress(buffer);
}
public static ByteBuffer directBuffer(long memoryAddress, int size) {
if (PlatformDependent0.hasDirectBufferNoCleanerConstructor()) {
return PlatformDependent0.newDirectBuffer(memoryAddress, size);
}
throw new UnsupportedOperationException(
"sun.misc.Unsafe or java.nio.DirectByteBuffer.<init>(long, int) not available");
}
public static Object getObject(Object object, long fieldOffset) {
return PlatformDependent0.getObject(object, fieldOffset);
}
public static int getInt(Object object, long fieldOffset) {
return PlatformDependent0.getInt(object, fieldOffset);
}
public static int getIntVolatile(long address) {
return PlatformDependent0.getIntVolatile(address);
}
public static void putIntOrdered(long adddress, int newValue) {
PlatformDependent0.putIntOrdered(adddress, newValue);
}
public static byte getByte(long address) {
return PlatformDependent0.getByte(address);
}
public static short getShort(long address) {
return PlatformDependent0.getShort(address);
}
public static int getInt(long address) {
return PlatformDependent0.getInt(address);
}
public static long getLong(long address) {
return PlatformDependent0.getLong(address);
}
public static byte getByte(byte[] data, int index) {
return PlatformDependent0.getByte(data, index);
}
public static byte getByte(byte[] data, long index) {
return PlatformDependent0.getByte(data, index);
}
public static short getShort(byte[] data, int index) {
return PlatformDependent0.getShort(data, index);
}
public static int getInt(byte[] data, int index) {
return PlatformDependent0.getInt(data, index);
}
public static int getInt(int[] data, long index) {
return PlatformDependent0.getInt(data, index);
}
public static long getLong(byte[] data, int index) {
return PlatformDependent0.getLong(data, index);
}
public static long getLong(long[] data, long index) {
return PlatformDependent0.getLong(data, index);
}
private static long getLongSafe(byte[] bytes, int offset) {
if (BIG_ENDIAN_NATIVE_ORDER) {
return (long) bytes[offset] << 56 |
((long) bytes[offset + 1] & 0xff) << 48 |
((long) bytes[offset + 2] & 0xff) << 40 |
((long) bytes[offset + 3] & 0xff) << 32 |
((long) bytes[offset + 4] & 0xff) << 24 |
((long) bytes[offset + 5] & 0xff) << 16 |
((long) bytes[offset + 6] & 0xff) << 8 |
(long) bytes[offset + 7] & 0xff;
}
return (long) bytes[offset] & 0xff |
((long) bytes[offset + 1] & 0xff) << 8 |
((long) bytes[offset + 2] & 0xff) << 16 |
((long) bytes[offset + 3] & 0xff) << 24 |
((long) bytes[offset + 4] & 0xff) << 32 |
((long) bytes[offset + 5] & 0xff) << 40 |
((long) bytes[offset + 6] & 0xff) << 48 |
(long) bytes[offset + 7] << 56;
}
private static int getIntSafe(byte[] bytes, int offset) {
if (BIG_ENDIAN_NATIVE_ORDER) {
return bytes[offset] << 24 |
(bytes[offset + 1] & 0xff) << 16 |
(bytes[offset + 2] & 0xff) << 8 |
bytes[offset + 3] & 0xff;
}
return bytes[offset] & 0xff |
(bytes[offset + 1] & 0xff) << 8 |
(bytes[offset + 2] & 0xff) << 16 |
bytes[offset + 3] << 24;
}
private static short getShortSafe(byte[] bytes, int offset) {
if (BIG_ENDIAN_NATIVE_ORDER) {
return (short) (bytes[offset] << 8 | (bytes[offset + 1] & 0xff));
}
return (short) (bytes[offset] & 0xff | (bytes[offset + 1] << 8));
}
/**
* Identical to {@link PlatformDependent0#hashCodeAsciiCompute(long, int)} but for {@link CharSequence}.
*/
private static int hashCodeAsciiCompute(CharSequence value, int offset, int hash) {
if (BIG_ENDIAN_NATIVE_ORDER) {
return hash * HASH_CODE_C1 +
// Low order int
hashCodeAsciiSanitizeInt(value, offset + 4) * HASH_CODE_C2 +
// High order int
hashCodeAsciiSanitizeInt(value, offset);
}
return hash * HASH_CODE_C1 +
// Low order int
hashCodeAsciiSanitizeInt(value, offset) * HASH_CODE_C2 +
// High order int
hashCodeAsciiSanitizeInt(value, offset + 4);
}
/**
* Identical to {@link PlatformDependent0#hashCodeAsciiSanitize(int)} but for {@link CharSequence}.
*/
private static int hashCodeAsciiSanitizeInt(CharSequence value, int offset) {
if (BIG_ENDIAN_NATIVE_ORDER) {
// mimic a unsafe.getInt call on a big endian machine
return (value.charAt(offset + 3) & 0x1f) |
(value.charAt(offset + 2) & 0x1f) << 8 |
(value.charAt(offset + 1) & 0x1f) << 16 |
(value.charAt(offset) & 0x1f) << 24;
}
return (value.charAt(offset + 3) & 0x1f) << 24 |
(value.charAt(offset + 2) & 0x1f) << 16 |
(value.charAt(offset + 1) & 0x1f) << 8 |
(value.charAt(offset) & 0x1f);
}
/**
* Identical to {@link PlatformDependent0#hashCodeAsciiSanitize(short)} but for {@link CharSequence}.
*/
private static int hashCodeAsciiSanitizeShort(CharSequence value, int offset) {
if (BIG_ENDIAN_NATIVE_ORDER) {
// mimic a unsafe.getShort call on a big endian machine
return (value.charAt(offset + 1) & 0x1f) |
(value.charAt(offset) & 0x1f) << 8;
}
return (value.charAt(offset + 1) & 0x1f) << 8 |
(value.charAt(offset) & 0x1f);
}
/**
* Identical to {@link PlatformDependent0#hashCodeAsciiSanitize(byte)} but for {@link CharSequence}.
*/
private static int hashCodeAsciiSanitizeByte(char value) {
return value & 0x1f;
}
public static void putByte(long address, byte value) {
PlatformDependent0.putByte(address, value);
}
public static void putShort(long address, short value) {
PlatformDependent0.putShort(address, value);
}
public static void putInt(long address, int value) {
PlatformDependent0.putInt(address, value);
}
public static void putLong(long address, long value) {
PlatformDependent0.putLong(address, value);
}
public static void putByte(byte[] data, int index, byte value) {
PlatformDependent0.putByte(data, index, value);
}
public static void putByte(Object data, long offset, byte value) {
PlatformDependent0.putByte(data, offset, value);
}
public static void putShort(byte[] data, int index, short value) {
PlatformDependent0.putShort(data, index, value);
}
public static void putInt(byte[] data, int index, int value) {
PlatformDependent0.putInt(data, index, value);
}
public static void putLong(byte[] data, int index, long value) {
PlatformDependent0.putLong(data, index, value);
}
public static void putObject(Object o, long offset, Object x) {
PlatformDependent0.putObject(o, offset, x);
}
public static long objectFieldOffset(Field field) {
return PlatformDependent0.objectFieldOffset(field);
}
public static void copyMemory(long srcAddr, long dstAddr, long length) {
PlatformDependent0.copyMemory(srcAddr, dstAddr, length);
}
public static void copyMemory(byte[] src, int srcIndex, long dstAddr, long length) {
PlatformDependent0.copyMemory(src, BYTE_ARRAY_BASE_OFFSET + srcIndex, null, dstAddr, length);
}
public static void copyMemory(byte[] src, int srcIndex, byte[] dst, int dstIndex, long length) {
PlatformDependent0.copyMemory(src, BYTE_ARRAY_BASE_OFFSET + srcIndex,
dst, BYTE_ARRAY_BASE_OFFSET + dstIndex, length);
}
public static void copyMemory(long srcAddr, byte[] dst, int dstIndex, long length) {
PlatformDependent0.copyMemory(null, srcAddr, dst, BYTE_ARRAY_BASE_OFFSET + dstIndex, length);
}
public static void setMemory(byte[] dst, int dstIndex, long bytes, byte value) {
PlatformDependent0.setMemory(dst, BYTE_ARRAY_BASE_OFFSET + dstIndex, bytes, value);
}
public static void setMemory(long address, long bytes, byte value) {
PlatformDependent0.setMemory(address, bytes, value);
}
/**
* Allocate a new {@link ByteBuffer} with the given {@code capacity}. {@link ByteBuffer}s allocated with
* this method <strong>MUST</strong> be deallocated via {@link #freeDirectNoCleaner(ByteBuffer)}.
*/
public static ByteBuffer allocateDirectNoCleaner(int capacity) {
assert USE_DIRECT_BUFFER_NO_CLEANER;
incrementMemoryCounter(capacity);
try {
return PlatformDependent0.allocateDirectNoCleaner(capacity);
} catch (Throwable e) {
decrementMemoryCounter(capacity);
throwException(e);
return null;
}
}
/**
* Reallocate a new {@link ByteBuffer} with the given {@code capacity}. {@link ByteBuffer}s reallocated with
* this method <strong>MUST</strong> be deallocated via {@link #freeDirectNoCleaner(ByteBuffer)}.
*/
public static ByteBuffer reallocateDirectNoCleaner(ByteBuffer buffer, int capacity) {
assert USE_DIRECT_BUFFER_NO_CLEANER;
int len = capacity - buffer.capacity();
incrementMemoryCounter(len);
try {
return PlatformDependent0.reallocateDirectNoCleaner(buffer, capacity);
} catch (Throwable e) {
decrementMemoryCounter(len);
throwException(e);
return null;
}
}
/**
* This method <strong>MUST</strong> only be called for {@link ByteBuffer}s that were allocated via
* {@link #allocateDirectNoCleaner(int)}.
*/
public static void freeDirectNoCleaner(ByteBuffer buffer) {
assert USE_DIRECT_BUFFER_NO_CLEANER;
int capacity = buffer.capacity();
PlatformDependent0.freeMemory(PlatformDependent0.directBufferAddress(buffer));
decrementMemoryCounter(capacity);
}
private static void incrementMemoryCounter(int capacity) {
if (DIRECT_MEMORY_COUNTER != null) {
long newUsedMemory = DIRECT_MEMORY_COUNTER.addAndGet(capacity);
if (newUsedMemory > DIRECT_MEMORY_LIMIT) {
DIRECT_MEMORY_COUNTER.addAndGet(-capacity);
throw new OutOfDirectMemoryError("failed to allocate " + capacity
+ " byte(s) of direct memory (used: " + (newUsedMemory - capacity)
+ ", max: " + DIRECT_MEMORY_LIMIT + ')');
}
}
}
private static void decrementMemoryCounter(int capacity) {
if (DIRECT_MEMORY_COUNTER != null) {
long usedMemory = DIRECT_MEMORY_COUNTER.addAndGet(-capacity);
assert usedMemory >= 0;
}
}
public static boolean useDirectBufferNoCleaner() {
return USE_DIRECT_BUFFER_NO_CLEANER;
}
/**
* Compare two {@code byte} arrays for equality. For performance reasons no bounds checking on the
* parameters is performed.
*
* @param bytes1 the first byte array.
* @param startPos1 the position (inclusive) to start comparing in {@code bytes1}.
* @param bytes2 the second byte array.
* @param startPos2 the position (inclusive) to start comparing in {@code bytes2}.
* @param length the amount of bytes to compare. This is assumed to be validated as not going out of bounds
* by the caller.
*/
public static boolean equals(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
return !hasUnsafe() || !unalignedAccess() ?
equalsSafe(bytes1, startPos1, bytes2, startPos2, length) :
PlatformDependent0.equals(bytes1, startPos1, bytes2, startPos2, length);
}
/**
* Determine if a subsection of an array is zero.
* @param bytes The byte array.
* @param startPos The starting index (inclusive) in {@code bytes}.
* @param length The amount of bytes to check for zero.
* @return {@code false} if {@code bytes[startPos:startsPos+length)} contains a value other than zero.
*/
public static boolean isZero(byte[] bytes, int startPos, int length) {
return !hasUnsafe() || !unalignedAccess() ?
isZeroSafe(bytes, startPos, length) :
PlatformDependent0.isZero(bytes, startPos, length);
}
/**
* Compare two {@code byte} arrays for equality without leaking timing information.
* For performance reasons no bounds checking on the parameters is performed.
* <p>
* The {@code int} return type is intentional and is designed to allow cascading of constant time operations:
* <pre>
* byte[] s1 = new {1, 2, 3};
* byte[] s2 = new {1, 2, 3};
* byte[] s3 = new {1, 2, 3};
* byte[] s4 = new {4, 5, 6};
* boolean equals = (equalsConstantTime(s1, 0, s2, 0, s1.length) &
* equalsConstantTime(s3, 0, s4, 0, s3.length)) != 0;
* </pre>
* @param bytes1 the first byte array.
* @param startPos1 the position (inclusive) to start comparing in {@code bytes1}.
* @param bytes2 the second byte array.
* @param startPos2 the position (inclusive) to start comparing in {@code bytes2}.
* @param length the amount of bytes to compare. This is assumed to be validated as not going out of bounds
* by the caller.
* @return {@code 0} if not equal. {@code 1} if equal.
*/
public static int equalsConstantTime(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
return !hasUnsafe() || !unalignedAccess() ?
ConstantTimeUtils.equalsConstantTime(bytes1, startPos1, bytes2, startPos2, length) :
PlatformDependent0.equalsConstantTime(bytes1, startPos1, bytes2, startPos2, length);
}
/**
* Calculate a hash code of a byte array assuming ASCII character encoding.
* The resulting hash code will be case insensitive.
* @param bytes The array which contains the data to hash.
* @param startPos What index to start generating a hash code in {@code bytes}
* @param length The amount of bytes that should be accounted for in the computation.
* @return The hash code of {@code bytes} assuming ASCII character encoding.
* The resulting hash code will be case insensitive.
*/
public static int hashCodeAscii(byte[] bytes, int startPos, int length) {
return !hasUnsafe() || !unalignedAccess() ?
hashCodeAsciiSafe(bytes, startPos, length) :
PlatformDependent0.hashCodeAscii(bytes, startPos, length);
}
/**
* Calculate a hash code of a byte array assuming ASCII character encoding.
* The resulting hash code will be case insensitive.
* <p>
* This method assumes that {@code bytes} is equivalent to a {@code byte[]} but just using {@link CharSequence}
* for storage. The upper most byte of each {@code char} from {@code bytes} is ignored.
* @param bytes The array which contains the data to hash (assumed to be equivalent to a {@code byte[]}).
* @return The hash code of {@code bytes} assuming ASCII character encoding.
* The resulting hash code will be case insensitive.
*/
public static int hashCodeAscii(CharSequence bytes) {
final int length = bytes.length();
final int remainingBytes = length & 7;
int hash = HASH_CODE_ASCII_SEED;
// Benchmarking shows that by just naively looping for inputs 8~31 bytes long we incur a relatively large
// performance penalty (only achieve about 60% performance of loop which iterates over each char). So because
// of this we take special provisions to unroll the looping for these conditions.
if (length >= 32) {
for (int i = length - 8; i >= remainingBytes; i -= 8) {
hash = hashCodeAsciiCompute(bytes, i, hash);
}
} else if (length >= 8) {
hash = hashCodeAsciiCompute(bytes, length - 8, hash);
if (length >= 16) {
hash = hashCodeAsciiCompute(bytes, length - 16, hash);
if (length >= 24) {
hash = hashCodeAsciiCompute(bytes, length - 24, hash);
}
}
}
if (remainingBytes == 0) {
return hash;
}
int offset = 0;
if (remainingBytes != 2 & remainingBytes != 4 & remainingBytes != 6) { // 1, 3, 5, 7
hash = hash * HASH_CODE_C1 + hashCodeAsciiSanitizeByte(bytes.charAt(0));
offset = 1;
}
if (remainingBytes != 1 & remainingBytes != 4 & remainingBytes != 5) { // 2, 3, 6, 7
hash = hash * (offset == 0 ? HASH_CODE_C1 : HASH_CODE_C2)
+ hashCodeAsciiSanitize(hashCodeAsciiSanitizeShort(bytes, offset));
offset += 2;
}
if (remainingBytes >= 4) { // 4, 5, 6, 7
return hash * ((offset == 0 | offset == 3) ? HASH_CODE_C1 : HASH_CODE_C2)
+ hashCodeAsciiSanitizeInt(bytes, offset);
}
return hash;
}
private static final class Mpsc {
private static final boolean USE_MPSC_CHUNKED_ARRAY_QUEUE;
private Mpsc() {
}
static {
Object unsafe = null;
if (hasUnsafe()) {
// jctools goes through its own process of initializing unsafe; of
// course, this requires permissions which might not be granted to calling code, so we
// must mark this block as privileged too
unsafe = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
// force JCTools to initialize unsafe
return UnsafeAccess.UNSAFE;
}
});
}
if (unsafe == null) {
logger.debug("org.jctools-core.MpscChunkedArrayQueue: unavailable");
USE_MPSC_CHUNKED_ARRAY_QUEUE = false;
} else {
logger.debug("org.jctools-core.MpscChunkedArrayQueue: available");
USE_MPSC_CHUNKED_ARRAY_QUEUE = true;
}
}
static <T> Queue<T> newMpscQueue(final int maxCapacity) {
// Calculate the max capacity which can not be bigger than MAX_ALLOWED_MPSC_CAPACITY.
// This is forced by the MpscChunkedArrayQueue implementation as will try to round it
// up to the next power of two and so will overflow otherwise.
final int capacity = max(min(maxCapacity, MAX_ALLOWED_MPSC_CAPACITY), MIN_MAX_MPSC_CAPACITY);
return USE_MPSC_CHUNKED_ARRAY_QUEUE ? new MpscChunkedArrayQueue<T>(MPSC_CHUNK_SIZE, capacity)
: new MpscChunkedAtomicArrayQueue<T>(MPSC_CHUNK_SIZE, capacity);
}
static <T> Queue<T> newMpscQueue() {
return USE_MPSC_CHUNKED_ARRAY_QUEUE ? new MpscUnboundedArrayQueue<T>(MPSC_CHUNK_SIZE)
: new MpscUnboundedAtomicArrayQueue<T>(MPSC_CHUNK_SIZE);
}
}
/**
* Create a new {@link Queue} which is safe to use for multiple producers (different threads) and a single
* consumer (one thread!).
* @return A MPSC queue which may be unbounded.
*/
public static <T> Queue<T> newMpscQueue() {
return Mpsc.newMpscQueue();
}
/**
* Create a new {@link Queue} which is safe to use for multiple producers (different threads) and a single
* consumer (one thread!).
*/
public static <T> Queue<T> newMpscQueue(final int maxCapacity) {
return Mpsc.newMpscQueue(maxCapacity);
}
/**
* Create a new {@link Queue} which is safe to use for single producer (one thread!) and a single
* consumer (one thread!).
*/
public static <T> Queue<T> newSpscQueue() {
return hasUnsafe() ? new SpscLinkedQueue<T>() : new SpscLinkedAtomicQueue<T>();
}
/**
* Create a new {@link Queue} which is safe to use for multiple producers (different threads) and a single
* consumer (one thread!) with the given fixes {@code capacity}.
*/
public static <T> Queue<T> newFixedMpscQueue(int capacity) {
return hasUnsafe() ? new MpscArrayQueue<T>(capacity) : new MpscAtomicArrayQueue<T>(capacity);
}
/**
* Return the {@link ClassLoader} for the given {@link Class}.
*/
public static ClassLoader getClassLoader(final Class<?> clazz) {
return PlatformDependent0.getClassLoader(clazz);
}
/**
* Return the context {@link ClassLoader} for the current {@link Thread}.
*/
public static ClassLoader getContextClassLoader() {
return PlatformDependent0.getContextClassLoader();
}
/**
* Return the system {@link ClassLoader}.
*/
public static ClassLoader getSystemClassLoader() {
return PlatformDependent0.getSystemClassLoader();
}
/**
* Returns a new concurrent {@link Deque}.
*/
@SuppressJava6Requirement(reason = "Usage guarded by java version check")
public static <C> Deque<C> newConcurrentDeque() {
if (javaVersion() < 7) {
return new LinkedBlockingDeque<C>();
} else {
return new ConcurrentLinkedDeque<C>();
}
}
/**
* Return a {@link Random} which is not-threadsafe and so can only be used from the same thread.
*/
public static Random threadLocalRandom() {
return RANDOM_PROVIDER.current();
}
private static boolean isWindows0() {
boolean windows = SystemPropertyUtil.get("os.name", "").toLowerCase(Locale.US).contains("win");
if (windows) {
logger.debug("Platform: Windows");
}
return windows;
}
private static boolean isOsx0() {
String osname = SystemPropertyUtil.get("os.name", "").toLowerCase(Locale.US)
.replaceAll("[^a-z0-9]+", "");
boolean osx = osname.startsWith("macosx") || osname.startsWith("osx");
if (osx) {
logger.debug("Platform: MacOS");
}
return osx;
}
private static boolean maybeSuperUser0() {
String username = SystemPropertyUtil.get("user.name");
if (isWindows()) {
return "Administrator".equals(username);
}
// Check for root and toor as some BSDs have a toor user that is basically the same as root.
return "root".equals(username) || "toor".equals(username);
}
private static Throwable unsafeUnavailabilityCause0() {
if (isAndroid()) {
logger.debug("sun.misc.Unsafe: unavailable (Android)");
return new UnsupportedOperationException("sun.misc.Unsafe: unavailable (Android)");
}
if (isIkvmDotNet()) {
logger.debug("sun.misc.Unsafe: unavailable (IKVM.NET)");
return new UnsupportedOperationException("sun.misc.Unsafe: unavailable (IKVM.NET)");
}
Throwable cause = PlatformDependent0.getUnsafeUnavailabilityCause();
if (cause != null) {
return cause;
}
try {
boolean hasUnsafe = PlatformDependent0.hasUnsafe();
logger.debug("sun.misc.Unsafe: {}", hasUnsafe ? "available" : "unavailable");
return hasUnsafe ? null : PlatformDependent0.getUnsafeUnavailabilityCause();
} catch (Throwable t) {
logger.trace("Could not determine if Unsafe is available", t);
// Probably failed to initialize PlatformDependent0.
return new UnsupportedOperationException("Could not determine if Unsafe is available", t);
}
}
/**
* Returns {@code true} if the running JVM is either <a href="https://developer.ibm.com/javasdk/">IBM J9</a> or
* <a href="https://www.eclipse.org/openj9/">Eclipse OpenJ9</a>, {@code false} otherwise.
*/
public static boolean isJ9Jvm() {
return IS_J9_JVM;
}
private static boolean isJ9Jvm0() {
String vmName = SystemPropertyUtil.get("java.vm.name", "").toLowerCase();
return vmName.startsWith("ibm j9") || vmName.startsWith("eclipse openj9");
}
/**
* Returns {@code true} if the running JVM is <a href="https://www.ikvm.net">IKVM.NET</a>, {@code false} otherwise.
*/
public static boolean isIkvmDotNet() {
return IS_IVKVM_DOT_NET;
}
private static boolean isIkvmDotNet0() {
String vmName = SystemPropertyUtil.get("java.vm.name", "").toUpperCase(Locale.US);
return vmName.equals("IKVM.NET");
}
private static long maxDirectMemory0() {
long maxDirectMemory = 0;
ClassLoader systemClassLoader = null;
try {
systemClassLoader = getSystemClassLoader();
// When using IBM J9 / Eclipse OpenJ9 we should not use VM.maxDirectMemory() as it not reflects the
// correct value.
// See:
// - https://github.com/netty/netty/issues/7654
String vmName = SystemPropertyUtil.get("java.vm.name", "").toLowerCase();
if (!vmName.startsWith("ibm j9") &&
// https://github.com/eclipse/openj9/blob/openj9-0.8.0/runtime/include/vendor_version.h#L53
!vmName.startsWith("eclipse openj9")) {
// Try to get from sun.misc.VM.maxDirectMemory() which should be most accurate.
Class<?> vmClass = Class.forName("sun.misc.VM", true, systemClassLoader);
Method m = vmClass.getDeclaredMethod("maxDirectMemory");
maxDirectMemory = ((Number) m.invoke(null)).longValue();
}
} catch (Throwable ignored) {
// Ignore
}
if (maxDirectMemory > 0) {
return maxDirectMemory;
}
try {
// Now try to get the JVM option (-XX:MaxDirectMemorySize) and parse it.
// Note that we are using reflection because Android doesn't have these classes.
Class<?> mgmtFactoryClass = Class.forName(
"java.lang.management.ManagementFactory", true, systemClassLoader);
Class<?> runtimeClass = Class.forName(
"java.lang.management.RuntimeMXBean", true, systemClassLoader);
Object runtime = mgmtFactoryClass.getDeclaredMethod("getRuntimeMXBean").invoke(null);
@SuppressWarnings("unchecked")
List<String> vmArgs = (List<String>) runtimeClass.getDeclaredMethod("getInputArguments").invoke(runtime);
for (int i = vmArgs.size() - 1; i >= 0; i --) {
Matcher m = MAX_DIRECT_MEMORY_SIZE_ARG_PATTERN.matcher(vmArgs.get(i));
if (!m.matches()) {
continue;
}
maxDirectMemory = Long.parseLong(m.group(1));
switch (m.group(2).charAt(0)) {
case 'k': case 'K':
maxDirectMemory *= 1024;
break;
case 'm': case 'M':
maxDirectMemory *= 1024 * 1024;
break;
case 'g': case 'G':
maxDirectMemory *= 1024 * 1024 * 1024;
break;
default:
break;
}
break;
}
} catch (Throwable ignored) {
// Ignore
}
if (maxDirectMemory <= 0) {
maxDirectMemory = Runtime.getRuntime().maxMemory();
logger.debug("maxDirectMemory: {} bytes (maybe)", maxDirectMemory);
} else {
logger.debug("maxDirectMemory: {} bytes", maxDirectMemory);
}
return maxDirectMemory;
}
private static File tmpdir0() {
File f;
try {
f = toDirectory(SystemPropertyUtil.get("io.netty.tmpdir"));
if (f != null) {
logger.debug("-Dio.netty.tmpdir: {}", f);
return f;
}
f = toDirectory(SystemPropertyUtil.get("java.io.tmpdir"));
if (f != null) {
logger.debug("-Dio.netty.tmpdir: {} (java.io.tmpdir)", f);
return f;
}
// This shouldn't happen, but just in case ..
if (isWindows()) {
f = toDirectory(System.getenv("TEMP"));
if (f != null) {
logger.debug("-Dio.netty.tmpdir: {} (%TEMP%)", f);
return f;
}
String userprofile = System.getenv("USERPROFILE");
if (userprofile != null) {
f = toDirectory(userprofile + "\\AppData\\Local\\Temp");
if (f != null) {
logger.debug("-Dio.netty.tmpdir: {} (%USERPROFILE%\\AppData\\Local\\Temp)", f);
return f;
}
f = toDirectory(userprofile + "\\Local Settings\\Temp");
if (f != null) {
logger.debug("-Dio.netty.tmpdir: {} (%USERPROFILE%\\Local Settings\\Temp)", f);
return f;
}
}
} else {
f = toDirectory(System.getenv("TMPDIR"));
if (f != null) {
logger.debug("-Dio.netty.tmpdir: {} ($TMPDIR)", f);
return f;
}
}
} catch (Throwable ignored) {
// Environment variable inaccessible
}
// Last resort.
if (isWindows()) {
f = new File("C:\\Windows\\Temp");
} else {
f = new File("/tmp");
}
logger.warn("Failed to get the temporary directory; falling back to: {}", f);
return f;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static File toDirectory(String path) {
if (path == null) {
return null;
}
File f = new File(path);
f.mkdirs();
if (!f.isDirectory()) {
return null;
}
try {
return f.getAbsoluteFile();
} catch (Exception ignored) {
return f;
}
}
private static int bitMode0() {
// Check user-specified bit mode first.
int bitMode = SystemPropertyUtil.getInt("io.netty.bitMode", 0);
if (bitMode > 0) {
logger.debug("-Dio.netty.bitMode: {}", bitMode);
return bitMode;
}
// And then the vendor specific ones which is probably most reliable.
bitMode = SystemPropertyUtil.getInt("sun.arch.data.model", 0);
if (bitMode > 0) {
logger.debug("-Dio.netty.bitMode: {} (sun.arch.data.model)", bitMode);
return bitMode;
}
bitMode = SystemPropertyUtil.getInt("com.ibm.vm.bitmode", 0);
if (bitMode > 0) {
logger.debug("-Dio.netty.bitMode: {} (com.ibm.vm.bitmode)", bitMode);
return bitMode;
}
// os.arch also gives us a good hint.
String arch = SystemPropertyUtil.get("os.arch", "").toLowerCase(Locale.US).trim();
if ("amd64".equals(arch) || "x86_64".equals(arch)) {
bitMode = 64;
} else if ("i386".equals(arch) || "i486".equals(arch) || "i586".equals(arch) || "i686".equals(arch)) {
bitMode = 32;
}
if (bitMode > 0) {
logger.debug("-Dio.netty.bitMode: {} (os.arch: {})", bitMode, arch);
}
// Last resort: guess from VM name and then fall back to most common 64-bit mode.
String vm = SystemPropertyUtil.get("java.vm.name", "").toLowerCase(Locale.US);
Pattern bitPattern = Pattern.compile("([1-9][0-9]+)-?bit");
Matcher m = bitPattern.matcher(vm);
if (m.find()) {
return Integer.parseInt(m.group(1));
} else {
return 64;
}
}
private static int addressSize0() {
if (!hasUnsafe()) {
return -1;
}
return PlatformDependent0.addressSize();
}
private static long byteArrayBaseOffset0() {
if (!hasUnsafe()) {
return -1;
}
return PlatformDependent0.byteArrayBaseOffset();
}
private static boolean equalsSafe(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
final int end = startPos1 + length;
for (; startPos1 < end; ++startPos1, ++startPos2) {
if (bytes1[startPos1] != bytes2[startPos2]) {
return false;
}
}
return true;
}
private static boolean isZeroSafe(byte[] bytes, int startPos, int length) {
final int end = startPos + length;
for (; startPos < end; ++startPos) {
if (bytes[startPos] != 0) {
return false;
}
}
return true;
}
/**
* Package private for testing purposes only!
*/
static int hashCodeAsciiSafe(byte[] bytes, int startPos, int length) {
int hash = HASH_CODE_ASCII_SEED;
final int remainingBytes = length & 7;
final int end = startPos + remainingBytes;
for (int i = startPos - 8 + length; i >= end; i -= 8) {
hash = PlatformDependent0.hashCodeAsciiCompute(getLongSafe(bytes, i), hash);
}
switch(remainingBytes) {
case 7:
return ((hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]))
* HASH_CODE_C2 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos + 1)))
* HASH_CODE_C1 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos + 3));
case 6:
return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos)))
* HASH_CODE_C2 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos + 2));
case 5:
return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]))
* HASH_CODE_C2 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos + 1));
case 4:
return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos));
case 3:
return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]))
* HASH_CODE_C2 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos + 1));
case 2:
return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos));
case 1:
return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]);
default:
return hash;
}
}
public static String normalizedArch() {
return NORMALIZED_ARCH;
}
public static String normalizedOs() {
return NORMALIZED_OS;
}
public static Set<String> normalizedLinuxClassifiers() {
return LINUX_OS_CLASSIFIERS;
}
/**
* Adds only those classifier strings to <tt>dest</tt> which are present in <tt>allowed</tt>.
*
* @param allowed allowed classifiers
* @param dest destination set
* @param maybeClassifiers potential classifiers to add
*/
private static void addClassifier(Set<String> allowed, Set<String> dest, String... maybeClassifiers) {
for (String id : maybeClassifiers) {
if (allowed.contains(id)) {
dest.add(id);
}
}
}
private static String normalizeOsReleaseVariableValue(String value) {
// Variable assignment values may be enclosed in double or single quotes.
return value.trim().replaceAll("[\"']", "");
}
private static String normalize(String value) {
return value.toLowerCase(Locale.US).replaceAll("[^a-z0-9]+", "");
}
private static String normalizeArch(String value) {
value = normalize(value);
if (value.matches("^(x8664|amd64|ia32e|em64t|x64)$")) {
return "x86_64";
}
if (value.matches("^(x8632|x86|i[3-6]86|ia32|x32)$")) {
return "x86_32";
}
if (value.matches("^(ia64|itanium64)$")) {
return "itanium_64";
}
if (value.matches("^(sparc|sparc32)$")) {
return "sparc_32";
}
if (value.matches("^(sparcv9|sparc64)$")) {
return "sparc_64";
}
if (value.matches("^(arm|arm32)$")) {
return "arm_32";
}
if ("aarch64".equals(value)) {
return "aarch_64";
}
if (value.matches("^(ppc|ppc32)$")) {
return "ppc_32";
}
if ("ppc64".equals(value)) {
return "ppc_64";
}
if ("ppc64le".equals(value)) {
return "ppcle_64";
}
if ("s390".equals(value)) {
return "s390_32";
}
if ("s390x".equals(value)) {
return "s390_64";
}
return "unknown";
}
private static String normalizeOs(String value) {
value = normalize(value);
if (value.startsWith("aix")) {
return "aix";
}
if (value.startsWith("hpux")) {
return "hpux";
}
if (value.startsWith("os400")) {
// Avoid the names such as os4000
if (value.length() <= 5 || !Character.isDigit(value.charAt(5))) {
return "os400";
}
}
if (value.startsWith("linux")) {
return "linux";
}
if (value.startsWith("macosx") || value.startsWith("osx")) {
return "osx";
}
if (value.startsWith("freebsd")) {
return "freebsd";
}
if (value.startsWith("openbsd")) {
return "openbsd";
}
if (value.startsWith("netbsd")) {
return "netbsd";
}
if (value.startsWith("solaris") || value.startsWith("sunos")) {
return "sunos";
}
if (value.startsWith("windows")) {
return "windows";
}
return "unknown";
}
private static final class AtomicLongCounter extends AtomicLong implements LongCounter {
private static final long serialVersionUID = 4074772784610639305L;
@Override
public void add(long delta) {
addAndGet(delta);
}
@Override
public void increment() {
incrementAndGet();
}
@Override
public void decrement() {
decrementAndGet();
}
@Override
public long value() {
return get();
}
}
private interface ThreadLocalRandomProvider {
Random current();
}
private PlatformDependent() {
// only static method supported
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_8 |
crossvul-java_data_good_1927_13 | /*
* Copyright 2015 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 io.netty.channel.epoll;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.unix.FileDescriptor;
import io.netty.util.NetUtil;
import io.netty.util.internal.PlatformDependent;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
public class EpollSpliceTest {
private static final int SPLICE_LEN = 32 * 1024;
private static final Random random = new Random();
private static final byte[] data = new byte[1048576];
static {
random.nextBytes(data);
}
@Test
public void spliceToSocket() throws Throwable {
final EchoHandler sh = new EchoHandler();
final EchoHandler ch = new EchoHandler();
EventLoopGroup group = new EpollEventLoopGroup(1);
ServerBootstrap bs = new ServerBootstrap();
bs.channel(EpollServerSocketChannel.class);
bs.group(group).childHandler(sh);
final Channel sc = bs.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel();
ServerBootstrap bs2 = new ServerBootstrap();
bs2.channel(EpollServerSocketChannel.class);
bs2.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
bs2.group(group).childHandler(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
ctx.channel().config().setAutoRead(false);
Bootstrap bs = new Bootstrap();
bs.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
bs.channel(EpollSocketChannel.class);
bs.group(ctx.channel().eventLoop()).handler(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(ChannelHandlerContext context) throws Exception {
final EpollSocketChannel ch = (EpollSocketChannel) ctx.channel();
final EpollSocketChannel ch2 = (EpollSocketChannel) context.channel();
// We are splicing two channels together, at this point we have a tcp proxy which handles all
// the data transfer only in kernel space!
// Integer.MAX_VALUE will splice infinitly.
ch.spliceTo(ch2, Integer.MAX_VALUE).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
future.channel().close();
}
}
});
// Trigger multiple splices to see if partial splicing works as well.
ch2.spliceTo(ch, SPLICE_LEN).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
future.channel().close();
} else {
ch2.spliceTo(ch, SPLICE_LEN).addListener(this);
}
}
});
ctx.channel().config().setAutoRead(true);
}
@Override
public void channelInactive(ChannelHandlerContext context) throws Exception {
context.close();
}
});
bs.connect(sc.localAddress()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
ctx.close();
} else {
future.channel().closeFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
ctx.close();
}
});
}
}
});
}
});
Channel pc = bs2.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel();
Bootstrap cb = new Bootstrap();
cb.group(group);
cb.channel(EpollSocketChannel.class);
cb.handler(ch);
Channel cc = cb.connect(pc.localAddress()).syncUninterruptibly().channel();
for (int i = 0; i < data.length;) {
int length = Math.min(random.nextInt(1024 * 64), data.length - i);
ByteBuf buf = Unpooled.wrappedBuffer(data, i, length);
cc.writeAndFlush(buf);
i += length;
}
while (ch.counter < data.length) {
if (sh.exception.get() != null) {
break;
}
if (ch.exception.get() != null) {
break;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore.
}
}
while (sh.counter < data.length) {
if (sh.exception.get() != null) {
break;
}
if (ch.exception.get() != null) {
break;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore.
}
}
sh.channel.close().sync();
ch.channel.close().sync();
sc.close().sync();
pc.close().sync();
group.shutdownGracefully();
if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
throw sh.exception.get();
}
if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
throw ch.exception.get();
}
if (sh.exception.get() != null) {
throw sh.exception.get();
}
if (ch.exception.get() != null) {
throw ch.exception.get();
}
}
@Test(timeout = 10000)
public void spliceToFile() throws Throwable {
EventLoopGroup group = new EpollEventLoopGroup(1);
File file = PlatformDependent.createTempFile("netty-splice", null, null);
file.deleteOnExit();
SpliceHandler sh = new SpliceHandler(file);
ServerBootstrap bs = new ServerBootstrap();
bs.channel(EpollServerSocketChannel.class);
bs.group(group).childHandler(sh);
bs.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
Channel sc = bs.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel();
Bootstrap cb = new Bootstrap();
cb.group(group);
cb.channel(EpollSocketChannel.class);
cb.handler(new ChannelInboundHandlerAdapter());
Channel cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
for (int i = 0; i < data.length;) {
int length = Math.min(random.nextInt(1024 * 64), data.length - i);
ByteBuf buf = Unpooled.wrappedBuffer(data, i, length);
cc.writeAndFlush(buf);
i += length;
}
while (sh.future2 == null || !sh.future2.isDone() || !sh.future.isDone()) {
if (sh.exception.get() != null) {
break;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore.
}
}
sc.close().sync();
cc.close().sync();
if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
throw sh.exception.get();
}
byte[] written = new byte[data.length];
FileInputStream in = new FileInputStream(file);
try {
Assert.assertEquals(written.length, in.read(written));
Assert.assertArrayEquals(data, written);
} finally {
in.close();
group.shutdownGracefully();
}
}
private static class EchoHandler extends SimpleChannelInboundHandler<ByteBuf> {
volatile Channel channel;
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
volatile int counter;
@Override
public void channelActive(ChannelHandlerContext ctx)
throws Exception {
channel = ctx.channel();
}
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
byte[] actual = new byte[in.readableBytes()];
in.readBytes(actual);
int lastIdx = counter;
for (int i = 0; i < actual.length; i ++) {
assertEquals(data[i + lastIdx], actual[i]);
}
if (channel.parent() != null) {
channel.write(Unpooled.wrappedBuffer(actual));
}
counter += actual.length;
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) throws Exception {
if (exception.compareAndSet(null, cause)) {
cause.printStackTrace();
ctx.close();
}
}
}
private static class SpliceHandler extends ChannelInboundHandlerAdapter {
private final File file;
volatile ChannelFuture future;
volatile ChannelFuture future2;
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
SpliceHandler(File file) {
this.file = file;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
final EpollSocketChannel ch = (EpollSocketChannel) ctx.channel();
final FileDescriptor fd = FileDescriptor.from(file);
// splice two halves separately to test starting offset
future = ch.spliceTo(fd, 0, data.length / 2);
future2 = ch.spliceTo(fd, data.length / 2, data.length / 2);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) throws Exception {
if (exception.compareAndSet(null, cause)) {
cause.printStackTrace();
ctx.close();
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_13 |
crossvul-java_data_bad_1927_5 | /*
* Copyright 2012 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 io.netty.handler.codec.http.multipart;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;
import java.util.UUID;
import static io.netty.util.CharsetUtil.*;
import static org.junit.Assert.*;
/** {@link AbstractMemoryHttpData} test cases. */
public class AbstractMemoryHttpDataTest {
@Test
public void testSetContentFromFile() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] bytes = new byte[4096];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
test.setContent(tmpFile);
ByteBuf buf = test.getByteBuf();
assertEquals(buf.readerIndex(), 0);
assertEquals(buf.writerIndex(), bytes.length);
assertArrayEquals(bytes, test.get());
assertArrayEquals(bytes, ByteBufUtil.getBytes(buf));
} finally {
//release the ByteBuf
test.delete();
}
}
@Test
public void testRenameTo() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
tmpFile.deleteOnExit();
final int totalByteCount = 4096;
byte[] bytes = new byte[totalByteCount];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ByteBuf content = Unpooled.wrappedBuffer(bytes);
test.setContent(content);
boolean succ = test.renameTo(tmpFile);
assertTrue(succ);
FileInputStream fis = new FileInputStream(tmpFile);
try {
byte[] buf = new byte[totalByteCount];
int count = 0;
int offset = 0;
int size = totalByteCount;
while ((count = fis.read(buf, offset, size)) > 0) {
offset += count;
size -= count;
if (offset >= totalByteCount || size <= 0) {
break;
}
}
assertArrayEquals(bytes, buf);
assertEquals(0, fis.available());
} finally {
fis.close();
}
} finally {
//release the ByteBuf in AbstractMemoryHttpData
test.delete();
}
}
/**
* Provide content into HTTP data with input stream.
*
* @throws Exception In case of any exception.
*/
@Test
public void testSetContentFromStream() throws Exception {
// definedSize=0
TestHttpData test = new TestHttpData("test", UTF_8, 0);
String contentStr = "foo_test";
ByteBuf buf = Unpooled.wrappedBuffer(contentStr.getBytes(UTF_8));
buf.markReaderIndex();
ByteBufInputStream is = new ByteBufInputStream(buf);
try {
test.setContent(is);
assertFalse(buf.isReadable());
assertEquals(test.getString(UTF_8), contentStr);
buf.resetReaderIndex();
assertTrue(ByteBufUtil.equals(buf, test.getByteBuf()));
} finally {
is.close();
}
Random random = new SecureRandom();
for (int i = 0; i < 20; i++) {
// Generate input data bytes.
int size = random.nextInt(Short.MAX_VALUE);
byte[] bytes = new byte[size];
random.nextBytes(bytes);
// Generate parsed HTTP data block.
TestHttpData data = new TestHttpData("name", UTF_8, 0);
data.setContent(new ByteArrayInputStream(bytes));
// Validate stored data.
ByteBuf buffer = data.getByteBuf();
assertEquals(0, buffer.readerIndex());
assertEquals(bytes.length, buffer.writerIndex());
assertArrayEquals(bytes, Arrays.copyOf(buffer.array(), bytes.length));
assertArrayEquals(bytes, data.get());
}
}
/** Memory-based HTTP data implementation for test purposes. */
private static final class TestHttpData extends AbstractMemoryHttpData {
/**
* Constructs HTTP data for tests.
*
* @param name Name of parsed data block.
* @param charset Used charset for data decoding.
* @param size Expected data block size.
*/
private TestHttpData(String name, Charset charset, long size) {
super(name, charset, size);
}
@Override
public InterfaceHttpData.HttpDataType getHttpDataType() {
throw reject();
}
@Override
public HttpData copy() {
throw reject();
}
@Override
public HttpData duplicate() {
throw reject();
}
@Override
public HttpData retainedDuplicate() {
throw reject();
}
@Override
public HttpData replace(ByteBuf content) {
return null;
}
@Override
public int compareTo(InterfaceHttpData o) {
throw reject();
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
private static UnsupportedOperationException reject() {
throw new UnsupportedOperationException("Should never be called.");
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_5 |
crossvul-java_data_bad_1927_6 | /*
* Copyright 2016 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 io.netty.handler.codec.http.multipart;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class DiskFileUploadTest {
@Test
public void testSpecificCustomBaseDir() throws IOException {
File baseDir = new File("target/DiskFileUploadTest/testSpecificCustomBaseDir");
baseDir.mkdirs(); // we don't need to clean it since it is in volatile files anyway
DiskFileUpload f =
new DiskFileUpload("d1", "d1", "application/json", null, null, 100,
baseDir.getAbsolutePath(), false);
f.setContent(Unpooled.EMPTY_BUFFER);
assertTrue(f.getFile().getAbsolutePath().startsWith(baseDir.getAbsolutePath()));
assertTrue(f.getFile().exists());
assertEquals(0, f.getFile().length());
f.delete();
}
@Test
public final void testDiskFileUploadEquals() {
DiskFileUpload f2 =
new DiskFileUpload("d1", "d1", "application/json", null, null, 100);
assertEquals(f2, f2);
f2.delete();
}
@Test
public void testEmptyBufferSetMultipleTimes() throws IOException {
DiskFileUpload f =
new DiskFileUpload("d1", "d1", "application/json", null, null, 100);
f.setContent(Unpooled.EMPTY_BUFFER);
assertTrue(f.getFile().exists());
assertEquals(0, f.getFile().length());
f.setContent(Unpooled.EMPTY_BUFFER);
assertTrue(f.getFile().exists());
assertEquals(0, f.getFile().length());
f.delete();
}
@Test
public void testEmptyBufferSetAfterNonEmptyBuffer() throws IOException {
DiskFileUpload f =
new DiskFileUpload("d1", "d1", "application/json", null, null, 100);
f.setContent(Unpooled.wrappedBuffer(new byte[] { 1, 2, 3, 4 }));
assertTrue(f.getFile().exists());
assertEquals(4, f.getFile().length());
f.setContent(Unpooled.EMPTY_BUFFER);
assertTrue(f.getFile().exists());
assertEquals(0, f.getFile().length());
f.delete();
}
@Test
public void testNonEmptyBufferSetMultipleTimes() throws IOException {
DiskFileUpload f =
new DiskFileUpload("d1", "d1", "application/json", null, null, 100);
f.setContent(Unpooled.wrappedBuffer(new byte[] { 1, 2, 3, 4 }));
assertTrue(f.getFile().exists());
assertEquals(4, f.getFile().length());
f.setContent(Unpooled.wrappedBuffer(new byte[] { 1, 2}));
assertTrue(f.getFile().exists());
assertEquals(2, f.getFile().length());
f.delete();
}
@Test
public void testAddContents() throws Exception {
DiskFileUpload f1 = new DiskFileUpload("file1", "file1", "application/json", null, null, 0);
try {
byte[] jsonBytes = new byte[4096];
PlatformDependent.threadLocalRandom().nextBytes(jsonBytes);
f1.addContent(Unpooled.wrappedBuffer(jsonBytes, 0, 1024), false);
f1.addContent(Unpooled.wrappedBuffer(jsonBytes, 1024, jsonBytes.length - 1024), true);
assertArrayEquals(jsonBytes, f1.get());
File file = f1.getFile();
assertEquals(jsonBytes.length, file.length());
FileInputStream fis = new FileInputStream(file);
try {
byte[] buf = new byte[jsonBytes.length];
int offset = 0;
int read = 0;
int len = buf.length;
while ((read = fis.read(buf, offset, len)) > 0) {
len -= read;
offset += read;
if (len <= 0 || offset >= buf.length) {
break;
}
}
assertArrayEquals(jsonBytes, buf);
} finally {
fis.close();
}
} finally {
f1.delete();
}
}
@Test
public void testSetContentFromByteBuf() throws Exception {
DiskFileUpload f1 = new DiskFileUpload("file2", "file2", "application/json", null, null, 0);
try {
String json = "{\"hello\":\"world\"}";
byte[] bytes = json.getBytes(CharsetUtil.UTF_8);
f1.setContent(Unpooled.wrappedBuffer(bytes));
assertEquals(json, f1.getString());
assertArrayEquals(bytes, f1.get());
File file = f1.getFile();
assertEquals((long) bytes.length, file.length());
assertArrayEquals(bytes, doReadFile(file, bytes.length));
} finally {
f1.delete();
}
}
@Test
public void testSetContentFromInputStream() throws Exception {
String json = "{\"hello\":\"world\",\"foo\":\"bar\"}";
DiskFileUpload f1 = new DiskFileUpload("file3", "file3", "application/json", null, null, 0);
try {
byte[] bytes = json.getBytes(CharsetUtil.UTF_8);
ByteBuf buf = Unpooled.wrappedBuffer(bytes);
InputStream is = new ByteBufInputStream(buf);
try {
f1.setContent(is);
assertEquals(json, f1.getString());
assertArrayEquals(bytes, f1.get());
File file = f1.getFile();
assertEquals((long) bytes.length, file.length());
assertArrayEquals(bytes, doReadFile(file, bytes.length));
} finally {
buf.release();
is.close();
}
} finally {
f1.delete();
}
}
@Test
public void testAddContentFromByteBuf() throws Exception {
testAddContentFromByteBuf0(false);
}
@Test
public void testAddContentFromCompositeByteBuf() throws Exception {
testAddContentFromByteBuf0(true);
}
private static void testAddContentFromByteBuf0(boolean composite) throws Exception {
DiskFileUpload f1 = new DiskFileUpload("file3", "file3", "application/json", null, null, 0);
try {
byte[] bytes = new byte[4096];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
final ByteBuf buffer;
if (composite) {
buffer = Unpooled.compositeBuffer()
.addComponent(true, Unpooled.wrappedBuffer(bytes, 0 , bytes.length / 2))
.addComponent(true, Unpooled.wrappedBuffer(bytes, bytes.length / 2, bytes.length / 2));
} else {
buffer = Unpooled.wrappedBuffer(bytes);
}
f1.addContent(buffer, true);
ByteBuf buf = f1.getByteBuf();
assertEquals(buf.readerIndex(), 0);
assertEquals(buf.writerIndex(), bytes.length);
assertArrayEquals(bytes, ByteBufUtil.getBytes(buf));
} finally {
//release the ByteBuf
f1.delete();
}
}
private static byte[] doReadFile(File file, int maxRead) throws Exception {
FileInputStream fis = new FileInputStream(file);
try {
byte[] buf = new byte[maxRead];
int offset = 0;
int read = 0;
int len = buf.length;
while ((read = fis.read(buf, offset, len)) > 0) {
len -= read;
offset += read;
if (len <= 0 || offset >= buf.length) {
break;
}
}
return buf;
} finally {
fis.close();
}
}
@Test
public void testDelete() throws Exception {
String json = "{\"foo\":\"bar\"}";
byte[] bytes = json.getBytes(CharsetUtil.UTF_8);
File tmpFile = null;
DiskFileUpload f1 = new DiskFileUpload("file4", "file4", "application/json", null, null, 0);
try {
assertNull(f1.getFile());
f1.setContent(Unpooled.wrappedBuffer(bytes));
assertNotNull(tmpFile = f1.getFile());
} finally {
f1.delete();
assertNull(f1.getFile());
assertNotNull(tmpFile);
assertFalse(tmpFile.exists());
}
}
@Test
public void setSetContentFromFileExceptionally() throws Exception {
final long maxSize = 4;
DiskFileUpload f1 = new DiskFileUpload("file5", "file5", "application/json", null, null, 0);
f1.setMaxSize(maxSize);
try {
f1.setContent(Unpooled.wrappedBuffer(new byte[(int) maxSize]));
File originalFile = f1.getFile();
assertNotNull(originalFile);
assertEquals(maxSize, originalFile.length());
assertEquals(maxSize, f1.length());
byte[] bytes = new byte[8];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpFile);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
try {
f1.setContent(tmpFile);
fail("should not reach here!");
} catch (IOException e) {
assertNotNull(f1.getFile());
assertEquals(originalFile, f1.getFile());
assertEquals(maxSize, f1.length());
}
} finally {
f1.delete();
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_6 |
crossvul-java_data_good_1927_9 | /*
* 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 io.netty.handler.ssl.util;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.base64.Base64;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.ThrowableUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Date;
/**
* Generates a temporary self-signed certificate for testing purposes.
* <p>
* <strong>NOTE:</strong>
* Never use the certificate and private key generated by this class in production.
* It is purely for testing purposes, and thus it is very insecure.
* It even uses an insecure pseudo-random generator for faster generation internally.
* </p><p>
* An X.509 certificate file and a EC/RSA private key file are generated in a system's temporary directory using
* {@link java.io.File#createTempFile(String, String)}, and they are deleted when the JVM exits using
* {@link java.io.File#deleteOnExit()}.
* </p><p>
* At first, this method tries to use OpenJDK's X.509 implementation (the {@code sun.security.x509} package).
* If it fails, it tries to use <a href="https://www.bouncycastle.org/">Bouncy Castle</a> as a fallback.
* </p>
*/
public final class SelfSignedCertificate {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SelfSignedCertificate.class);
/** Current time minus 1 year, just in case software clock goes back due to time synchronization */
private static final Date DEFAULT_NOT_BEFORE = new Date(SystemPropertyUtil.getLong(
"io.netty.selfSignedCertificate.defaultNotBefore", System.currentTimeMillis() - 86400000L * 365));
/** The maximum possible value in X.509 specification: 9999-12-31 23:59:59 */
private static final Date DEFAULT_NOT_AFTER = new Date(SystemPropertyUtil.getLong(
"io.netty.selfSignedCertificate.defaultNotAfter", 253402300799000L));
/**
* FIPS 140-2 encryption requires the RSA key length to be 2048 bits or greater.
* Let's use that as a sane default but allow the default to be set dynamically
* for those that need more stringent security requirements.
*/
private static final int DEFAULT_KEY_LENGTH_BITS =
SystemPropertyUtil.getInt("io.netty.handler.ssl.util.selfSignedKeyStrength", 2048);
private final File certificate;
private final File privateKey;
private final X509Certificate cert;
private final PrivateKey key;
/**
* Creates a new instance.
* <p> Algorithm: RSA </p>
*/
public SelfSignedCertificate() throws CertificateException {
this(DEFAULT_NOT_BEFORE, DEFAULT_NOT_AFTER, "RSA", DEFAULT_KEY_LENGTH_BITS);
}
/**
* Creates a new instance.
* <p> Algorithm: RSA </p>
*
* @param notBefore Certificate is not valid before this time
* @param notAfter Certificate is not valid after this time
*/
public SelfSignedCertificate(Date notBefore, Date notAfter)
throws CertificateException {
this("localhost", notBefore, notAfter, "RSA", DEFAULT_KEY_LENGTH_BITS);
}
/**
* Creates a new instance.
*
* @param notBefore Certificate is not valid before this time
* @param notAfter Certificate is not valid after this time
* @param algorithm Key pair algorithm
* @param bits the number of bits of the generated private key
*/
public SelfSignedCertificate(Date notBefore, Date notAfter, String algorithm, int bits)
throws CertificateException {
this("localhost", notBefore, notAfter, algorithm, bits);
}
/**
* Creates a new instance.
* <p> Algorithm: RSA </p>
*
* @param fqdn a fully qualified domain name
*/
public SelfSignedCertificate(String fqdn) throws CertificateException {
this(fqdn, DEFAULT_NOT_BEFORE, DEFAULT_NOT_AFTER, "RSA", DEFAULT_KEY_LENGTH_BITS);
}
/**
* Creates a new instance.
*
* @param fqdn a fully qualified domain name
* @param algorithm Key pair algorithm
* @param bits the number of bits of the generated private key
*/
public SelfSignedCertificate(String fqdn, String algorithm, int bits) throws CertificateException {
this(fqdn, DEFAULT_NOT_BEFORE, DEFAULT_NOT_AFTER, algorithm, bits);
}
/**
* Creates a new instance.
* <p> Algorithm: RSA </p>
*
* @param fqdn a fully qualified domain name
* @param notBefore Certificate is not valid before this time
* @param notAfter Certificate is not valid after this time
*/
public SelfSignedCertificate(String fqdn, Date notBefore, Date notAfter) throws CertificateException {
// Bypass entropy collection by using insecure random generator.
// We just want to generate it without any delay because it's for testing purposes only.
this(fqdn, ThreadLocalInsecureRandom.current(), DEFAULT_KEY_LENGTH_BITS, notBefore, notAfter, "RSA");
}
/**
* Creates a new instance.
*
* @param fqdn a fully qualified domain name
* @param notBefore Certificate is not valid before this time
* @param notAfter Certificate is not valid after this time
* @param algorithm Key pair algorithm
* @param bits the number of bits of the generated private key
*/
public SelfSignedCertificate(String fqdn, Date notBefore, Date notAfter, String algorithm, int bits)
throws CertificateException {
// Bypass entropy collection by using insecure random generator.
// We just want to generate it without any delay because it's for testing purposes only.
this(fqdn, ThreadLocalInsecureRandom.current(), bits, notBefore, notAfter, algorithm);
}
/**
* Creates a new instance.
* <p> Algorithm: RSA </p>
*
* @param fqdn a fully qualified domain name
* @param random the {@link SecureRandom} to use
* @param bits the number of bits of the generated private key
*/
public SelfSignedCertificate(String fqdn, SecureRandom random, int bits)
throws CertificateException {
this(fqdn, random, bits, DEFAULT_NOT_BEFORE, DEFAULT_NOT_AFTER, "RSA");
}
/**
* Creates a new instance.
*
* @param fqdn a fully qualified domain name
* @param random the {@link SecureRandom} to use
* @param algorithm Key pair algorithm
* @param bits the number of bits of the generated private key
*/
public SelfSignedCertificate(String fqdn, SecureRandom random, String algorithm, int bits)
throws CertificateException {
this(fqdn, random, bits, DEFAULT_NOT_BEFORE, DEFAULT_NOT_AFTER, algorithm);
}
/**
* Creates a new instance.
* <p> Algorithm: RSA </p>
*
* @param fqdn a fully qualified domain name
* @param random the {@link SecureRandom} to use
* @param bits the number of bits of the generated private key
* @param notBefore Certificate is not valid before this time
* @param notAfter Certificate is not valid after this time
*/
public SelfSignedCertificate(String fqdn, SecureRandom random, int bits, Date notBefore, Date notAfter)
throws CertificateException {
this(fqdn, random, bits, notBefore, notAfter, "RSA");
}
/**
* Creates a new instance.
*
* @param fqdn a fully qualified domain name
* @param random the {@link SecureRandom} to use
* @param bits the number of bits of the generated private key
* @param notBefore Certificate is not valid before this time
* @param notAfter Certificate is not valid after this time
* @param algorithm Key pair algorithm
*/
public SelfSignedCertificate(String fqdn, SecureRandom random, int bits, Date notBefore, Date notAfter,
String algorithm) throws CertificateException {
if (!algorithm.equalsIgnoreCase("EC") && !algorithm.equalsIgnoreCase("RSA")) {
throw new IllegalArgumentException("Algorithm not valid: " + algorithm);
}
final KeyPair keypair;
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
keyGen.initialize(bits, random);
keypair = keyGen.generateKeyPair();
} catch (NoSuchAlgorithmException e) {
// Should not reach here because every Java implementation must have RSA and EC key pair generator.
throw new Error(e);
}
String[] paths;
try {
// Try the OpenJDK's proprietary implementation.
paths = OpenJdkSelfSignedCertGenerator.generate(fqdn, keypair, random, notBefore, notAfter, algorithm);
} catch (Throwable t) {
logger.debug("Failed to generate a self-signed X.509 certificate using sun.security.x509:", t);
try {
// Try Bouncy Castle if the current JVM didn't have sun.security.x509.
paths = BouncyCastleSelfSignedCertGenerator.generate(
fqdn, keypair, random, notBefore, notAfter, algorithm);
} catch (Throwable t2) {
logger.debug("Failed to generate a self-signed X.509 certificate using Bouncy Castle:", t2);
final CertificateException certificateException = new CertificateException(
"No provider succeeded to generate a self-signed certificate. " +
"See debug log for the root cause.", t2);
ThrowableUtil.addSuppressed(certificateException, t);
throw certificateException;
}
}
certificate = new File(paths[0]);
privateKey = new File(paths[1]);
key = keypair.getPrivate();
FileInputStream certificateInput = null;
try {
certificateInput = new FileInputStream(certificate);
cert = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(certificateInput);
} catch (Exception e) {
throw new CertificateEncodingException(e);
} finally {
if (certificateInput != null) {
try {
certificateInput.close();
} catch (IOException e) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a file: " + certificate, e);
}
}
}
}
}
/**
* Returns the generated X.509 certificate file in PEM format.
*/
public File certificate() {
return certificate;
}
/**
* Returns the generated RSA private key file in PEM format.
*/
public File privateKey() {
return privateKey;
}
/**
* Returns the generated X.509 certificate.
*/
public X509Certificate cert() {
return cert;
}
/**
* Returns the generated RSA private key.
*/
public PrivateKey key() {
return key;
}
/**
* Deletes the generated X.509 certificate file and RSA private key file.
*/
public void delete() {
safeDelete(certificate);
safeDelete(privateKey);
}
static String[] newSelfSignedCertificate(
String fqdn, PrivateKey key, X509Certificate cert) throws IOException, CertificateEncodingException {
// Encode the private key into a file.
ByteBuf wrappedBuf = Unpooled.wrappedBuffer(key.getEncoded());
ByteBuf encodedBuf;
final String keyText;
try {
encodedBuf = Base64.encode(wrappedBuf, true);
try {
keyText = "-----BEGIN PRIVATE KEY-----\n" +
encodedBuf.toString(CharsetUtil.US_ASCII) +
"\n-----END PRIVATE KEY-----\n";
} finally {
encodedBuf.release();
}
} finally {
wrappedBuf.release();
}
File keyFile = PlatformDependent.createTempFile("keyutil_" + fqdn + '_', ".key", null);
keyFile.deleteOnExit();
OutputStream keyOut = new FileOutputStream(keyFile);
try {
keyOut.write(keyText.getBytes(CharsetUtil.US_ASCII));
keyOut.close();
keyOut = null;
} finally {
if (keyOut != null) {
safeClose(keyFile, keyOut);
safeDelete(keyFile);
}
}
wrappedBuf = Unpooled.wrappedBuffer(cert.getEncoded());
final String certText;
try {
encodedBuf = Base64.encode(wrappedBuf, true);
try {
// Encode the certificate into a CRT file.
certText = "-----BEGIN CERTIFICATE-----\n" +
encodedBuf.toString(CharsetUtil.US_ASCII) +
"\n-----END CERTIFICATE-----\n";
} finally {
encodedBuf.release();
}
} finally {
wrappedBuf.release();
}
File certFile = PlatformDependent.createTempFile("keyutil_" + fqdn + '_', ".crt", null);
certFile.deleteOnExit();
OutputStream certOut = new FileOutputStream(certFile);
try {
certOut.write(certText.getBytes(CharsetUtil.US_ASCII));
certOut.close();
certOut = null;
} finally {
if (certOut != null) {
safeClose(certFile, certOut);
safeDelete(certFile);
safeDelete(keyFile);
}
}
return new String[] { certFile.getPath(), keyFile.getPath() };
}
private static void safeDelete(File certFile) {
if (!certFile.delete()) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to delete a file: " + certFile);
}
}
}
private static void safeClose(File keyFile, OutputStream keyOut) {
try {
keyOut.close();
} catch (IOException e) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to close a file: " + keyFile, e);
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_9 |
crossvul-java_data_good_1927_7 | /*
* 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 io.netty.util.internal;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
/**
* Helper class to load JNI resources.
*
*/
public final class NativeLibraryLoader {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(NativeLibraryLoader.class);
private static final String NATIVE_RESOURCE_HOME = "META-INF/native/";
private static final File WORKDIR;
private static final boolean DELETE_NATIVE_LIB_AFTER_LOADING;
private static final boolean TRY_TO_PATCH_SHADED_ID;
// Just use a-Z and numbers as valid ID bytes.
private static final byte[] UNIQUE_ID_BYTES =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(CharsetUtil.US_ASCII);
static {
String workdir = SystemPropertyUtil.get("io.netty.native.workdir");
if (workdir != null) {
File f = new File(workdir);
f.mkdirs();
try {
f = f.getAbsoluteFile();
} catch (Exception ignored) {
// Good to have an absolute path, but it's OK.
}
WORKDIR = f;
logger.debug("-Dio.netty.native.workdir: " + WORKDIR);
} else {
WORKDIR = PlatformDependent.tmpdir();
logger.debug("-Dio.netty.native.workdir: " + WORKDIR + " (io.netty.tmpdir)");
}
DELETE_NATIVE_LIB_AFTER_LOADING = SystemPropertyUtil.getBoolean(
"io.netty.native.deleteLibAfterLoading", true);
logger.debug("-Dio.netty.native.deleteLibAfterLoading: {}", DELETE_NATIVE_LIB_AFTER_LOADING);
TRY_TO_PATCH_SHADED_ID = SystemPropertyUtil.getBoolean(
"io.netty.native.tryPatchShadedId", true);
logger.debug("-Dio.netty.native.tryPatchShadedId: {}", TRY_TO_PATCH_SHADED_ID);
}
/**
* Loads the first available library in the collection with the specified
* {@link ClassLoader}.
*
* @throws IllegalArgumentException
* if none of the given libraries load successfully.
*/
public static void loadFirstAvailable(ClassLoader loader, String... names) {
List<Throwable> suppressed = new ArrayList<Throwable>();
for (String name : names) {
try {
load(name, loader);
return;
} catch (Throwable t) {
suppressed.add(t);
}
}
IllegalArgumentException iae =
new IllegalArgumentException("Failed to load any of the given libraries: " + Arrays.toString(names));
ThrowableUtil.addSuppressedAndClear(iae, suppressed);
throw iae;
}
/**
* The shading prefix added to this class's full name.
*
* @throws UnsatisfiedLinkError if the shader used something other than a prefix
*/
private static String calculatePackagePrefix() {
String maybeShaded = NativeLibraryLoader.class.getName();
// Use ! instead of . to avoid shading utilities from modifying the string
String expected = "io!netty!util!internal!NativeLibraryLoader".replace('!', '.');
if (!maybeShaded.endsWith(expected)) {
throw new UnsatisfiedLinkError(String.format(
"Could not find prefix added to %s to get %s. When shading, only adding a "
+ "package prefix is supported", expected, maybeShaded));
}
return maybeShaded.substring(0, maybeShaded.length() - expected.length());
}
/**
* Load the given library with the specified {@link ClassLoader}
*/
public static void load(String originalName, ClassLoader loader) {
// Adjust expected name to support shading of native libraries.
String packagePrefix = calculatePackagePrefix().replace('.', '_');
String name = packagePrefix + originalName;
List<Throwable> suppressed = new ArrayList<Throwable>();
try {
// first try to load from java.library.path
loadLibrary(loader, name, false);
return;
} catch (Throwable ex) {
suppressed.add(ex);
}
String libname = System.mapLibraryName(name);
String path = NATIVE_RESOURCE_HOME + libname;
InputStream in = null;
OutputStream out = null;
File tmpFile = null;
URL url;
if (loader == null) {
url = ClassLoader.getSystemResource(path);
} else {
url = loader.getResource(path);
}
try {
if (url == null) {
if (PlatformDependent.isOsx()) {
String fileName = path.endsWith(".jnilib") ? NATIVE_RESOURCE_HOME + "lib" + name + ".dynlib" :
NATIVE_RESOURCE_HOME + "lib" + name + ".jnilib";
if (loader == null) {
url = ClassLoader.getSystemResource(fileName);
} else {
url = loader.getResource(fileName);
}
if (url == null) {
FileNotFoundException fnf = new FileNotFoundException(fileName);
ThrowableUtil.addSuppressedAndClear(fnf, suppressed);
throw fnf;
}
} else {
FileNotFoundException fnf = new FileNotFoundException(path);
ThrowableUtil.addSuppressedAndClear(fnf, suppressed);
throw fnf;
}
}
int index = libname.lastIndexOf('.');
String prefix = libname.substring(0, index);
String suffix = libname.substring(index);
tmpFile = PlatformDependent.createTempFile(prefix, suffix, WORKDIR);
in = url.openStream();
out = new FileOutputStream(tmpFile);
if (shouldShadedLibraryIdBePatched(packagePrefix)) {
patchShadedLibraryId(in, out, originalName, name);
} else {
byte[] buffer = new byte[8192];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}
out.flush();
// Close the output stream before loading the unpacked library,
// because otherwise Windows will refuse to load it when it's in use by other process.
closeQuietly(out);
out = null;
loadLibrary(loader, tmpFile.getPath(), true);
} catch (UnsatisfiedLinkError e) {
try {
if (tmpFile != null && tmpFile.isFile() && tmpFile.canRead() &&
!NoexecVolumeDetector.canExecuteExecutable(tmpFile)) {
// Pass "io.netty.native.workdir" as an argument to allow shading tools to see
// the string. Since this is printed out to users to tell them what to do next,
// we want the value to be correct even when shading.
logger.info("{} exists but cannot be executed even when execute permissions set; " +
"check volume for \"noexec\" flag; use -D{}=[path] " +
"to set native working directory separately.",
tmpFile.getPath(), "io.netty.native.workdir");
}
} catch (Throwable t) {
suppressed.add(t);
logger.debug("Error checking if {} is on a file store mounted with noexec", tmpFile, t);
}
// Re-throw to fail the load
ThrowableUtil.addSuppressedAndClear(e, suppressed);
throw e;
} catch (Exception e) {
UnsatisfiedLinkError ule = new UnsatisfiedLinkError("could not load a native library: " + name);
ule.initCause(e);
ThrowableUtil.addSuppressedAndClear(ule, suppressed);
throw ule;
} finally {
closeQuietly(in);
closeQuietly(out);
// After we load the library it is safe to delete the file.
// We delete the file immediately to free up resources as soon as possible,
// and if this fails fallback to deleting on JVM exit.
if (tmpFile != null && (!DELETE_NATIVE_LIB_AFTER_LOADING || !tmpFile.delete())) {
tmpFile.deleteOnExit();
}
}
}
// Package-private for testing.
static boolean patchShadedLibraryId(InputStream in, OutputStream out, String originalName, String name)
throws IOException {
byte[] buffer = new byte[8192];
int length;
// We read the whole native lib into memory to make it easier to monkey-patch the id.
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(in.available());
while ((length = in.read(buffer)) > 0) {
byteArrayOutputStream.write(buffer, 0, length);
}
byteArrayOutputStream.flush();
byte[] bytes = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
final boolean patched;
// Try to patch the library id.
if (!patchShadedLibraryId(bytes, originalName, name)) {
// We did not find the Id, check if we used a originalName that has the os and arch as suffix.
// If this is the case we should also try to patch with the os and arch suffix removed.
String os = PlatformDependent.normalizedOs();
String arch = PlatformDependent.normalizedArch();
String osArch = "_" + os + "_" + arch;
if (originalName.endsWith(osArch)) {
patched = patchShadedLibraryId(bytes,
originalName.substring(0, originalName.length() - osArch.length()), name);
} else {
patched = false;
}
} else {
patched = true;
}
out.write(bytes, 0, bytes.length);
return patched;
}
private static boolean shouldShadedLibraryIdBePatched(String packagePrefix) {
return TRY_TO_PATCH_SHADED_ID && PlatformDependent.isOsx() && !packagePrefix.isEmpty();
}
/**
* Try to patch shaded library to ensure it uses a unique ID.
*/
private static boolean patchShadedLibraryId(byte[] bytes, String originalName, String name) {
// Our native libs always have the name as part of their id so we can search for it and replace it
// to make the ID unique if shading is used.
byte[] nameBytes = originalName.getBytes(CharsetUtil.UTF_8);
int idIdx = -1;
// Be aware this is a really raw way of patching a dylib but it does all we need without implementing
// a full mach-o parser and writer. Basically we just replace the the original bytes with some
// random bytes as part of the ID regeneration. The important thing here is that we need to use the same
// length to not corrupt the mach-o header.
outerLoop: for (int i = 0; i < bytes.length && bytes.length - i >= nameBytes.length; i++) {
int idx = i;
for (int j = 0; j < nameBytes.length;) {
if (bytes[idx++] != nameBytes[j++]) {
// Did not match the name, increase the index and try again.
break;
} else if (j == nameBytes.length) {
// We found the index within the id.
idIdx = i;
break outerLoop;
}
}
}
if (idIdx == -1) {
logger.debug("Was not able to find the ID of the shaded native library {}, can't adjust it.", name);
return false;
} else {
// We found our ID... now monkey-patch it!
for (int i = 0; i < nameBytes.length; i++) {
// We should only use bytes as replacement that are in our UNIQUE_ID_BYTES array.
bytes[idIdx + i] = UNIQUE_ID_BYTES[PlatformDependent.threadLocalRandom()
.nextInt(UNIQUE_ID_BYTES.length)];
}
if (logger.isDebugEnabled()) {
logger.debug(
"Found the ID of the shaded native library {}. Replacing ID part {} with {}",
name, originalName, new String(bytes, idIdx, nameBytes.length, CharsetUtil.UTF_8));
}
return true;
}
}
/**
* Loading the native library into the specified {@link ClassLoader}.
* @param loader - The {@link ClassLoader} where the native library will be loaded into
* @param name - The native library path or name
* @param absolute - Whether the native library will be loaded by path or by name
*/
private static void loadLibrary(final ClassLoader loader, final String name, final boolean absolute) {
Throwable suppressed = null;
try {
try {
// Make sure the helper is belong to the target ClassLoader.
final Class<?> newHelper = tryToLoadClass(loader, NativeLibraryUtil.class);
loadLibraryByHelper(newHelper, name, absolute);
logger.debug("Successfully loaded the library {}", name);
return;
} catch (UnsatisfiedLinkError e) { // Should by pass the UnsatisfiedLinkError here!
suppressed = e;
} catch (Exception e) {
suppressed = e;
}
NativeLibraryUtil.loadLibrary(name, absolute); // Fallback to local helper class.
logger.debug("Successfully loaded the library {}", name);
} catch (NoSuchMethodError nsme) {
if (suppressed != null) {
ThrowableUtil.addSuppressed(nsme, suppressed);
}
rethrowWithMoreDetailsIfPossible(name, nsme);
} catch (UnsatisfiedLinkError ule) {
if (suppressed != null) {
ThrowableUtil.addSuppressed(ule, suppressed);
}
throw ule;
}
}
@SuppressJava6Requirement(reason = "Guarded by version check")
private static void rethrowWithMoreDetailsIfPossible(String name, NoSuchMethodError error) {
if (PlatformDependent.javaVersion() >= 7) {
throw new LinkageError(
"Possible multiple incompatible native libraries on the classpath for '" + name + "'?", error);
}
throw error;
}
private static void loadLibraryByHelper(final Class<?> helper, final String name, final boolean absolute)
throws UnsatisfiedLinkError {
Object ret = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
// Invoke the helper to load the native library, if succeed, then the native
// library belong to the specified ClassLoader.
Method method = helper.getMethod("loadLibrary", String.class, boolean.class);
method.setAccessible(true);
return method.invoke(null, name, absolute);
} catch (Exception e) {
return e;
}
}
});
if (ret instanceof Throwable) {
Throwable t = (Throwable) ret;
assert !(t instanceof UnsatisfiedLinkError) : t + " should be a wrapper throwable";
Throwable cause = t.getCause();
if (cause instanceof UnsatisfiedLinkError) {
throw (UnsatisfiedLinkError) cause;
}
UnsatisfiedLinkError ule = new UnsatisfiedLinkError(t.getMessage());
ule.initCause(t);
throw ule;
}
}
/**
* Try to load the helper {@link Class} into specified {@link ClassLoader}.
* @param loader - The {@link ClassLoader} where to load the helper {@link Class}
* @param helper - The helper {@link Class}
* @return A new helper Class defined in the specified ClassLoader.
* @throws ClassNotFoundException Helper class not found or loading failed
*/
private static Class<?> tryToLoadClass(final ClassLoader loader, final Class<?> helper)
throws ClassNotFoundException {
try {
return Class.forName(helper.getName(), false, loader);
} catch (ClassNotFoundException e1) {
if (loader == null) {
// cannot defineClass inside bootstrap class loader
throw e1;
}
try {
// The helper class is NOT found in target ClassLoader, we have to define the helper class.
final byte[] classBinary = classToByteArray(helper);
return AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
@Override
public Class<?> run() {
try {
// Define the helper class in the target ClassLoader,
// then we can call the helper to load the native library.
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class,
byte[].class, int.class, int.class);
defineClass.setAccessible(true);
return (Class<?>) defineClass.invoke(loader, helper.getName(), classBinary, 0,
classBinary.length);
} catch (Exception e) {
throw new IllegalStateException("Define class failed!", e);
}
}
});
} catch (ClassNotFoundException e2) {
ThrowableUtil.addSuppressed(e2, e1);
throw e2;
} catch (RuntimeException e2) {
ThrowableUtil.addSuppressed(e2, e1);
throw e2;
} catch (Error e2) {
ThrowableUtil.addSuppressed(e2, e1);
throw e2;
}
}
}
/**
* Load the helper {@link Class} as a byte array, to be redefined in specified {@link ClassLoader}.
* @param clazz - The helper {@link Class} provided by this bundle
* @return The binary content of helper {@link Class}.
* @throws ClassNotFoundException Helper class not found or loading failed
*/
private static byte[] classToByteArray(Class<?> clazz) throws ClassNotFoundException {
String fileName = clazz.getName();
int lastDot = fileName.lastIndexOf('.');
if (lastDot > 0) {
fileName = fileName.substring(lastDot + 1);
}
URL classUrl = clazz.getResource(fileName + ".class");
if (classUrl == null) {
throw new ClassNotFoundException(clazz.getName());
}
byte[] buf = new byte[1024];
ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
InputStream in = null;
try {
in = classUrl.openStream();
for (int r; (r = in.read(buf)) != -1;) {
out.write(buf, 0, r);
}
return out.toByteArray();
} catch (IOException ex) {
throw new ClassNotFoundException(clazz.getName(), ex);
} finally {
closeQuietly(in);
closeQuietly(out);
}
}
private static void closeQuietly(Closeable c) {
if (c != null) {
try {
c.close();
} catch (IOException ignore) {
// ignore
}
}
}
private NativeLibraryLoader() {
// Utility
}
private static final class NoexecVolumeDetector {
@SuppressJava6Requirement(reason = "Usage guarded by java version check")
private static boolean canExecuteExecutable(File file) throws IOException {
if (PlatformDependent.javaVersion() < 7) {
// Pre-JDK7, the Java API did not directly support POSIX permissions; instead of implementing a custom
// work-around, assume true, which disables the check.
return true;
}
// If we can already execute, there is nothing to do.
if (file.canExecute()) {
return true;
}
// On volumes, with noexec set, even files with the executable POSIX permissions will fail to execute.
// The File#canExecute() method honors this behavior, probaby via parsing the noexec flag when initializing
// the UnixFileStore, though the flag is not exposed via a public API. To find out if library is being
// loaded off a volume with noexec, confirm or add executalbe permissions, then check File#canExecute().
// Note: We use FQCN to not break when netty is used in java6
Set<java.nio.file.attribute.PosixFilePermission> existingFilePermissions =
java.nio.file.Files.getPosixFilePermissions(file.toPath());
Set<java.nio.file.attribute.PosixFilePermission> executePermissions =
EnumSet.of(java.nio.file.attribute.PosixFilePermission.OWNER_EXECUTE,
java.nio.file.attribute.PosixFilePermission.GROUP_EXECUTE,
java.nio.file.attribute.PosixFilePermission.OTHERS_EXECUTE);
if (existingFilePermissions.containsAll(executePermissions)) {
return false;
}
Set<java.nio.file.attribute.PosixFilePermission> newPermissions = EnumSet.copyOf(existingFilePermissions);
newPermissions.addAll(executePermissions);
java.nio.file.Files.setPosixFilePermissions(file.toPath(), newPermissions);
return file.canExecute();
}
private NoexecVolumeDetector() {
// Utility
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_7 |
crossvul-java_data_bad_1927_3 | /*
* 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 io.netty.handler.codec.http;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.stream.ChunkedFile;
import io.netty.handler.stream.ChunkedInput;
import io.netty.handler.stream.ChunkedNioFile;
import io.netty.handler.stream.ChunkedNioStream;
import io.netty.handler.stream.ChunkedStream;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import static org.junit.Assert.*;
public class HttpChunkedInputTest {
private static final byte[] BYTES = new byte[1024 * 64];
private static final File TMP;
static {
for (int i = 0; i < BYTES.length; i++) {
BYTES[i] = (byte) i;
}
FileOutputStream out = null;
try {
TMP = File.createTempFile("netty-chunk-", ".tmp");
TMP.deleteOnExit();
out = new FileOutputStream(TMP);
out.write(BYTES);
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignore
}
}
}
}
@Test
public void testChunkedStream() {
check(new HttpChunkedInput(new ChunkedStream(new ByteArrayInputStream(BYTES))));
}
@Test
public void testChunkedNioStream() {
check(new HttpChunkedInput(new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES)))));
}
@Test
public void testChunkedFile() throws IOException {
check(new HttpChunkedInput(new ChunkedFile(TMP)));
}
@Test
public void testChunkedNioFile() throws IOException {
check(new HttpChunkedInput(new ChunkedNioFile(TMP)));
}
@Test
public void testWrappedReturnNull() throws Exception {
HttpChunkedInput input = new HttpChunkedInput(new ChunkedInput<ByteBuf>() {
@Override
public boolean isEndOfInput() throws Exception {
return false;
}
@Override
public void close() throws Exception {
// NOOP
}
@Override
public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
return null;
}
@Override
public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {
return null;
}
@Override
public long length() {
return 0;
}
@Override
public long progress() {
return 0;
}
});
assertNull(input.readChunk(ByteBufAllocator.DEFAULT));
}
private static void check(ChunkedInput<?>... inputs) {
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
for (ChunkedInput<?> input : inputs) {
ch.writeOutbound(input);
}
assertTrue(ch.finish());
int i = 0;
int read = 0;
HttpContent lastHttpContent = null;
for (;;) {
HttpContent httpContent = ch.readOutbound();
if (httpContent == null) {
break;
}
if (lastHttpContent != null) {
assertTrue("Chunk must be DefaultHttpContent", lastHttpContent instanceof DefaultHttpContent);
}
ByteBuf buffer = httpContent.content();
while (buffer.isReadable()) {
assertEquals(BYTES[i++], buffer.readByte());
read++;
if (i == BYTES.length) {
i = 0;
}
}
buffer.release();
// Save last chunk
lastHttpContent = httpContent;
}
assertEquals(BYTES.length * inputs.length, read);
assertSame("Last chunk must be LastHttpContent.EMPTY_LAST_CONTENT",
LastHttpContent.EMPTY_LAST_CONTENT, lastHttpContent);
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_3 |
crossvul-java_data_good_1927_6 | /*
* Copyright 2016 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 io.netty.handler.codec.http.multipart;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class DiskFileUploadTest {
@Test
public void testSpecificCustomBaseDir() throws IOException {
File baseDir = new File("target/DiskFileUploadTest/testSpecificCustomBaseDir");
baseDir.mkdirs(); // we don't need to clean it since it is in volatile files anyway
DiskFileUpload f =
new DiskFileUpload("d1", "d1", "application/json", null, null, 100,
baseDir.getAbsolutePath(), false);
f.setContent(Unpooled.EMPTY_BUFFER);
assertTrue(f.getFile().getAbsolutePath().startsWith(baseDir.getAbsolutePath()));
assertTrue(f.getFile().exists());
assertEquals(0, f.getFile().length());
f.delete();
}
@Test
public final void testDiskFileUploadEquals() {
DiskFileUpload f2 =
new DiskFileUpload("d1", "d1", "application/json", null, null, 100);
assertEquals(f2, f2);
f2.delete();
}
@Test
public void testEmptyBufferSetMultipleTimes() throws IOException {
DiskFileUpload f =
new DiskFileUpload("d1", "d1", "application/json", null, null, 100);
f.setContent(Unpooled.EMPTY_BUFFER);
assertTrue(f.getFile().exists());
assertEquals(0, f.getFile().length());
f.setContent(Unpooled.EMPTY_BUFFER);
assertTrue(f.getFile().exists());
assertEquals(0, f.getFile().length());
f.delete();
}
@Test
public void testEmptyBufferSetAfterNonEmptyBuffer() throws IOException {
DiskFileUpload f =
new DiskFileUpload("d1", "d1", "application/json", null, null, 100);
f.setContent(Unpooled.wrappedBuffer(new byte[] { 1, 2, 3, 4 }));
assertTrue(f.getFile().exists());
assertEquals(4, f.getFile().length());
f.setContent(Unpooled.EMPTY_BUFFER);
assertTrue(f.getFile().exists());
assertEquals(0, f.getFile().length());
f.delete();
}
@Test
public void testNonEmptyBufferSetMultipleTimes() throws IOException {
DiskFileUpload f =
new DiskFileUpload("d1", "d1", "application/json", null, null, 100);
f.setContent(Unpooled.wrappedBuffer(new byte[] { 1, 2, 3, 4 }));
assertTrue(f.getFile().exists());
assertEquals(4, f.getFile().length());
f.setContent(Unpooled.wrappedBuffer(new byte[] { 1, 2}));
assertTrue(f.getFile().exists());
assertEquals(2, f.getFile().length());
f.delete();
}
@Test
public void testAddContents() throws Exception {
DiskFileUpload f1 = new DiskFileUpload("file1", "file1", "application/json", null, null, 0);
try {
byte[] jsonBytes = new byte[4096];
PlatformDependent.threadLocalRandom().nextBytes(jsonBytes);
f1.addContent(Unpooled.wrappedBuffer(jsonBytes, 0, 1024), false);
f1.addContent(Unpooled.wrappedBuffer(jsonBytes, 1024, jsonBytes.length - 1024), true);
assertArrayEquals(jsonBytes, f1.get());
File file = f1.getFile();
assertEquals(jsonBytes.length, file.length());
FileInputStream fis = new FileInputStream(file);
try {
byte[] buf = new byte[jsonBytes.length];
int offset = 0;
int read = 0;
int len = buf.length;
while ((read = fis.read(buf, offset, len)) > 0) {
len -= read;
offset += read;
if (len <= 0 || offset >= buf.length) {
break;
}
}
assertArrayEquals(jsonBytes, buf);
} finally {
fis.close();
}
} finally {
f1.delete();
}
}
@Test
public void testSetContentFromByteBuf() throws Exception {
DiskFileUpload f1 = new DiskFileUpload("file2", "file2", "application/json", null, null, 0);
try {
String json = "{\"hello\":\"world\"}";
byte[] bytes = json.getBytes(CharsetUtil.UTF_8);
f1.setContent(Unpooled.wrappedBuffer(bytes));
assertEquals(json, f1.getString());
assertArrayEquals(bytes, f1.get());
File file = f1.getFile();
assertEquals((long) bytes.length, file.length());
assertArrayEquals(bytes, doReadFile(file, bytes.length));
} finally {
f1.delete();
}
}
@Test
public void testSetContentFromInputStream() throws Exception {
String json = "{\"hello\":\"world\",\"foo\":\"bar\"}";
DiskFileUpload f1 = new DiskFileUpload("file3", "file3", "application/json", null, null, 0);
try {
byte[] bytes = json.getBytes(CharsetUtil.UTF_8);
ByteBuf buf = Unpooled.wrappedBuffer(bytes);
InputStream is = new ByteBufInputStream(buf);
try {
f1.setContent(is);
assertEquals(json, f1.getString());
assertArrayEquals(bytes, f1.get());
File file = f1.getFile();
assertEquals((long) bytes.length, file.length());
assertArrayEquals(bytes, doReadFile(file, bytes.length));
} finally {
buf.release();
is.close();
}
} finally {
f1.delete();
}
}
@Test
public void testAddContentFromByteBuf() throws Exception {
testAddContentFromByteBuf0(false);
}
@Test
public void testAddContentFromCompositeByteBuf() throws Exception {
testAddContentFromByteBuf0(true);
}
private static void testAddContentFromByteBuf0(boolean composite) throws Exception {
DiskFileUpload f1 = new DiskFileUpload("file3", "file3", "application/json", null, null, 0);
try {
byte[] bytes = new byte[4096];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
final ByteBuf buffer;
if (composite) {
buffer = Unpooled.compositeBuffer()
.addComponent(true, Unpooled.wrappedBuffer(bytes, 0 , bytes.length / 2))
.addComponent(true, Unpooled.wrappedBuffer(bytes, bytes.length / 2, bytes.length / 2));
} else {
buffer = Unpooled.wrappedBuffer(bytes);
}
f1.addContent(buffer, true);
ByteBuf buf = f1.getByteBuf();
assertEquals(buf.readerIndex(), 0);
assertEquals(buf.writerIndex(), bytes.length);
assertArrayEquals(bytes, ByteBufUtil.getBytes(buf));
} finally {
//release the ByteBuf
f1.delete();
}
}
private static byte[] doReadFile(File file, int maxRead) throws Exception {
FileInputStream fis = new FileInputStream(file);
try {
byte[] buf = new byte[maxRead];
int offset = 0;
int read = 0;
int len = buf.length;
while ((read = fis.read(buf, offset, len)) > 0) {
len -= read;
offset += read;
if (len <= 0 || offset >= buf.length) {
break;
}
}
return buf;
} finally {
fis.close();
}
}
@Test
public void testDelete() throws Exception {
String json = "{\"foo\":\"bar\"}";
byte[] bytes = json.getBytes(CharsetUtil.UTF_8);
File tmpFile = null;
DiskFileUpload f1 = new DiskFileUpload("file4", "file4", "application/json", null, null, 0);
try {
assertNull(f1.getFile());
f1.setContent(Unpooled.wrappedBuffer(bytes));
assertNotNull(tmpFile = f1.getFile());
} finally {
f1.delete();
assertNull(f1.getFile());
assertNotNull(tmpFile);
assertFalse(tmpFile.exists());
}
}
@Test
public void setSetContentFromFileExceptionally() throws Exception {
final long maxSize = 4;
DiskFileUpload f1 = new DiskFileUpload("file5", "file5", "application/json", null, null, 0);
f1.setMaxSize(maxSize);
try {
f1.setContent(Unpooled.wrappedBuffer(new byte[(int) maxSize]));
File originalFile = f1.getFile();
assertNotNull(originalFile);
assertEquals(maxSize, originalFile.length());
assertEquals(maxSize, f1.length());
byte[] bytes = new byte[8];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), ".tmp", null);
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpFile);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
try {
f1.setContent(tmpFile);
fail("should not reach here!");
} catch (IOException e) {
assertNotNull(f1.getFile());
assertEquals(originalFile, f1.getFile());
assertEquals(maxSize, f1.length());
}
} finally {
f1.delete();
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_6 |
crossvul-java_data_good_1927_15 | /*
* Copyright 2019 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 io.netty.channel;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class DefaultFileRegionTest {
private static final byte[] data = new byte[1048576 * 10];
static {
PlatformDependent.threadLocalRandom().nextBytes(data);
}
private static File newFile() throws IOException {
File file = PlatformDependent.createTempFile("netty-", ".tmp", null);
file.deleteOnExit();
final FileOutputStream out = new FileOutputStream(file);
out.write(data);
out.close();
return file;
}
@Test
public void testCreateFromFile() throws IOException {
File file = newFile();
try {
testFileRegion(new DefaultFileRegion(file, 0, data.length));
} finally {
file.delete();
}
}
@Test
public void testCreateFromFileChannel() throws IOException {
File file = newFile();
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
try {
testFileRegion(new DefaultFileRegion(randomAccessFile.getChannel(), 0, data.length));
} finally {
randomAccessFile.close();
file.delete();
}
}
private static void testFileRegion(FileRegion region) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
WritableByteChannel channel = Channels.newChannel(outputStream);
try {
assertEquals(data.length, region.count());
assertEquals(0, region.transferred());
assertEquals(data.length, region.transferTo(channel, 0));
assertEquals(data.length, region.count());
assertEquals(data.length, region.transferred());
assertArrayEquals(data, outputStream.toByteArray());
} finally {
channel.close();
}
}
@Test
public void testTruncated() throws IOException {
File file = newFile();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
WritableByteChannel channel = Channels.newChannel(outputStream);
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
try {
FileRegion region = new DefaultFileRegion(randomAccessFile.getChannel(), 0, data.length);
randomAccessFile.getChannel().truncate(data.length - 1024);
assertEquals(data.length, region.count());
assertEquals(0, region.transferred());
assertEquals(data.length - 1024, region.transferTo(channel, 0));
assertEquals(data.length, region.count());
assertEquals(data.length - 1024, region.transferred());
try {
region.transferTo(channel, data.length - 1024);
fail();
} catch (IOException expected) {
// expected
}
} finally {
channel.close();
randomAccessFile.close();
file.delete();
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_15 |
crossvul-java_data_good_1927_8 | /*
* Copyright 2012 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 io.netty.util.internal;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.jctools.queues.MpscArrayQueue;
import org.jctools.queues.MpscChunkedArrayQueue;
import org.jctools.queues.MpscUnboundedArrayQueue;
import org.jctools.queues.SpscLinkedQueue;
import org.jctools.queues.atomic.MpscAtomicArrayQueue;
import org.jctools.queues.atomic.MpscChunkedAtomicArrayQueue;
import org.jctools.queues.atomic.MpscUnboundedAtomicArrayQueue;
import org.jctools.queues.atomic.SpscLinkedAtomicQueue;
import org.jctools.util.Pow2;
import org.jctools.util.UnsafeAccess;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.netty.util.internal.PlatformDependent0.HASH_CODE_ASCII_SEED;
import static io.netty.util.internal.PlatformDependent0.HASH_CODE_C1;
import static io.netty.util.internal.PlatformDependent0.HASH_CODE_C2;
import static io.netty.util.internal.PlatformDependent0.hashCodeAsciiSanitize;
import static io.netty.util.internal.PlatformDependent0.unalignedAccess;
import static java.lang.Math.max;
import static java.lang.Math.min;
/**
* Utility that detects various properties specific to the current runtime
* environment, such as Java version and the availability of the
* {@code sun.misc.Unsafe} object.
* <p>
* You can disable the use of {@code sun.misc.Unsafe} if you specify
* the system property <strong>io.netty.noUnsafe</strong>.
*/
public final class PlatformDependent {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(PlatformDependent.class);
private static final Pattern MAX_DIRECT_MEMORY_SIZE_ARG_PATTERN = Pattern.compile(
"\\s*-XX:MaxDirectMemorySize\\s*=\\s*([0-9]+)\\s*([kKmMgG]?)\\s*$");
private static final boolean IS_WINDOWS = isWindows0();
private static final boolean IS_OSX = isOsx0();
private static final boolean IS_J9_JVM = isJ9Jvm0();
private static final boolean IS_IVKVM_DOT_NET = isIkvmDotNet0();
private static final boolean MAYBE_SUPER_USER;
private static final boolean CAN_ENABLE_TCP_NODELAY_BY_DEFAULT = !isAndroid();
private static final Throwable UNSAFE_UNAVAILABILITY_CAUSE = unsafeUnavailabilityCause0();
private static final boolean DIRECT_BUFFER_PREFERRED;
private static final long MAX_DIRECT_MEMORY = maxDirectMemory0();
private static final int MPSC_CHUNK_SIZE = 1024;
private static final int MIN_MAX_MPSC_CAPACITY = MPSC_CHUNK_SIZE * 2;
private static final int MAX_ALLOWED_MPSC_CAPACITY = Pow2.MAX_POW2;
private static final long BYTE_ARRAY_BASE_OFFSET = byteArrayBaseOffset0();
private static final File TMPDIR = tmpdir0();
private static final int BIT_MODE = bitMode0();
private static final String NORMALIZED_ARCH = normalizeArch(SystemPropertyUtil.get("os.arch", ""));
private static final String NORMALIZED_OS = normalizeOs(SystemPropertyUtil.get("os.name", ""));
// keep in sync with maven's pom.xml via os.detection.classifierWithLikes!
private static final String[] ALLOWED_LINUX_OS_CLASSIFIERS = {"fedora", "suse", "arch"};
private static final Set<String> LINUX_OS_CLASSIFIERS;
private static final int ADDRESS_SIZE = addressSize0();
private static final boolean USE_DIRECT_BUFFER_NO_CLEANER;
private static final AtomicLong DIRECT_MEMORY_COUNTER;
private static final long DIRECT_MEMORY_LIMIT;
private static final ThreadLocalRandomProvider RANDOM_PROVIDER;
private static final Cleaner CLEANER;
private static final int UNINITIALIZED_ARRAY_ALLOCATION_THRESHOLD;
// For specifications, see https://www.freedesktop.org/software/systemd/man/os-release.html
private static final String[] OS_RELEASE_FILES = {"/etc/os-release", "/usr/lib/os-release"};
private static final String LINUX_ID_PREFIX = "ID=";
private static final String LINUX_ID_LIKE_PREFIX = "ID_LIKE=";
public static final boolean BIG_ENDIAN_NATIVE_ORDER = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN;
private static final Cleaner NOOP = new Cleaner() {
@Override
public void freeDirectBuffer(ByteBuffer buffer) {
// NOOP
}
};
static {
if (javaVersion() >= 7) {
RANDOM_PROVIDER = new ThreadLocalRandomProvider() {
@Override
@SuppressJava6Requirement(reason = "Usage guarded by java version check")
public Random current() {
return java.util.concurrent.ThreadLocalRandom.current();
}
};
} else {
RANDOM_PROVIDER = new ThreadLocalRandomProvider() {
@Override
public Random current() {
return ThreadLocalRandom.current();
}
};
}
// Here is how the system property is used:
//
// * < 0 - Don't use cleaner, and inherit max direct memory from java. In this case the
// "practical max direct memory" would be 2 * max memory as defined by the JDK.
// * == 0 - Use cleaner, Netty will not enforce max memory, and instead will defer to JDK.
// * > 0 - Don't use cleaner. This will limit Netty's total direct memory
// (note: that JDK's direct memory limit is independent of this).
long maxDirectMemory = SystemPropertyUtil.getLong("io.netty.maxDirectMemory", -1);
if (maxDirectMemory == 0 || !hasUnsafe() || !PlatformDependent0.hasDirectBufferNoCleanerConstructor()) {
USE_DIRECT_BUFFER_NO_CLEANER = false;
DIRECT_MEMORY_COUNTER = null;
} else {
USE_DIRECT_BUFFER_NO_CLEANER = true;
if (maxDirectMemory < 0) {
maxDirectMemory = MAX_DIRECT_MEMORY;
if (maxDirectMemory <= 0) {
DIRECT_MEMORY_COUNTER = null;
} else {
DIRECT_MEMORY_COUNTER = new AtomicLong();
}
} else {
DIRECT_MEMORY_COUNTER = new AtomicLong();
}
}
logger.debug("-Dio.netty.maxDirectMemory: {} bytes", maxDirectMemory);
DIRECT_MEMORY_LIMIT = maxDirectMemory >= 1 ? maxDirectMemory : MAX_DIRECT_MEMORY;
int tryAllocateUninitializedArray =
SystemPropertyUtil.getInt("io.netty.uninitializedArrayAllocationThreshold", 1024);
UNINITIALIZED_ARRAY_ALLOCATION_THRESHOLD = javaVersion() >= 9 && PlatformDependent0.hasAllocateArrayMethod() ?
tryAllocateUninitializedArray : -1;
logger.debug("-Dio.netty.uninitializedArrayAllocationThreshold: {}", UNINITIALIZED_ARRAY_ALLOCATION_THRESHOLD);
MAYBE_SUPER_USER = maybeSuperUser0();
if (!isAndroid()) {
// only direct to method if we are not running on android.
// See https://github.com/netty/netty/issues/2604
if (javaVersion() >= 9) {
CLEANER = CleanerJava9.isSupported() ? new CleanerJava9() : NOOP;
} else {
CLEANER = CleanerJava6.isSupported() ? new CleanerJava6() : NOOP;
}
} else {
CLEANER = NOOP;
}
// We should always prefer direct buffers by default if we can use a Cleaner to release direct buffers.
DIRECT_BUFFER_PREFERRED = CLEANER != NOOP
&& !SystemPropertyUtil.getBoolean("io.netty.noPreferDirect", false);
if (logger.isDebugEnabled()) {
logger.debug("-Dio.netty.noPreferDirect: {}", !DIRECT_BUFFER_PREFERRED);
}
/*
* We do not want to log this message if unsafe is explicitly disabled. Do not remove the explicit no unsafe
* guard.
*/
if (CLEANER == NOOP && !PlatformDependent0.isExplicitNoUnsafe()) {
logger.info(
"Your platform does not provide complete low-level API for accessing direct buffers reliably. " +
"Unless explicitly requested, heap buffer will always be preferred to avoid potential system " +
"instability.");
}
final Set<String> allowedClassifiers = Collections.unmodifiableSet(
new HashSet<String>(Arrays.asList(ALLOWED_LINUX_OS_CLASSIFIERS)));
final Set<String> availableClassifiers = new LinkedHashSet<String>();
for (final String osReleaseFileName : OS_RELEASE_FILES) {
final File file = new File(osReleaseFileName);
boolean found = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
try {
if (file.exists()) {
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(file), CharsetUtil.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith(LINUX_ID_PREFIX)) {
String id = normalizeOsReleaseVariableValue(
line.substring(LINUX_ID_PREFIX.length()));
addClassifier(allowedClassifiers, availableClassifiers, id);
} else if (line.startsWith(LINUX_ID_LIKE_PREFIX)) {
line = normalizeOsReleaseVariableValue(
line.substring(LINUX_ID_LIKE_PREFIX.length()));
addClassifier(allowedClassifiers, availableClassifiers, line.split("[ ]+"));
}
}
} catch (SecurityException e) {
logger.debug("Unable to read {}", osReleaseFileName, e);
} catch (IOException e) {
logger.debug("Error while reading content of {}", osReleaseFileName, e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
// Ignore
}
}
}
// specification states we should only fall back if /etc/os-release does not exist
return true;
}
} catch (SecurityException e) {
logger.debug("Unable to check if {} exists", osReleaseFileName, e);
}
return false;
}
});
if (found) {
break;
}
}
LINUX_OS_CLASSIFIERS = Collections.unmodifiableSet(availableClassifiers);
}
public static long byteArrayBaseOffset() {
return BYTE_ARRAY_BASE_OFFSET;
}
public static boolean hasDirectBufferNoCleanerConstructor() {
return PlatformDependent0.hasDirectBufferNoCleanerConstructor();
}
public static byte[] allocateUninitializedArray(int size) {
return UNINITIALIZED_ARRAY_ALLOCATION_THRESHOLD < 0 || UNINITIALIZED_ARRAY_ALLOCATION_THRESHOLD > size ?
new byte[size] : PlatformDependent0.allocateUninitializedArray(size);
}
/**
* Returns {@code true} if and only if the current platform is Android
*/
public static boolean isAndroid() {
return PlatformDependent0.isAndroid();
}
/**
* Return {@code true} if the JVM is running on Windows
*/
public static boolean isWindows() {
return IS_WINDOWS;
}
/**
* Return {@code true} if the JVM is running on OSX / MacOS
*/
public static boolean isOsx() {
return IS_OSX;
}
/**
* Return {@code true} if the current user may be a super-user. Be aware that this is just an hint and so it may
* return false-positives.
*/
public static boolean maybeSuperUser() {
return MAYBE_SUPER_USER;
}
/**
* Return the version of Java under which this library is used.
*/
public static int javaVersion() {
return PlatformDependent0.javaVersion();
}
/**
* Returns {@code true} if and only if it is fine to enable TCP_NODELAY socket option by default.
*/
public static boolean canEnableTcpNoDelayByDefault() {
return CAN_ENABLE_TCP_NODELAY_BY_DEFAULT;
}
/**
* Return {@code true} if {@code sun.misc.Unsafe} was found on the classpath and can be used for accelerated
* direct memory access.
*/
public static boolean hasUnsafe() {
return UNSAFE_UNAVAILABILITY_CAUSE == null;
}
/**
* Return the reason (if any) why {@code sun.misc.Unsafe} was not available.
*/
public static Throwable getUnsafeUnavailabilityCause() {
return UNSAFE_UNAVAILABILITY_CAUSE;
}
/**
* {@code true} if and only if the platform supports unaligned access.
*
* @see <a href="https://en.wikipedia.org/wiki/Segmentation_fault#Bus_error">Wikipedia on segfault</a>
*/
public static boolean isUnaligned() {
return PlatformDependent0.isUnaligned();
}
/**
* Returns {@code true} if the platform has reliable low-level direct buffer access API and a user has not specified
* {@code -Dio.netty.noPreferDirect} option.
*/
public static boolean directBufferPreferred() {
return DIRECT_BUFFER_PREFERRED;
}
/**
* Returns the maximum memory reserved for direct buffer allocation.
*/
public static long maxDirectMemory() {
return DIRECT_MEMORY_LIMIT;
}
/**
* Returns the current memory reserved for direct buffer allocation.
* This method returns -1 in case that a value is not available.
*
* @see #maxDirectMemory()
*/
public static long usedDirectMemory() {
return DIRECT_MEMORY_COUNTER != null ? DIRECT_MEMORY_COUNTER.get() : -1;
}
/**
* Returns the temporary directory.
*/
public static File tmpdir() {
return TMPDIR;
}
/**
* Returns the bit mode of the current VM (usually 32 or 64.)
*/
public static int bitMode() {
return BIT_MODE;
}
/**
* Return the address size of the OS.
* 4 (for 32 bits systems ) and 8 (for 64 bits systems).
*/
public static int addressSize() {
return ADDRESS_SIZE;
}
public static long allocateMemory(long size) {
return PlatformDependent0.allocateMemory(size);
}
public static void freeMemory(long address) {
PlatformDependent0.freeMemory(address);
}
public static long reallocateMemory(long address, long newSize) {
return PlatformDependent0.reallocateMemory(address, newSize);
}
/**
* Raises an exception bypassing compiler checks for checked exceptions.
*/
public static void throwException(Throwable t) {
if (hasUnsafe()) {
PlatformDependent0.throwException(t);
} else {
PlatformDependent.<RuntimeException>throwException0(t);
}
}
@SuppressWarnings("unchecked")
private static <E extends Throwable> void throwException0(Throwable t) throws E {
throw (E) t;
}
/**
* Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap() {
return new ConcurrentHashMap<K, V>();
}
/**
* Creates a new fastest {@link LongCounter} implementation for the current platform.
*/
public static LongCounter newLongCounter() {
if (javaVersion() >= 8) {
return new LongAdderCounter();
} else {
return new AtomicLongCounter();
}
}
/**
* Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(int initialCapacity) {
return new ConcurrentHashMap<K, V>(initialCapacity);
}
/**
* Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(int initialCapacity, float loadFactor) {
return new ConcurrentHashMap<K, V>(initialCapacity, loadFactor);
}
/**
* Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(
int initialCapacity, float loadFactor, int concurrencyLevel) {
return new ConcurrentHashMap<K, V>(initialCapacity, loadFactor, concurrencyLevel);
}
/**
* Creates a new fastest {@link ConcurrentMap} implementation for the current platform.
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(Map<? extends K, ? extends V> map) {
return new ConcurrentHashMap<K, V>(map);
}
/**
* Try to deallocate the specified direct {@link ByteBuffer}. Please note this method does nothing if
* the current platform does not support this operation or the specified buffer is not a direct buffer.
*/
public static void freeDirectBuffer(ByteBuffer buffer) {
CLEANER.freeDirectBuffer(buffer);
}
public static long directBufferAddress(ByteBuffer buffer) {
return PlatformDependent0.directBufferAddress(buffer);
}
public static ByteBuffer directBuffer(long memoryAddress, int size) {
if (PlatformDependent0.hasDirectBufferNoCleanerConstructor()) {
return PlatformDependent0.newDirectBuffer(memoryAddress, size);
}
throw new UnsupportedOperationException(
"sun.misc.Unsafe or java.nio.DirectByteBuffer.<init>(long, int) not available");
}
public static Object getObject(Object object, long fieldOffset) {
return PlatformDependent0.getObject(object, fieldOffset);
}
public static int getInt(Object object, long fieldOffset) {
return PlatformDependent0.getInt(object, fieldOffset);
}
public static int getIntVolatile(long address) {
return PlatformDependent0.getIntVolatile(address);
}
public static void putIntOrdered(long adddress, int newValue) {
PlatformDependent0.putIntOrdered(adddress, newValue);
}
public static byte getByte(long address) {
return PlatformDependent0.getByte(address);
}
public static short getShort(long address) {
return PlatformDependent0.getShort(address);
}
public static int getInt(long address) {
return PlatformDependent0.getInt(address);
}
public static long getLong(long address) {
return PlatformDependent0.getLong(address);
}
public static byte getByte(byte[] data, int index) {
return PlatformDependent0.getByte(data, index);
}
public static byte getByte(byte[] data, long index) {
return PlatformDependent0.getByte(data, index);
}
public static short getShort(byte[] data, int index) {
return PlatformDependent0.getShort(data, index);
}
public static int getInt(byte[] data, int index) {
return PlatformDependent0.getInt(data, index);
}
public static int getInt(int[] data, long index) {
return PlatformDependent0.getInt(data, index);
}
public static long getLong(byte[] data, int index) {
return PlatformDependent0.getLong(data, index);
}
public static long getLong(long[] data, long index) {
return PlatformDependent0.getLong(data, index);
}
private static long getLongSafe(byte[] bytes, int offset) {
if (BIG_ENDIAN_NATIVE_ORDER) {
return (long) bytes[offset] << 56 |
((long) bytes[offset + 1] & 0xff) << 48 |
((long) bytes[offset + 2] & 0xff) << 40 |
((long) bytes[offset + 3] & 0xff) << 32 |
((long) bytes[offset + 4] & 0xff) << 24 |
((long) bytes[offset + 5] & 0xff) << 16 |
((long) bytes[offset + 6] & 0xff) << 8 |
(long) bytes[offset + 7] & 0xff;
}
return (long) bytes[offset] & 0xff |
((long) bytes[offset + 1] & 0xff) << 8 |
((long) bytes[offset + 2] & 0xff) << 16 |
((long) bytes[offset + 3] & 0xff) << 24 |
((long) bytes[offset + 4] & 0xff) << 32 |
((long) bytes[offset + 5] & 0xff) << 40 |
((long) bytes[offset + 6] & 0xff) << 48 |
(long) bytes[offset + 7] << 56;
}
private static int getIntSafe(byte[] bytes, int offset) {
if (BIG_ENDIAN_NATIVE_ORDER) {
return bytes[offset] << 24 |
(bytes[offset + 1] & 0xff) << 16 |
(bytes[offset + 2] & 0xff) << 8 |
bytes[offset + 3] & 0xff;
}
return bytes[offset] & 0xff |
(bytes[offset + 1] & 0xff) << 8 |
(bytes[offset + 2] & 0xff) << 16 |
bytes[offset + 3] << 24;
}
private static short getShortSafe(byte[] bytes, int offset) {
if (BIG_ENDIAN_NATIVE_ORDER) {
return (short) (bytes[offset] << 8 | (bytes[offset + 1] & 0xff));
}
return (short) (bytes[offset] & 0xff | (bytes[offset + 1] << 8));
}
/**
* Identical to {@link PlatformDependent0#hashCodeAsciiCompute(long, int)} but for {@link CharSequence}.
*/
private static int hashCodeAsciiCompute(CharSequence value, int offset, int hash) {
if (BIG_ENDIAN_NATIVE_ORDER) {
return hash * HASH_CODE_C1 +
// Low order int
hashCodeAsciiSanitizeInt(value, offset + 4) * HASH_CODE_C2 +
// High order int
hashCodeAsciiSanitizeInt(value, offset);
}
return hash * HASH_CODE_C1 +
// Low order int
hashCodeAsciiSanitizeInt(value, offset) * HASH_CODE_C2 +
// High order int
hashCodeAsciiSanitizeInt(value, offset + 4);
}
/**
* Identical to {@link PlatformDependent0#hashCodeAsciiSanitize(int)} but for {@link CharSequence}.
*/
private static int hashCodeAsciiSanitizeInt(CharSequence value, int offset) {
if (BIG_ENDIAN_NATIVE_ORDER) {
// mimic a unsafe.getInt call on a big endian machine
return (value.charAt(offset + 3) & 0x1f) |
(value.charAt(offset + 2) & 0x1f) << 8 |
(value.charAt(offset + 1) & 0x1f) << 16 |
(value.charAt(offset) & 0x1f) << 24;
}
return (value.charAt(offset + 3) & 0x1f) << 24 |
(value.charAt(offset + 2) & 0x1f) << 16 |
(value.charAt(offset + 1) & 0x1f) << 8 |
(value.charAt(offset) & 0x1f);
}
/**
* Identical to {@link PlatformDependent0#hashCodeAsciiSanitize(short)} but for {@link CharSequence}.
*/
private static int hashCodeAsciiSanitizeShort(CharSequence value, int offset) {
if (BIG_ENDIAN_NATIVE_ORDER) {
// mimic a unsafe.getShort call on a big endian machine
return (value.charAt(offset + 1) & 0x1f) |
(value.charAt(offset) & 0x1f) << 8;
}
return (value.charAt(offset + 1) & 0x1f) << 8 |
(value.charAt(offset) & 0x1f);
}
/**
* Identical to {@link PlatformDependent0#hashCodeAsciiSanitize(byte)} but for {@link CharSequence}.
*/
private static int hashCodeAsciiSanitizeByte(char value) {
return value & 0x1f;
}
public static void putByte(long address, byte value) {
PlatformDependent0.putByte(address, value);
}
public static void putShort(long address, short value) {
PlatformDependent0.putShort(address, value);
}
public static void putInt(long address, int value) {
PlatformDependent0.putInt(address, value);
}
public static void putLong(long address, long value) {
PlatformDependent0.putLong(address, value);
}
public static void putByte(byte[] data, int index, byte value) {
PlatformDependent0.putByte(data, index, value);
}
public static void putByte(Object data, long offset, byte value) {
PlatformDependent0.putByte(data, offset, value);
}
public static void putShort(byte[] data, int index, short value) {
PlatformDependent0.putShort(data, index, value);
}
public static void putInt(byte[] data, int index, int value) {
PlatformDependent0.putInt(data, index, value);
}
public static void putLong(byte[] data, int index, long value) {
PlatformDependent0.putLong(data, index, value);
}
public static void putObject(Object o, long offset, Object x) {
PlatformDependent0.putObject(o, offset, x);
}
public static long objectFieldOffset(Field field) {
return PlatformDependent0.objectFieldOffset(field);
}
public static void copyMemory(long srcAddr, long dstAddr, long length) {
PlatformDependent0.copyMemory(srcAddr, dstAddr, length);
}
public static void copyMemory(byte[] src, int srcIndex, long dstAddr, long length) {
PlatformDependent0.copyMemory(src, BYTE_ARRAY_BASE_OFFSET + srcIndex, null, dstAddr, length);
}
public static void copyMemory(byte[] src, int srcIndex, byte[] dst, int dstIndex, long length) {
PlatformDependent0.copyMemory(src, BYTE_ARRAY_BASE_OFFSET + srcIndex,
dst, BYTE_ARRAY_BASE_OFFSET + dstIndex, length);
}
public static void copyMemory(long srcAddr, byte[] dst, int dstIndex, long length) {
PlatformDependent0.copyMemory(null, srcAddr, dst, BYTE_ARRAY_BASE_OFFSET + dstIndex, length);
}
public static void setMemory(byte[] dst, int dstIndex, long bytes, byte value) {
PlatformDependent0.setMemory(dst, BYTE_ARRAY_BASE_OFFSET + dstIndex, bytes, value);
}
public static void setMemory(long address, long bytes, byte value) {
PlatformDependent0.setMemory(address, bytes, value);
}
/**
* Allocate a new {@link ByteBuffer} with the given {@code capacity}. {@link ByteBuffer}s allocated with
* this method <strong>MUST</strong> be deallocated via {@link #freeDirectNoCleaner(ByteBuffer)}.
*/
public static ByteBuffer allocateDirectNoCleaner(int capacity) {
assert USE_DIRECT_BUFFER_NO_CLEANER;
incrementMemoryCounter(capacity);
try {
return PlatformDependent0.allocateDirectNoCleaner(capacity);
} catch (Throwable e) {
decrementMemoryCounter(capacity);
throwException(e);
return null;
}
}
/**
* Reallocate a new {@link ByteBuffer} with the given {@code capacity}. {@link ByteBuffer}s reallocated with
* this method <strong>MUST</strong> be deallocated via {@link #freeDirectNoCleaner(ByteBuffer)}.
*/
public static ByteBuffer reallocateDirectNoCleaner(ByteBuffer buffer, int capacity) {
assert USE_DIRECT_BUFFER_NO_CLEANER;
int len = capacity - buffer.capacity();
incrementMemoryCounter(len);
try {
return PlatformDependent0.reallocateDirectNoCleaner(buffer, capacity);
} catch (Throwable e) {
decrementMemoryCounter(len);
throwException(e);
return null;
}
}
/**
* This method <strong>MUST</strong> only be called for {@link ByteBuffer}s that were allocated via
* {@link #allocateDirectNoCleaner(int)}.
*/
public static void freeDirectNoCleaner(ByteBuffer buffer) {
assert USE_DIRECT_BUFFER_NO_CLEANER;
int capacity = buffer.capacity();
PlatformDependent0.freeMemory(PlatformDependent0.directBufferAddress(buffer));
decrementMemoryCounter(capacity);
}
private static void incrementMemoryCounter(int capacity) {
if (DIRECT_MEMORY_COUNTER != null) {
long newUsedMemory = DIRECT_MEMORY_COUNTER.addAndGet(capacity);
if (newUsedMemory > DIRECT_MEMORY_LIMIT) {
DIRECT_MEMORY_COUNTER.addAndGet(-capacity);
throw new OutOfDirectMemoryError("failed to allocate " + capacity
+ " byte(s) of direct memory (used: " + (newUsedMemory - capacity)
+ ", max: " + DIRECT_MEMORY_LIMIT + ')');
}
}
}
private static void decrementMemoryCounter(int capacity) {
if (DIRECT_MEMORY_COUNTER != null) {
long usedMemory = DIRECT_MEMORY_COUNTER.addAndGet(-capacity);
assert usedMemory >= 0;
}
}
public static boolean useDirectBufferNoCleaner() {
return USE_DIRECT_BUFFER_NO_CLEANER;
}
/**
* Compare two {@code byte} arrays for equality. For performance reasons no bounds checking on the
* parameters is performed.
*
* @param bytes1 the first byte array.
* @param startPos1 the position (inclusive) to start comparing in {@code bytes1}.
* @param bytes2 the second byte array.
* @param startPos2 the position (inclusive) to start comparing in {@code bytes2}.
* @param length the amount of bytes to compare. This is assumed to be validated as not going out of bounds
* by the caller.
*/
public static boolean equals(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
return !hasUnsafe() || !unalignedAccess() ?
equalsSafe(bytes1, startPos1, bytes2, startPos2, length) :
PlatformDependent0.equals(bytes1, startPos1, bytes2, startPos2, length);
}
/**
* Determine if a subsection of an array is zero.
* @param bytes The byte array.
* @param startPos The starting index (inclusive) in {@code bytes}.
* @param length The amount of bytes to check for zero.
* @return {@code false} if {@code bytes[startPos:startsPos+length)} contains a value other than zero.
*/
public static boolean isZero(byte[] bytes, int startPos, int length) {
return !hasUnsafe() || !unalignedAccess() ?
isZeroSafe(bytes, startPos, length) :
PlatformDependent0.isZero(bytes, startPos, length);
}
/**
* Compare two {@code byte} arrays for equality without leaking timing information.
* For performance reasons no bounds checking on the parameters is performed.
* <p>
* The {@code int} return type is intentional and is designed to allow cascading of constant time operations:
* <pre>
* byte[] s1 = new {1, 2, 3};
* byte[] s2 = new {1, 2, 3};
* byte[] s3 = new {1, 2, 3};
* byte[] s4 = new {4, 5, 6};
* boolean equals = (equalsConstantTime(s1, 0, s2, 0, s1.length) &
* equalsConstantTime(s3, 0, s4, 0, s3.length)) != 0;
* </pre>
* @param bytes1 the first byte array.
* @param startPos1 the position (inclusive) to start comparing in {@code bytes1}.
* @param bytes2 the second byte array.
* @param startPos2 the position (inclusive) to start comparing in {@code bytes2}.
* @param length the amount of bytes to compare. This is assumed to be validated as not going out of bounds
* by the caller.
* @return {@code 0} if not equal. {@code 1} if equal.
*/
public static int equalsConstantTime(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
return !hasUnsafe() || !unalignedAccess() ?
ConstantTimeUtils.equalsConstantTime(bytes1, startPos1, bytes2, startPos2, length) :
PlatformDependent0.equalsConstantTime(bytes1, startPos1, bytes2, startPos2, length);
}
/**
* Calculate a hash code of a byte array assuming ASCII character encoding.
* The resulting hash code will be case insensitive.
* @param bytes The array which contains the data to hash.
* @param startPos What index to start generating a hash code in {@code bytes}
* @param length The amount of bytes that should be accounted for in the computation.
* @return The hash code of {@code bytes} assuming ASCII character encoding.
* The resulting hash code will be case insensitive.
*/
public static int hashCodeAscii(byte[] bytes, int startPos, int length) {
return !hasUnsafe() || !unalignedAccess() ?
hashCodeAsciiSafe(bytes, startPos, length) :
PlatformDependent0.hashCodeAscii(bytes, startPos, length);
}
/**
* Calculate a hash code of a byte array assuming ASCII character encoding.
* The resulting hash code will be case insensitive.
* <p>
* This method assumes that {@code bytes} is equivalent to a {@code byte[]} but just using {@link CharSequence}
* for storage. The upper most byte of each {@code char} from {@code bytes} is ignored.
* @param bytes The array which contains the data to hash (assumed to be equivalent to a {@code byte[]}).
* @return The hash code of {@code bytes} assuming ASCII character encoding.
* The resulting hash code will be case insensitive.
*/
public static int hashCodeAscii(CharSequence bytes) {
final int length = bytes.length();
final int remainingBytes = length & 7;
int hash = HASH_CODE_ASCII_SEED;
// Benchmarking shows that by just naively looping for inputs 8~31 bytes long we incur a relatively large
// performance penalty (only achieve about 60% performance of loop which iterates over each char). So because
// of this we take special provisions to unroll the looping for these conditions.
if (length >= 32) {
for (int i = length - 8; i >= remainingBytes; i -= 8) {
hash = hashCodeAsciiCompute(bytes, i, hash);
}
} else if (length >= 8) {
hash = hashCodeAsciiCompute(bytes, length - 8, hash);
if (length >= 16) {
hash = hashCodeAsciiCompute(bytes, length - 16, hash);
if (length >= 24) {
hash = hashCodeAsciiCompute(bytes, length - 24, hash);
}
}
}
if (remainingBytes == 0) {
return hash;
}
int offset = 0;
if (remainingBytes != 2 & remainingBytes != 4 & remainingBytes != 6) { // 1, 3, 5, 7
hash = hash * HASH_CODE_C1 + hashCodeAsciiSanitizeByte(bytes.charAt(0));
offset = 1;
}
if (remainingBytes != 1 & remainingBytes != 4 & remainingBytes != 5) { // 2, 3, 6, 7
hash = hash * (offset == 0 ? HASH_CODE_C1 : HASH_CODE_C2)
+ hashCodeAsciiSanitize(hashCodeAsciiSanitizeShort(bytes, offset));
offset += 2;
}
if (remainingBytes >= 4) { // 4, 5, 6, 7
return hash * ((offset == 0 | offset == 3) ? HASH_CODE_C1 : HASH_CODE_C2)
+ hashCodeAsciiSanitizeInt(bytes, offset);
}
return hash;
}
private static final class Mpsc {
private static final boolean USE_MPSC_CHUNKED_ARRAY_QUEUE;
private Mpsc() {
}
static {
Object unsafe = null;
if (hasUnsafe()) {
// jctools goes through its own process of initializing unsafe; of
// course, this requires permissions which might not be granted to calling code, so we
// must mark this block as privileged too
unsafe = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
// force JCTools to initialize unsafe
return UnsafeAccess.UNSAFE;
}
});
}
if (unsafe == null) {
logger.debug("org.jctools-core.MpscChunkedArrayQueue: unavailable");
USE_MPSC_CHUNKED_ARRAY_QUEUE = false;
} else {
logger.debug("org.jctools-core.MpscChunkedArrayQueue: available");
USE_MPSC_CHUNKED_ARRAY_QUEUE = true;
}
}
static <T> Queue<T> newMpscQueue(final int maxCapacity) {
// Calculate the max capacity which can not be bigger than MAX_ALLOWED_MPSC_CAPACITY.
// This is forced by the MpscChunkedArrayQueue implementation as will try to round it
// up to the next power of two and so will overflow otherwise.
final int capacity = max(min(maxCapacity, MAX_ALLOWED_MPSC_CAPACITY), MIN_MAX_MPSC_CAPACITY);
return USE_MPSC_CHUNKED_ARRAY_QUEUE ? new MpscChunkedArrayQueue<T>(MPSC_CHUNK_SIZE, capacity)
: new MpscChunkedAtomicArrayQueue<T>(MPSC_CHUNK_SIZE, capacity);
}
static <T> Queue<T> newMpscQueue() {
return USE_MPSC_CHUNKED_ARRAY_QUEUE ? new MpscUnboundedArrayQueue<T>(MPSC_CHUNK_SIZE)
: new MpscUnboundedAtomicArrayQueue<T>(MPSC_CHUNK_SIZE);
}
}
/**
* Create a new {@link Queue} which is safe to use for multiple producers (different threads) and a single
* consumer (one thread!).
* @return A MPSC queue which may be unbounded.
*/
public static <T> Queue<T> newMpscQueue() {
return Mpsc.newMpscQueue();
}
/**
* Create a new {@link Queue} which is safe to use for multiple producers (different threads) and a single
* consumer (one thread!).
*/
public static <T> Queue<T> newMpscQueue(final int maxCapacity) {
return Mpsc.newMpscQueue(maxCapacity);
}
/**
* Create a new {@link Queue} which is safe to use for single producer (one thread!) and a single
* consumer (one thread!).
*/
public static <T> Queue<T> newSpscQueue() {
return hasUnsafe() ? new SpscLinkedQueue<T>() : new SpscLinkedAtomicQueue<T>();
}
/**
* Create a new {@link Queue} which is safe to use for multiple producers (different threads) and a single
* consumer (one thread!) with the given fixes {@code capacity}.
*/
public static <T> Queue<T> newFixedMpscQueue(int capacity) {
return hasUnsafe() ? new MpscArrayQueue<T>(capacity) : new MpscAtomicArrayQueue<T>(capacity);
}
/**
* Return the {@link ClassLoader} for the given {@link Class}.
*/
public static ClassLoader getClassLoader(final Class<?> clazz) {
return PlatformDependent0.getClassLoader(clazz);
}
/**
* Return the context {@link ClassLoader} for the current {@link Thread}.
*/
public static ClassLoader getContextClassLoader() {
return PlatformDependent0.getContextClassLoader();
}
/**
* Return the system {@link ClassLoader}.
*/
public static ClassLoader getSystemClassLoader() {
return PlatformDependent0.getSystemClassLoader();
}
/**
* Returns a new concurrent {@link Deque}.
*/
@SuppressJava6Requirement(reason = "Usage guarded by java version check")
public static <C> Deque<C> newConcurrentDeque() {
if (javaVersion() < 7) {
return new LinkedBlockingDeque<C>();
} else {
return new ConcurrentLinkedDeque<C>();
}
}
/**
* Return a {@link Random} which is not-threadsafe and so can only be used from the same thread.
*/
public static Random threadLocalRandom() {
return RANDOM_PROVIDER.current();
}
private static boolean isWindows0() {
boolean windows = SystemPropertyUtil.get("os.name", "").toLowerCase(Locale.US).contains("win");
if (windows) {
logger.debug("Platform: Windows");
}
return windows;
}
private static boolean isOsx0() {
String osname = SystemPropertyUtil.get("os.name", "").toLowerCase(Locale.US)
.replaceAll("[^a-z0-9]+", "");
boolean osx = osname.startsWith("macosx") || osname.startsWith("osx");
if (osx) {
logger.debug("Platform: MacOS");
}
return osx;
}
private static boolean maybeSuperUser0() {
String username = SystemPropertyUtil.get("user.name");
if (isWindows()) {
return "Administrator".equals(username);
}
// Check for root and toor as some BSDs have a toor user that is basically the same as root.
return "root".equals(username) || "toor".equals(username);
}
private static Throwable unsafeUnavailabilityCause0() {
if (isAndroid()) {
logger.debug("sun.misc.Unsafe: unavailable (Android)");
return new UnsupportedOperationException("sun.misc.Unsafe: unavailable (Android)");
}
if (isIkvmDotNet()) {
logger.debug("sun.misc.Unsafe: unavailable (IKVM.NET)");
return new UnsupportedOperationException("sun.misc.Unsafe: unavailable (IKVM.NET)");
}
Throwable cause = PlatformDependent0.getUnsafeUnavailabilityCause();
if (cause != null) {
return cause;
}
try {
boolean hasUnsafe = PlatformDependent0.hasUnsafe();
logger.debug("sun.misc.Unsafe: {}", hasUnsafe ? "available" : "unavailable");
return hasUnsafe ? null : PlatformDependent0.getUnsafeUnavailabilityCause();
} catch (Throwable t) {
logger.trace("Could not determine if Unsafe is available", t);
// Probably failed to initialize PlatformDependent0.
return new UnsupportedOperationException("Could not determine if Unsafe is available", t);
}
}
/**
* Returns {@code true} if the running JVM is either <a href="https://developer.ibm.com/javasdk/">IBM J9</a> or
* <a href="https://www.eclipse.org/openj9/">Eclipse OpenJ9</a>, {@code false} otherwise.
*/
public static boolean isJ9Jvm() {
return IS_J9_JVM;
}
private static boolean isJ9Jvm0() {
String vmName = SystemPropertyUtil.get("java.vm.name", "").toLowerCase();
return vmName.startsWith("ibm j9") || vmName.startsWith("eclipse openj9");
}
/**
* Returns {@code true} if the running JVM is <a href="https://www.ikvm.net">IKVM.NET</a>, {@code false} otherwise.
*/
public static boolean isIkvmDotNet() {
return IS_IVKVM_DOT_NET;
}
private static boolean isIkvmDotNet0() {
String vmName = SystemPropertyUtil.get("java.vm.name", "").toUpperCase(Locale.US);
return vmName.equals("IKVM.NET");
}
private static long maxDirectMemory0() {
long maxDirectMemory = 0;
ClassLoader systemClassLoader = null;
try {
systemClassLoader = getSystemClassLoader();
// When using IBM J9 / Eclipse OpenJ9 we should not use VM.maxDirectMemory() as it not reflects the
// correct value.
// See:
// - https://github.com/netty/netty/issues/7654
String vmName = SystemPropertyUtil.get("java.vm.name", "").toLowerCase();
if (!vmName.startsWith("ibm j9") &&
// https://github.com/eclipse/openj9/blob/openj9-0.8.0/runtime/include/vendor_version.h#L53
!vmName.startsWith("eclipse openj9")) {
// Try to get from sun.misc.VM.maxDirectMemory() which should be most accurate.
Class<?> vmClass = Class.forName("sun.misc.VM", true, systemClassLoader);
Method m = vmClass.getDeclaredMethod("maxDirectMemory");
maxDirectMemory = ((Number) m.invoke(null)).longValue();
}
} catch (Throwable ignored) {
// Ignore
}
if (maxDirectMemory > 0) {
return maxDirectMemory;
}
try {
// Now try to get the JVM option (-XX:MaxDirectMemorySize) and parse it.
// Note that we are using reflection because Android doesn't have these classes.
Class<?> mgmtFactoryClass = Class.forName(
"java.lang.management.ManagementFactory", true, systemClassLoader);
Class<?> runtimeClass = Class.forName(
"java.lang.management.RuntimeMXBean", true, systemClassLoader);
Object runtime = mgmtFactoryClass.getDeclaredMethod("getRuntimeMXBean").invoke(null);
@SuppressWarnings("unchecked")
List<String> vmArgs = (List<String>) runtimeClass.getDeclaredMethod("getInputArguments").invoke(runtime);
for (int i = vmArgs.size() - 1; i >= 0; i --) {
Matcher m = MAX_DIRECT_MEMORY_SIZE_ARG_PATTERN.matcher(vmArgs.get(i));
if (!m.matches()) {
continue;
}
maxDirectMemory = Long.parseLong(m.group(1));
switch (m.group(2).charAt(0)) {
case 'k': case 'K':
maxDirectMemory *= 1024;
break;
case 'm': case 'M':
maxDirectMemory *= 1024 * 1024;
break;
case 'g': case 'G':
maxDirectMemory *= 1024 * 1024 * 1024;
break;
default:
break;
}
break;
}
} catch (Throwable ignored) {
// Ignore
}
if (maxDirectMemory <= 0) {
maxDirectMemory = Runtime.getRuntime().maxMemory();
logger.debug("maxDirectMemory: {} bytes (maybe)", maxDirectMemory);
} else {
logger.debug("maxDirectMemory: {} bytes", maxDirectMemory);
}
return maxDirectMemory;
}
private static File tmpdir0() {
File f;
try {
f = toDirectory(SystemPropertyUtil.get("io.netty.tmpdir"));
if (f != null) {
logger.debug("-Dio.netty.tmpdir: {}", f);
return f;
}
f = toDirectory(SystemPropertyUtil.get("java.io.tmpdir"));
if (f != null) {
logger.debug("-Dio.netty.tmpdir: {} (java.io.tmpdir)", f);
return f;
}
// This shouldn't happen, but just in case ..
if (isWindows()) {
f = toDirectory(System.getenv("TEMP"));
if (f != null) {
logger.debug("-Dio.netty.tmpdir: {} (%TEMP%)", f);
return f;
}
String userprofile = System.getenv("USERPROFILE");
if (userprofile != null) {
f = toDirectory(userprofile + "\\AppData\\Local\\Temp");
if (f != null) {
logger.debug("-Dio.netty.tmpdir: {} (%USERPROFILE%\\AppData\\Local\\Temp)", f);
return f;
}
f = toDirectory(userprofile + "\\Local Settings\\Temp");
if (f != null) {
logger.debug("-Dio.netty.tmpdir: {} (%USERPROFILE%\\Local Settings\\Temp)", f);
return f;
}
}
} else {
f = toDirectory(System.getenv("TMPDIR"));
if (f != null) {
logger.debug("-Dio.netty.tmpdir: {} ($TMPDIR)", f);
return f;
}
}
} catch (Throwable ignored) {
// Environment variable inaccessible
}
// Last resort.
if (isWindows()) {
f = new File("C:\\Windows\\Temp");
} else {
f = new File("/tmp");
}
logger.warn("Failed to get the temporary directory; falling back to: {}", f);
return f;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static File toDirectory(String path) {
if (path == null) {
return null;
}
File f = new File(path);
f.mkdirs();
if (!f.isDirectory()) {
return null;
}
try {
return f.getAbsoluteFile();
} catch (Exception ignored) {
return f;
}
}
private static int bitMode0() {
// Check user-specified bit mode first.
int bitMode = SystemPropertyUtil.getInt("io.netty.bitMode", 0);
if (bitMode > 0) {
logger.debug("-Dio.netty.bitMode: {}", bitMode);
return bitMode;
}
// And then the vendor specific ones which is probably most reliable.
bitMode = SystemPropertyUtil.getInt("sun.arch.data.model", 0);
if (bitMode > 0) {
logger.debug("-Dio.netty.bitMode: {} (sun.arch.data.model)", bitMode);
return bitMode;
}
bitMode = SystemPropertyUtil.getInt("com.ibm.vm.bitmode", 0);
if (bitMode > 0) {
logger.debug("-Dio.netty.bitMode: {} (com.ibm.vm.bitmode)", bitMode);
return bitMode;
}
// os.arch also gives us a good hint.
String arch = SystemPropertyUtil.get("os.arch", "").toLowerCase(Locale.US).trim();
if ("amd64".equals(arch) || "x86_64".equals(arch)) {
bitMode = 64;
} else if ("i386".equals(arch) || "i486".equals(arch) || "i586".equals(arch) || "i686".equals(arch)) {
bitMode = 32;
}
if (bitMode > 0) {
logger.debug("-Dio.netty.bitMode: {} (os.arch: {})", bitMode, arch);
}
// Last resort: guess from VM name and then fall back to most common 64-bit mode.
String vm = SystemPropertyUtil.get("java.vm.name", "").toLowerCase(Locale.US);
Pattern bitPattern = Pattern.compile("([1-9][0-9]+)-?bit");
Matcher m = bitPattern.matcher(vm);
if (m.find()) {
return Integer.parseInt(m.group(1));
} else {
return 64;
}
}
private static int addressSize0() {
if (!hasUnsafe()) {
return -1;
}
return PlatformDependent0.addressSize();
}
private static long byteArrayBaseOffset0() {
if (!hasUnsafe()) {
return -1;
}
return PlatformDependent0.byteArrayBaseOffset();
}
private static boolean equalsSafe(byte[] bytes1, int startPos1, byte[] bytes2, int startPos2, int length) {
final int end = startPos1 + length;
for (; startPos1 < end; ++startPos1, ++startPos2) {
if (bytes1[startPos1] != bytes2[startPos2]) {
return false;
}
}
return true;
}
private static boolean isZeroSafe(byte[] bytes, int startPos, int length) {
final int end = startPos + length;
for (; startPos < end; ++startPos) {
if (bytes[startPos] != 0) {
return false;
}
}
return true;
}
/**
* Package private for testing purposes only!
*/
static int hashCodeAsciiSafe(byte[] bytes, int startPos, int length) {
int hash = HASH_CODE_ASCII_SEED;
final int remainingBytes = length & 7;
final int end = startPos + remainingBytes;
for (int i = startPos - 8 + length; i >= end; i -= 8) {
hash = PlatformDependent0.hashCodeAsciiCompute(getLongSafe(bytes, i), hash);
}
switch(remainingBytes) {
case 7:
return ((hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]))
* HASH_CODE_C2 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos + 1)))
* HASH_CODE_C1 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos + 3));
case 6:
return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos)))
* HASH_CODE_C2 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos + 2));
case 5:
return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]))
* HASH_CODE_C2 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos + 1));
case 4:
return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(getIntSafe(bytes, startPos));
case 3:
return (hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]))
* HASH_CODE_C2 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos + 1));
case 2:
return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(getShortSafe(bytes, startPos));
case 1:
return hash * HASH_CODE_C1 + hashCodeAsciiSanitize(bytes[startPos]);
default:
return hash;
}
}
public static String normalizedArch() {
return NORMALIZED_ARCH;
}
public static String normalizedOs() {
return NORMALIZED_OS;
}
public static Set<String> normalizedLinuxClassifiers() {
return LINUX_OS_CLASSIFIERS;
}
@SuppressJava6Requirement(reason = "Guarded by version check")
public static File createTempFile(String prefix, String suffix, File directory) throws IOException {
if (javaVersion() >= 7) {
if (directory == null) {
return Files.createTempFile(prefix, suffix).toFile();
}
return Files.createTempFile(directory.toPath(), prefix, suffix).toFile();
}
if (directory == null) {
return File.createTempFile(prefix, suffix);
}
File file = File.createTempFile(prefix, suffix, directory);
// Try to adjust the perms, if this fails there is not much else we can do...
file.setReadable(false, false);
file.setReadable(true, true);
return file;
}
/**
* Adds only those classifier strings to <tt>dest</tt> which are present in <tt>allowed</tt>.
*
* @param allowed allowed classifiers
* @param dest destination set
* @param maybeClassifiers potential classifiers to add
*/
private static void addClassifier(Set<String> allowed, Set<String> dest, String... maybeClassifiers) {
for (String id : maybeClassifiers) {
if (allowed.contains(id)) {
dest.add(id);
}
}
}
private static String normalizeOsReleaseVariableValue(String value) {
// Variable assignment values may be enclosed in double or single quotes.
return value.trim().replaceAll("[\"']", "");
}
private static String normalize(String value) {
return value.toLowerCase(Locale.US).replaceAll("[^a-z0-9]+", "");
}
private static String normalizeArch(String value) {
value = normalize(value);
if (value.matches("^(x8664|amd64|ia32e|em64t|x64)$")) {
return "x86_64";
}
if (value.matches("^(x8632|x86|i[3-6]86|ia32|x32)$")) {
return "x86_32";
}
if (value.matches("^(ia64|itanium64)$")) {
return "itanium_64";
}
if (value.matches("^(sparc|sparc32)$")) {
return "sparc_32";
}
if (value.matches("^(sparcv9|sparc64)$")) {
return "sparc_64";
}
if (value.matches("^(arm|arm32)$")) {
return "arm_32";
}
if ("aarch64".equals(value)) {
return "aarch_64";
}
if (value.matches("^(ppc|ppc32)$")) {
return "ppc_32";
}
if ("ppc64".equals(value)) {
return "ppc_64";
}
if ("ppc64le".equals(value)) {
return "ppcle_64";
}
if ("s390".equals(value)) {
return "s390_32";
}
if ("s390x".equals(value)) {
return "s390_64";
}
return "unknown";
}
private static String normalizeOs(String value) {
value = normalize(value);
if (value.startsWith("aix")) {
return "aix";
}
if (value.startsWith("hpux")) {
return "hpux";
}
if (value.startsWith("os400")) {
// Avoid the names such as os4000
if (value.length() <= 5 || !Character.isDigit(value.charAt(5))) {
return "os400";
}
}
if (value.startsWith("linux")) {
return "linux";
}
if (value.startsWith("macosx") || value.startsWith("osx")) {
return "osx";
}
if (value.startsWith("freebsd")) {
return "freebsd";
}
if (value.startsWith("openbsd")) {
return "openbsd";
}
if (value.startsWith("netbsd")) {
return "netbsd";
}
if (value.startsWith("solaris") || value.startsWith("sunos")) {
return "sunos";
}
if (value.startsWith("windows")) {
return "windows";
}
return "unknown";
}
private static final class AtomicLongCounter extends AtomicLong implements LongCounter {
private static final long serialVersionUID = 4074772784610639305L;
@Override
public void add(long delta) {
addAndGet(delta);
}
@Override
public void increment() {
incrementAndGet();
}
@Override
public void decrement() {
decrementAndGet();
}
@Override
public long value() {
return get();
}
}
private interface ThreadLocalRandomProvider {
Random current();
}
private PlatformDependent() {
// only static method supported
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_8 |
crossvul-java_data_bad_1927_0 | /*
* Copyright 2012 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 io.netty.buffer;
import io.netty.util.ByteProcessor;
import io.netty.util.CharsetUtil;
import io.netty.util.IllegalReferenceCountException;
import io.netty.util.internal.PlatformDependent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.ReadOnlyBufferException;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ScatteringByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static io.netty.buffer.Unpooled.LITTLE_ENDIAN;
import static io.netty.buffer.Unpooled.buffer;
import static io.netty.buffer.Unpooled.copiedBuffer;
import static io.netty.buffer.Unpooled.directBuffer;
import static io.netty.buffer.Unpooled.unreleasableBuffer;
import static io.netty.buffer.Unpooled.wrappedBuffer;
import static io.netty.util.internal.EmptyArrays.EMPTY_BYTES;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
/**
* An abstract test class for channel buffers
*/
public abstract class AbstractByteBufTest {
private static final int CAPACITY = 4096; // Must be even
private static final int BLOCK_SIZE = 128;
private static final int JAVA_BYTEBUFFER_CONSISTENCY_ITERATIONS = 100;
private long seed;
private Random random;
private ByteBuf buffer;
protected final ByteBuf newBuffer(int capacity) {
return newBuffer(capacity, Integer.MAX_VALUE);
}
protected abstract ByteBuf newBuffer(int capacity, int maxCapacity);
protected boolean discardReadBytesDoesNotMoveWritableBytes() {
return true;
}
@Before
public void init() {
buffer = newBuffer(CAPACITY);
seed = System.currentTimeMillis();
random = new Random(seed);
}
@After
public void dispose() {
if (buffer != null) {
assertThat(buffer.release(), is(true));
assertThat(buffer.refCnt(), is(0));
try {
buffer.release();
} catch (Exception e) {
// Ignore.
}
buffer = null;
}
}
@Test
public void comparableInterfaceNotViolated() {
assumeFalse(buffer.isReadOnly());
buffer.writerIndex(buffer.readerIndex());
assumeTrue(buffer.writableBytes() >= 4);
buffer.writeLong(0);
ByteBuf buffer2 = newBuffer(CAPACITY);
assumeFalse(buffer2.isReadOnly());
buffer2.writerIndex(buffer2.readerIndex());
// Write an unsigned integer that will cause buffer.getUnsignedInt() - buffer2.getUnsignedInt() to underflow the
// int type and wrap around on the negative side.
buffer2.writeLong(0xF0000000L);
assertTrue(buffer.compareTo(buffer2) < 0);
assertTrue(buffer2.compareTo(buffer) > 0);
buffer2.release();
}
@Test
public void initialState() {
assertEquals(CAPACITY, buffer.capacity());
assertEquals(0, buffer.readerIndex());
}
@Test(expected = IndexOutOfBoundsException.class)
public void readerIndexBoundaryCheck1() {
try {
buffer.writerIndex(0);
} catch (IndexOutOfBoundsException e) {
fail();
}
buffer.readerIndex(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void readerIndexBoundaryCheck2() {
try {
buffer.writerIndex(buffer.capacity());
} catch (IndexOutOfBoundsException e) {
fail();
}
buffer.readerIndex(buffer.capacity() + 1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void readerIndexBoundaryCheck3() {
try {
buffer.writerIndex(CAPACITY / 2);
} catch (IndexOutOfBoundsException e) {
fail();
}
buffer.readerIndex(CAPACITY * 3 / 2);
}
@Test
public void readerIndexBoundaryCheck4() {
buffer.writerIndex(0);
buffer.readerIndex(0);
buffer.writerIndex(buffer.capacity());
buffer.readerIndex(buffer.capacity());
}
@Test(expected = IndexOutOfBoundsException.class)
public void writerIndexBoundaryCheck1() {
buffer.writerIndex(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void writerIndexBoundaryCheck2() {
try {
buffer.writerIndex(CAPACITY);
buffer.readerIndex(CAPACITY);
} catch (IndexOutOfBoundsException e) {
fail();
}
buffer.writerIndex(buffer.capacity() + 1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void writerIndexBoundaryCheck3() {
try {
buffer.writerIndex(CAPACITY);
buffer.readerIndex(CAPACITY / 2);
} catch (IndexOutOfBoundsException e) {
fail();
}
buffer.writerIndex(CAPACITY / 4);
}
@Test
public void writerIndexBoundaryCheck4() {
buffer.writerIndex(0);
buffer.readerIndex(0);
buffer.writerIndex(CAPACITY);
buffer.writeBytes(ByteBuffer.wrap(EMPTY_BYTES));
}
@Test(expected = IndexOutOfBoundsException.class)
public void getBooleanBoundaryCheck1() {
buffer.getBoolean(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getBooleanBoundaryCheck2() {
buffer.getBoolean(buffer.capacity());
}
@Test(expected = IndexOutOfBoundsException.class)
public void getByteBoundaryCheck1() {
buffer.getByte(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getByteBoundaryCheck2() {
buffer.getByte(buffer.capacity());
}
@Test(expected = IndexOutOfBoundsException.class)
public void getShortBoundaryCheck1() {
buffer.getShort(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getShortBoundaryCheck2() {
buffer.getShort(buffer.capacity() - 1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getMediumBoundaryCheck1() {
buffer.getMedium(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getMediumBoundaryCheck2() {
buffer.getMedium(buffer.capacity() - 2);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getIntBoundaryCheck1() {
buffer.getInt(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getIntBoundaryCheck2() {
buffer.getInt(buffer.capacity() - 3);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getLongBoundaryCheck1() {
buffer.getLong(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getLongBoundaryCheck2() {
buffer.getLong(buffer.capacity() - 7);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getByteArrayBoundaryCheck1() {
buffer.getBytes(-1, EMPTY_BYTES);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getByteArrayBoundaryCheck2() {
buffer.getBytes(-1, EMPTY_BYTES, 0, 0);
}
@Test
public void getByteArrayBoundaryCheck3() {
byte[] dst = new byte[4];
buffer.setInt(0, 0x01020304);
try {
buffer.getBytes(0, dst, -1, 4);
fail();
} catch (IndexOutOfBoundsException e) {
// Success
}
// No partial copy is expected.
assertEquals(0, dst[0]);
assertEquals(0, dst[1]);
assertEquals(0, dst[2]);
assertEquals(0, dst[3]);
}
@Test
public void getByteArrayBoundaryCheck4() {
byte[] dst = new byte[4];
buffer.setInt(0, 0x01020304);
try {
buffer.getBytes(0, dst, 1, 4);
fail();
} catch (IndexOutOfBoundsException e) {
// Success
}
// No partial copy is expected.
assertEquals(0, dst[0]);
assertEquals(0, dst[1]);
assertEquals(0, dst[2]);
assertEquals(0, dst[3]);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getByteBufferBoundaryCheck() {
buffer.getBytes(-1, ByteBuffer.allocate(0));
}
@Test(expected = IndexOutOfBoundsException.class)
public void copyBoundaryCheck1() {
buffer.copy(-1, 0);
}
@Test(expected = IndexOutOfBoundsException.class)
public void copyBoundaryCheck2() {
buffer.copy(0, buffer.capacity() + 1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void copyBoundaryCheck3() {
buffer.copy(buffer.capacity() + 1, 0);
}
@Test(expected = IndexOutOfBoundsException.class)
public void copyBoundaryCheck4() {
buffer.copy(buffer.capacity(), 1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void setIndexBoundaryCheck1() {
buffer.setIndex(-1, CAPACITY);
}
@Test(expected = IndexOutOfBoundsException.class)
public void setIndexBoundaryCheck2() {
buffer.setIndex(CAPACITY / 2, CAPACITY / 4);
}
@Test(expected = IndexOutOfBoundsException.class)
public void setIndexBoundaryCheck3() {
buffer.setIndex(0, CAPACITY + 1);
}
@Test
public void getByteBufferState() {
ByteBuffer dst = ByteBuffer.allocate(4);
dst.position(1);
dst.limit(3);
buffer.setByte(0, (byte) 1);
buffer.setByte(1, (byte) 2);
buffer.setByte(2, (byte) 3);
buffer.setByte(3, (byte) 4);
buffer.getBytes(1, dst);
assertEquals(3, dst.position());
assertEquals(3, dst.limit());
dst.clear();
assertEquals(0, dst.get(0));
assertEquals(2, dst.get(1));
assertEquals(3, dst.get(2));
assertEquals(0, dst.get(3));
}
@Test(expected = IndexOutOfBoundsException.class)
public void getDirectByteBufferBoundaryCheck() {
buffer.getBytes(-1, ByteBuffer.allocateDirect(0));
}
@Test
public void getDirectByteBufferState() {
ByteBuffer dst = ByteBuffer.allocateDirect(4);
dst.position(1);
dst.limit(3);
buffer.setByte(0, (byte) 1);
buffer.setByte(1, (byte) 2);
buffer.setByte(2, (byte) 3);
buffer.setByte(3, (byte) 4);
buffer.getBytes(1, dst);
assertEquals(3, dst.position());
assertEquals(3, dst.limit());
dst.clear();
assertEquals(0, dst.get(0));
assertEquals(2, dst.get(1));
assertEquals(3, dst.get(2));
assertEquals(0, dst.get(3));
}
@Test
public void testRandomByteAccess() {
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
buffer.setByte(i, value);
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
assertEquals(value, buffer.getByte(i));
}
}
@Test
public void testRandomUnsignedByteAccess() {
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
buffer.setByte(i, value);
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i ++) {
int value = random.nextInt() & 0xFF;
assertEquals(value, buffer.getUnsignedByte(i));
}
}
@Test
public void testRandomShortAccess() {
testRandomShortAccess(true);
}
@Test
public void testRandomShortLEAccess() {
testRandomShortAccess(false);
}
private void testRandomShortAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 1; i += 2) {
short value = (short) random.nextInt();
if (testBigEndian) {
buffer.setShort(i, value);
} else {
buffer.setShortLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 1; i += 2) {
short value = (short) random.nextInt();
if (testBigEndian) {
assertEquals(value, buffer.getShort(i));
} else {
assertEquals(value, buffer.getShortLE(i));
}
}
}
@Test
public void testShortConsistentWithByteBuffer() {
testShortConsistentWithByteBuffer(true, true);
testShortConsistentWithByteBuffer(true, false);
testShortConsistentWithByteBuffer(false, true);
testShortConsistentWithByteBuffer(false, false);
}
private void testShortConsistentWithByteBuffer(boolean direct, boolean testBigEndian) {
for (int i = 0; i < JAVA_BYTEBUFFER_CONSISTENCY_ITERATIONS; ++i) {
ByteBuffer javaBuffer = direct ? ByteBuffer.allocateDirect(buffer.capacity())
: ByteBuffer.allocate(buffer.capacity());
if (!testBigEndian) {
javaBuffer = javaBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
short expected = (short) (random.nextInt() & 0xFFFF);
javaBuffer.putShort(expected);
final int bufferIndex = buffer.capacity() - 2;
if (testBigEndian) {
buffer.setShort(bufferIndex, expected);
} else {
buffer.setShortLE(bufferIndex, expected);
}
javaBuffer.flip();
short javaActual = javaBuffer.getShort();
assertEquals(expected, javaActual);
assertEquals(javaActual, testBigEndian ? buffer.getShort(bufferIndex)
: buffer.getShortLE(bufferIndex));
}
}
@Test
public void testRandomUnsignedShortAccess() {
testRandomUnsignedShortAccess(true);
}
@Test
public void testRandomUnsignedShortLEAccess() {
testRandomUnsignedShortAccess(false);
}
private void testRandomUnsignedShortAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 1; i += 2) {
short value = (short) random.nextInt();
if (testBigEndian) {
buffer.setShort(i, value);
} else {
buffer.setShortLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 1; i += 2) {
int value = random.nextInt() & 0xFFFF;
if (testBigEndian) {
assertEquals(value, buffer.getUnsignedShort(i));
} else {
assertEquals(value, buffer.getUnsignedShortLE(i));
}
}
}
@Test
public void testRandomMediumAccess() {
testRandomMediumAccess(true);
}
@Test
public void testRandomMediumLEAccess() {
testRandomMediumAccess(false);
}
private void testRandomMediumAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 2; i += 3) {
int value = random.nextInt();
if (testBigEndian) {
buffer.setMedium(i, value);
} else {
buffer.setMediumLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 2; i += 3) {
int value = random.nextInt() << 8 >> 8;
if (testBigEndian) {
assertEquals(value, buffer.getMedium(i));
} else {
assertEquals(value, buffer.getMediumLE(i));
}
}
}
@Test
public void testRandomUnsignedMediumAccess() {
testRandomUnsignedMediumAccess(true);
}
@Test
public void testRandomUnsignedMediumLEAccess() {
testRandomUnsignedMediumAccess(false);
}
private void testRandomUnsignedMediumAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 2; i += 3) {
int value = random.nextInt();
if (testBigEndian) {
buffer.setMedium(i, value);
} else {
buffer.setMediumLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 2; i += 3) {
int value = random.nextInt() & 0x00FFFFFF;
if (testBigEndian) {
assertEquals(value, buffer.getUnsignedMedium(i));
} else {
assertEquals(value, buffer.getUnsignedMediumLE(i));
}
}
}
@Test
public void testMediumConsistentWithByteBuffer() {
testMediumConsistentWithByteBuffer(true, true);
testMediumConsistentWithByteBuffer(true, false);
testMediumConsistentWithByteBuffer(false, true);
testMediumConsistentWithByteBuffer(false, false);
}
private void testMediumConsistentWithByteBuffer(boolean direct, boolean testBigEndian) {
for (int i = 0; i < JAVA_BYTEBUFFER_CONSISTENCY_ITERATIONS; ++i) {
ByteBuffer javaBuffer = direct ? ByteBuffer.allocateDirect(buffer.capacity())
: ByteBuffer.allocate(buffer.capacity());
if (!testBigEndian) {
javaBuffer = javaBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
int expected = random.nextInt() & 0x00FFFFFF;
javaBuffer.putInt(expected);
final int bufferIndex = buffer.capacity() - 3;
if (testBigEndian) {
buffer.setMedium(bufferIndex, expected);
} else {
buffer.setMediumLE(bufferIndex, expected);
}
javaBuffer.flip();
int javaActual = javaBuffer.getInt();
assertEquals(expected, javaActual);
assertEquals(javaActual, testBigEndian ? buffer.getUnsignedMedium(bufferIndex)
: buffer.getUnsignedMediumLE(bufferIndex));
}
}
@Test
public void testRandomIntAccess() {
testRandomIntAccess(true);
}
@Test
public void testRandomIntLEAccess() {
testRandomIntAccess(false);
}
private void testRandomIntAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 3; i += 4) {
int value = random.nextInt();
if (testBigEndian) {
buffer.setInt(i, value);
} else {
buffer.setIntLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 3; i += 4) {
int value = random.nextInt();
if (testBigEndian) {
assertEquals(value, buffer.getInt(i));
} else {
assertEquals(value, buffer.getIntLE(i));
}
}
}
@Test
public void testIntConsistentWithByteBuffer() {
testIntConsistentWithByteBuffer(true, true);
testIntConsistentWithByteBuffer(true, false);
testIntConsistentWithByteBuffer(false, true);
testIntConsistentWithByteBuffer(false, false);
}
private void testIntConsistentWithByteBuffer(boolean direct, boolean testBigEndian) {
for (int i = 0; i < JAVA_BYTEBUFFER_CONSISTENCY_ITERATIONS; ++i) {
ByteBuffer javaBuffer = direct ? ByteBuffer.allocateDirect(buffer.capacity())
: ByteBuffer.allocate(buffer.capacity());
if (!testBigEndian) {
javaBuffer = javaBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
int expected = random.nextInt();
javaBuffer.putInt(expected);
final int bufferIndex = buffer.capacity() - 4;
if (testBigEndian) {
buffer.setInt(bufferIndex, expected);
} else {
buffer.setIntLE(bufferIndex, expected);
}
javaBuffer.flip();
int javaActual = javaBuffer.getInt();
assertEquals(expected, javaActual);
assertEquals(javaActual, testBigEndian ? buffer.getInt(bufferIndex)
: buffer.getIntLE(bufferIndex));
}
}
@Test
public void testRandomUnsignedIntAccess() {
testRandomUnsignedIntAccess(true);
}
@Test
public void testRandomUnsignedIntLEAccess() {
testRandomUnsignedIntAccess(false);
}
private void testRandomUnsignedIntAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 3; i += 4) {
int value = random.nextInt();
if (testBigEndian) {
buffer.setInt(i, value);
} else {
buffer.setIntLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 3; i += 4) {
long value = random.nextInt() & 0xFFFFFFFFL;
if (testBigEndian) {
assertEquals(value, buffer.getUnsignedInt(i));
} else {
assertEquals(value, buffer.getUnsignedIntLE(i));
}
}
}
@Test
public void testRandomLongAccess() {
testRandomLongAccess(true);
}
@Test
public void testRandomLongLEAccess() {
testRandomLongAccess(false);
}
private void testRandomLongAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 7; i += 8) {
long value = random.nextLong();
if (testBigEndian) {
buffer.setLong(i, value);
} else {
buffer.setLongLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 7; i += 8) {
long value = random.nextLong();
if (testBigEndian) {
assertEquals(value, buffer.getLong(i));
} else {
assertEquals(value, buffer.getLongLE(i));
}
}
}
@Test
public void testLongConsistentWithByteBuffer() {
testLongConsistentWithByteBuffer(true, true);
testLongConsistentWithByteBuffer(true, false);
testLongConsistentWithByteBuffer(false, true);
testLongConsistentWithByteBuffer(false, false);
}
private void testLongConsistentWithByteBuffer(boolean direct, boolean testBigEndian) {
for (int i = 0; i < JAVA_BYTEBUFFER_CONSISTENCY_ITERATIONS; ++i) {
ByteBuffer javaBuffer = direct ? ByteBuffer.allocateDirect(buffer.capacity())
: ByteBuffer.allocate(buffer.capacity());
if (!testBigEndian) {
javaBuffer = javaBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
long expected = random.nextLong();
javaBuffer.putLong(expected);
final int bufferIndex = buffer.capacity() - 8;
if (testBigEndian) {
buffer.setLong(bufferIndex, expected);
} else {
buffer.setLongLE(bufferIndex, expected);
}
javaBuffer.flip();
long javaActual = javaBuffer.getLong();
assertEquals(expected, javaActual);
assertEquals(javaActual, testBigEndian ? buffer.getLong(bufferIndex)
: buffer.getLongLE(bufferIndex));
}
}
@Test
public void testRandomFloatAccess() {
testRandomFloatAccess(true);
}
@Test
public void testRandomFloatLEAccess() {
testRandomFloatAccess(false);
}
private void testRandomFloatAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 7; i += 8) {
float value = random.nextFloat();
if (testBigEndian) {
buffer.setFloat(i, value);
} else {
buffer.setFloatLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 7; i += 8) {
float expected = random.nextFloat();
float actual = testBigEndian? buffer.getFloat(i) : buffer.getFloatLE(i);
assertEquals(expected, actual, 0.01);
}
}
@Test
public void testRandomDoubleAccess() {
testRandomDoubleAccess(true);
}
@Test
public void testRandomDoubleLEAccess() {
testRandomDoubleAccess(false);
}
private void testRandomDoubleAccess(boolean testBigEndian) {
for (int i = 0; i < buffer.capacity() - 7; i += 8) {
double value = random.nextDouble();
if (testBigEndian) {
buffer.setDouble(i, value);
} else {
buffer.setDoubleLE(i, value);
}
}
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() - 7; i += 8) {
double expected = random.nextDouble();
double actual = testBigEndian? buffer.getDouble(i) : buffer.getDoubleLE(i);
assertEquals(expected, actual, 0.01);
}
}
@Test
public void testSetZero() {
buffer.clear();
while (buffer.isWritable()) {
buffer.writeByte((byte) 0xFF);
}
for (int i = 0; i < buffer.capacity();) {
int length = Math.min(buffer.capacity() - i, random.nextInt(32));
buffer.setZero(i, length);
i += length;
}
for (int i = 0; i < buffer.capacity(); i ++) {
assertEquals(0, buffer.getByte(i));
}
}
@Test
public void testSequentialByteAccess() {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
buffer.writeByte(value);
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isWritable());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
assertEquals(value, buffer.readByte());
}
assertEquals(buffer.capacity(), buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isReadable());
assertFalse(buffer.isWritable());
}
@Test
public void testSequentialUnsignedByteAccess() {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
buffer.writeByte(value);
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isWritable());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i ++) {
int value = random.nextInt() & 0xFF;
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
assertEquals(value, buffer.readUnsignedByte());
}
assertEquals(buffer.capacity(), buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isReadable());
assertFalse(buffer.isWritable());
}
@Test
public void testSequentialShortAccess() {
testSequentialShortAccess(true);
}
@Test
public void testSequentialShortLEAccess() {
testSequentialShortAccess(false);
}
private void testSequentialShortAccess(boolean testBigEndian) {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i += 2) {
short value = (short) random.nextInt();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
if (testBigEndian) {
buffer.writeShort(value);
} else {
buffer.writeShortLE(value);
}
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isWritable());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i += 2) {
short value = (short) random.nextInt();
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
if (testBigEndian) {
assertEquals(value, buffer.readShort());
} else {
assertEquals(value, buffer.readShortLE());
}
}
assertEquals(buffer.capacity(), buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isReadable());
assertFalse(buffer.isWritable());
}
@Test
public void testSequentialUnsignedShortAccess() {
testSequentialUnsignedShortAccess(true);
}
@Test
public void testSequentialUnsignedShortLEAccess() {
testSequentialUnsignedShortAccess(true);
}
private void testSequentialUnsignedShortAccess(boolean testBigEndian) {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i += 2) {
short value = (short) random.nextInt();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
if (testBigEndian) {
buffer.writeShort(value);
} else {
buffer.writeShortLE(value);
}
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isWritable());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i += 2) {
int value = random.nextInt() & 0xFFFF;
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
if (testBigEndian) {
assertEquals(value, buffer.readUnsignedShort());
} else {
assertEquals(value, buffer.readUnsignedShortLE());
}
}
assertEquals(buffer.capacity(), buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isReadable());
assertFalse(buffer.isWritable());
}
@Test
public void testSequentialMediumAccess() {
testSequentialMediumAccess(true);
}
@Test
public void testSequentialMediumLEAccess() {
testSequentialMediumAccess(false);
}
private void testSequentialMediumAccess(boolean testBigEndian) {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() / 3 * 3; i += 3) {
int value = random.nextInt();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
if (testBigEndian) {
buffer.writeMedium(value);
} else {
buffer.writeMediumLE(value);
}
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity() / 3 * 3, buffer.writerIndex());
assertEquals(buffer.capacity() % 3, buffer.writableBytes());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() / 3 * 3; i += 3) {
int value = random.nextInt() << 8 >> 8;
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
if (testBigEndian) {
assertEquals(value, buffer.readMedium());
} else {
assertEquals(value, buffer.readMediumLE());
}
}
assertEquals(buffer.capacity() / 3 * 3, buffer.readerIndex());
assertEquals(buffer.capacity() / 3 * 3, buffer.writerIndex());
assertEquals(0, buffer.readableBytes());
assertEquals(buffer.capacity() % 3, buffer.writableBytes());
}
@Test
public void testSequentialUnsignedMediumAccess() {
testSequentialUnsignedMediumAccess(true);
}
@Test
public void testSequentialUnsignedMediumLEAccess() {
testSequentialUnsignedMediumAccess(false);
}
private void testSequentialUnsignedMediumAccess(boolean testBigEndian) {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() / 3 * 3; i += 3) {
int value = random.nextInt() & 0x00FFFFFF;
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
if (testBigEndian) {
buffer.writeMedium(value);
} else {
buffer.writeMediumLE(value);
}
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity() / 3 * 3, buffer.writerIndex());
assertEquals(buffer.capacity() % 3, buffer.writableBytes());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity() / 3 * 3; i += 3) {
int value = random.nextInt() & 0x00FFFFFF;
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
if (testBigEndian) {
assertEquals(value, buffer.readUnsignedMedium());
} else {
assertEquals(value, buffer.readUnsignedMediumLE());
}
}
assertEquals(buffer.capacity() / 3 * 3, buffer.readerIndex());
assertEquals(buffer.capacity() / 3 * 3, buffer.writerIndex());
assertEquals(0, buffer.readableBytes());
assertEquals(buffer.capacity() % 3, buffer.writableBytes());
}
@Test
public void testSequentialIntAccess() {
testSequentialIntAccess(true);
}
@Test
public void testSequentialIntLEAccess() {
testSequentialIntAccess(false);
}
private void testSequentialIntAccess(boolean testBigEndian) {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i += 4) {
int value = random.nextInt();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
if (testBigEndian) {
buffer.writeInt(value);
} else {
buffer.writeIntLE(value);
}
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isWritable());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i += 4) {
int value = random.nextInt();
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
if (testBigEndian) {
assertEquals(value, buffer.readInt());
} else {
assertEquals(value, buffer.readIntLE());
}
}
assertEquals(buffer.capacity(), buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isReadable());
assertFalse(buffer.isWritable());
}
@Test
public void testSequentialUnsignedIntAccess() {
testSequentialUnsignedIntAccess(true);
}
@Test
public void testSequentialUnsignedIntLEAccess() {
testSequentialUnsignedIntAccess(false);
}
private void testSequentialUnsignedIntAccess(boolean testBigEndian) {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i += 4) {
int value = random.nextInt();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
if (testBigEndian) {
buffer.writeInt(value);
} else {
buffer.writeIntLE(value);
}
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isWritable());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i += 4) {
long value = random.nextInt() & 0xFFFFFFFFL;
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
if (testBigEndian) {
assertEquals(value, buffer.readUnsignedInt());
} else {
assertEquals(value, buffer.readUnsignedIntLE());
}
}
assertEquals(buffer.capacity(), buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isReadable());
assertFalse(buffer.isWritable());
}
@Test
public void testSequentialLongAccess() {
testSequentialLongAccess(true);
}
@Test
public void testSequentialLongLEAccess() {
testSequentialLongAccess(false);
}
private void testSequentialLongAccess(boolean testBigEndian) {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i += 8) {
long value = random.nextLong();
assertEquals(i, buffer.writerIndex());
assertTrue(buffer.isWritable());
if (testBigEndian) {
buffer.writeLong(value);
} else {
buffer.writeLongLE(value);
}
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isWritable());
random.setSeed(seed);
for (int i = 0; i < buffer.capacity(); i += 8) {
long value = random.nextLong();
assertEquals(i, buffer.readerIndex());
assertTrue(buffer.isReadable());
if (testBigEndian) {
assertEquals(value, buffer.readLong());
} else {
assertEquals(value, buffer.readLongLE());
}
}
assertEquals(buffer.capacity(), buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
assertFalse(buffer.isReadable());
assertFalse(buffer.isWritable());
}
@Test
public void testByteArrayTransfer() {
byte[] value = new byte[BLOCK_SIZE * 2];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(value);
buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE);
}
random.setSeed(seed);
byte[] expectedValue = new byte[BLOCK_SIZE * 2];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValue);
int valueOffset = random.nextInt(BLOCK_SIZE);
buffer.getBytes(i, value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue[j], value[j]);
}
}
}
@Test
public void testRandomByteArrayTransfer1() {
byte[] value = new byte[BLOCK_SIZE];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(value);
buffer.setBytes(i, value);
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
buffer.getBytes(i, value);
for (int j = 0; j < BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value[j]);
}
}
}
@Test
public void testRandomByteArrayTransfer2() {
byte[] value = new byte[BLOCK_SIZE * 2];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(value);
buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE);
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
buffer.getBytes(i, value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value[j]);
}
}
}
@Test
public void testRandomHeapBufferTransfer1() {
byte[] valueContent = new byte[BLOCK_SIZE];
ByteBuf value = wrappedBuffer(valueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
value.setIndex(0, BLOCK_SIZE);
buffer.setBytes(i, value);
assertEquals(BLOCK_SIZE, value.readerIndex());
assertEquals(BLOCK_SIZE, value.writerIndex());
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
value.clear();
buffer.getBytes(i, value);
assertEquals(0, value.readerIndex());
assertEquals(BLOCK_SIZE, value.writerIndex());
for (int j = 0; j < BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
}
}
@Test
public void testRandomHeapBufferTransfer2() {
byte[] valueContent = new byte[BLOCK_SIZE * 2];
ByteBuf value = wrappedBuffer(valueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE);
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
buffer.getBytes(i, value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
}
}
@Test
public void testRandomDirectBufferTransfer() {
byte[] tmp = new byte[BLOCK_SIZE * 2];
ByteBuf value = directBuffer(BLOCK_SIZE * 2);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(tmp);
value.setBytes(0, tmp, 0, value.capacity());
buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE);
}
random.setSeed(seed);
ByteBuf expectedValue = directBuffer(BLOCK_SIZE * 2);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(tmp);
expectedValue.setBytes(0, tmp, 0, expectedValue.capacity());
int valueOffset = random.nextInt(BLOCK_SIZE);
buffer.getBytes(i, value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
}
value.release();
expectedValue.release();
}
@Test
public void testRandomByteBufferTransfer() {
ByteBuffer value = ByteBuffer.allocate(BLOCK_SIZE * 2);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(value.array());
value.clear().position(random.nextInt(BLOCK_SIZE));
value.limit(value.position() + BLOCK_SIZE);
buffer.setBytes(i, value);
}
random.setSeed(seed);
ByteBuffer expectedValue = ByteBuffer.allocate(BLOCK_SIZE * 2);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValue.array());
int valueOffset = random.nextInt(BLOCK_SIZE);
value.clear().position(valueOffset).limit(valueOffset + BLOCK_SIZE);
buffer.getBytes(i, value);
assertEquals(valueOffset + BLOCK_SIZE, value.position());
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.get(j), value.get(j));
}
}
}
@Test
public void testSequentialByteArrayTransfer1() {
byte[] value = new byte[BLOCK_SIZE];
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(value);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
buffer.writeBytes(value);
}
random.setSeed(seed);
byte[] expectedValue = new byte[BLOCK_SIZE];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValue);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
buffer.readBytes(value);
for (int j = 0; j < BLOCK_SIZE; j ++) {
assertEquals(expectedValue[j], value[j]);
}
}
}
@Test
public void testSequentialByteArrayTransfer2() {
byte[] value = new byte[BLOCK_SIZE * 2];
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(value);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
int readerIndex = random.nextInt(BLOCK_SIZE);
buffer.writeBytes(value, readerIndex, BLOCK_SIZE);
}
random.setSeed(seed);
byte[] expectedValue = new byte[BLOCK_SIZE * 2];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValue);
int valueOffset = random.nextInt(BLOCK_SIZE);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
buffer.readBytes(value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue[j], value[j]);
}
}
}
@Test
public void testSequentialHeapBufferTransfer1() {
byte[] valueContent = new byte[BLOCK_SIZE * 2];
ByteBuf value = wrappedBuffer(valueContent);
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
buffer.writeBytes(value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE);
assertEquals(0, value.readerIndex());
assertEquals(valueContent.length, value.writerIndex());
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
buffer.readBytes(value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
assertEquals(0, value.readerIndex());
assertEquals(valueContent.length, value.writerIndex());
}
}
@Test
public void testSequentialHeapBufferTransfer2() {
byte[] valueContent = new byte[BLOCK_SIZE * 2];
ByteBuf value = wrappedBuffer(valueContent);
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
int readerIndex = random.nextInt(BLOCK_SIZE);
value.readerIndex(readerIndex);
value.writerIndex(readerIndex + BLOCK_SIZE);
buffer.writeBytes(value);
assertEquals(readerIndex + BLOCK_SIZE, value.writerIndex());
assertEquals(value.writerIndex(), value.readerIndex());
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
value.readerIndex(valueOffset);
value.writerIndex(valueOffset);
buffer.readBytes(value, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
assertEquals(valueOffset, value.readerIndex());
assertEquals(valueOffset + BLOCK_SIZE, value.writerIndex());
}
}
@Test
public void testSequentialDirectBufferTransfer1() {
byte[] valueContent = new byte[BLOCK_SIZE * 2];
ByteBuf value = directBuffer(BLOCK_SIZE * 2);
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
value.setBytes(0, valueContent);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
buffer.writeBytes(value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE);
assertEquals(0, value.readerIndex());
assertEquals(0, value.writerIndex());
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
value.setBytes(0, valueContent);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
buffer.readBytes(value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
assertEquals(0, value.readerIndex());
assertEquals(0, value.writerIndex());
}
value.release();
expectedValue.release();
}
@Test
public void testSequentialDirectBufferTransfer2() {
byte[] valueContent = new byte[BLOCK_SIZE * 2];
ByteBuf value = directBuffer(BLOCK_SIZE * 2);
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
value.setBytes(0, valueContent);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
int readerIndex = random.nextInt(BLOCK_SIZE);
value.readerIndex(0);
value.writerIndex(readerIndex + BLOCK_SIZE);
value.readerIndex(readerIndex);
buffer.writeBytes(value);
assertEquals(readerIndex + BLOCK_SIZE, value.writerIndex());
assertEquals(value.writerIndex(), value.readerIndex());
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
value.setBytes(0, valueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
value.readerIndex(valueOffset);
value.writerIndex(valueOffset);
buffer.readBytes(value, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
assertEquals(valueOffset, value.readerIndex());
assertEquals(valueOffset + BLOCK_SIZE, value.writerIndex());
}
value.release();
expectedValue.release();
}
@Test
public void testSequentialByteBufferBackedHeapBufferTransfer1() {
byte[] valueContent = new byte[BLOCK_SIZE * 2];
ByteBuf value = wrappedBuffer(ByteBuffer.allocate(BLOCK_SIZE * 2));
value.writerIndex(0);
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
value.setBytes(0, valueContent);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
buffer.writeBytes(value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE);
assertEquals(0, value.readerIndex());
assertEquals(0, value.writerIndex());
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
value.setBytes(0, valueContent);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
buffer.readBytes(value, valueOffset, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
assertEquals(0, value.readerIndex());
assertEquals(0, value.writerIndex());
}
}
@Test
public void testSequentialByteBufferBackedHeapBufferTransfer2() {
byte[] valueContent = new byte[BLOCK_SIZE * 2];
ByteBuf value = wrappedBuffer(ByteBuffer.allocate(BLOCK_SIZE * 2));
value.writerIndex(0);
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(valueContent);
value.setBytes(0, valueContent);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
int readerIndex = random.nextInt(BLOCK_SIZE);
value.readerIndex(0);
value.writerIndex(readerIndex + BLOCK_SIZE);
value.readerIndex(readerIndex);
buffer.writeBytes(value);
assertEquals(readerIndex + BLOCK_SIZE, value.writerIndex());
assertEquals(value.writerIndex(), value.readerIndex());
}
random.setSeed(seed);
byte[] expectedValueContent = new byte[BLOCK_SIZE * 2];
ByteBuf expectedValue = wrappedBuffer(expectedValueContent);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValueContent);
value.setBytes(0, valueContent);
int valueOffset = random.nextInt(BLOCK_SIZE);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
value.readerIndex(valueOffset);
value.writerIndex(valueOffset);
buffer.readBytes(value, BLOCK_SIZE);
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.getByte(j), value.getByte(j));
}
assertEquals(valueOffset, value.readerIndex());
assertEquals(valueOffset + BLOCK_SIZE, value.writerIndex());
}
}
@Test
public void testSequentialByteBufferTransfer() {
buffer.writerIndex(0);
ByteBuffer value = ByteBuffer.allocate(BLOCK_SIZE * 2);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(value.array());
value.clear().position(random.nextInt(BLOCK_SIZE));
value.limit(value.position() + BLOCK_SIZE);
buffer.writeBytes(value);
}
random.setSeed(seed);
ByteBuffer expectedValue = ByteBuffer.allocate(BLOCK_SIZE * 2);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValue.array());
int valueOffset = random.nextInt(BLOCK_SIZE);
value.clear().position(valueOffset).limit(valueOffset + BLOCK_SIZE);
buffer.readBytes(value);
assertEquals(valueOffset + BLOCK_SIZE, value.position());
for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) {
assertEquals(expectedValue.get(j), value.get(j));
}
}
}
@Test
public void testSequentialCopiedBufferTransfer1() {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
byte[] value = new byte[BLOCK_SIZE];
random.nextBytes(value);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
buffer.writeBytes(value);
}
random.setSeed(seed);
byte[] expectedValue = new byte[BLOCK_SIZE];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValue);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
ByteBuf actualValue = buffer.readBytes(BLOCK_SIZE);
assertEquals(wrappedBuffer(expectedValue), actualValue);
// Make sure if it is a copied buffer.
actualValue.setByte(0, (byte) (actualValue.getByte(0) + 1));
assertFalse(buffer.getByte(i) == actualValue.getByte(0));
actualValue.release();
}
}
@Test
public void testSequentialSlice1() {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
byte[] value = new byte[BLOCK_SIZE];
random.nextBytes(value);
assertEquals(0, buffer.readerIndex());
assertEquals(i, buffer.writerIndex());
buffer.writeBytes(value);
}
random.setSeed(seed);
byte[] expectedValue = new byte[BLOCK_SIZE];
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
random.nextBytes(expectedValue);
assertEquals(i, buffer.readerIndex());
assertEquals(CAPACITY, buffer.writerIndex());
ByteBuf actualValue = buffer.readSlice(BLOCK_SIZE);
assertEquals(buffer.order(), actualValue.order());
assertEquals(wrappedBuffer(expectedValue), actualValue);
// Make sure if it is a sliced buffer.
actualValue.setByte(0, (byte) (actualValue.getByte(0) + 1));
assertEquals(buffer.getByte(i), actualValue.getByte(0));
}
}
@Test
public void testWriteZero() {
try {
buffer.writeZero(-1);
fail();
} catch (IllegalArgumentException e) {
// Expected
}
buffer.clear();
while (buffer.isWritable()) {
buffer.writeByte((byte) 0xFF);
}
buffer.clear();
for (int i = 0; i < buffer.capacity();) {
int length = Math.min(buffer.capacity() - i, random.nextInt(32));
buffer.writeZero(length);
i += length;
}
assertEquals(0, buffer.readerIndex());
assertEquals(buffer.capacity(), buffer.writerIndex());
for (int i = 0; i < buffer.capacity(); i ++) {
assertEquals(0, buffer.getByte(i));
}
}
@Test
public void testDiscardReadBytes() {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i += 4) {
buffer.writeInt(i);
}
ByteBuf copy = copiedBuffer(buffer);
// Make sure there's no effect if called when readerIndex is 0.
buffer.readerIndex(CAPACITY / 4);
buffer.markReaderIndex();
buffer.writerIndex(CAPACITY / 3);
buffer.markWriterIndex();
buffer.readerIndex(0);
buffer.writerIndex(CAPACITY / 2);
buffer.discardReadBytes();
assertEquals(0, buffer.readerIndex());
assertEquals(CAPACITY / 2, buffer.writerIndex());
assertEquals(copy.slice(0, CAPACITY / 2), buffer.slice(0, CAPACITY / 2));
buffer.resetReaderIndex();
assertEquals(CAPACITY / 4, buffer.readerIndex());
buffer.resetWriterIndex();
assertEquals(CAPACITY / 3, buffer.writerIndex());
// Make sure bytes after writerIndex is not copied.
buffer.readerIndex(1);
buffer.writerIndex(CAPACITY / 2);
buffer.discardReadBytes();
assertEquals(0, buffer.readerIndex());
assertEquals(CAPACITY / 2 - 1, buffer.writerIndex());
assertEquals(copy.slice(1, CAPACITY / 2 - 1), buffer.slice(0, CAPACITY / 2 - 1));
if (discardReadBytesDoesNotMoveWritableBytes()) {
// If writable bytes were copied, the test should fail to avoid unnecessary memory bandwidth consumption.
assertFalse(copy.slice(CAPACITY / 2, CAPACITY / 2).equals(buffer.slice(CAPACITY / 2 - 1, CAPACITY / 2)));
} else {
assertEquals(copy.slice(CAPACITY / 2, CAPACITY / 2), buffer.slice(CAPACITY / 2 - 1, CAPACITY / 2));
}
// Marks also should be relocated.
buffer.resetReaderIndex();
assertEquals(CAPACITY / 4 - 1, buffer.readerIndex());
buffer.resetWriterIndex();
assertEquals(CAPACITY / 3 - 1, buffer.writerIndex());
copy.release();
}
/**
* The similar test case with {@link #testDiscardReadBytes()} but this one
* discards a large chunk at once.
*/
@Test
public void testDiscardReadBytes2() {
buffer.writerIndex(0);
for (int i = 0; i < buffer.capacity(); i ++) {
buffer.writeByte((byte) i);
}
ByteBuf copy = copiedBuffer(buffer);
// Discard the first (CAPACITY / 2 - 1) bytes.
buffer.setIndex(CAPACITY / 2 - 1, CAPACITY - 1);
buffer.discardReadBytes();
assertEquals(0, buffer.readerIndex());
assertEquals(CAPACITY / 2, buffer.writerIndex());
for (int i = 0; i < CAPACITY / 2; i ++) {
assertEquals(copy.slice(CAPACITY / 2 - 1 + i, CAPACITY / 2 - i), buffer.slice(i, CAPACITY / 2 - i));
}
copy.release();
}
@Test
public void testStreamTransfer1() throws Exception {
byte[] expected = new byte[buffer.capacity()];
random.nextBytes(expected);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
ByteArrayInputStream in = new ByteArrayInputStream(expected, i, BLOCK_SIZE);
assertEquals(BLOCK_SIZE, buffer.setBytes(i, in, BLOCK_SIZE));
assertEquals(-1, buffer.setBytes(i, in, 0));
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
buffer.getBytes(i, out, BLOCK_SIZE);
}
assertTrue(Arrays.equals(expected, out.toByteArray()));
}
@Test
public void testStreamTransfer2() throws Exception {
byte[] expected = new byte[buffer.capacity()];
random.nextBytes(expected);
buffer.clear();
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
ByteArrayInputStream in = new ByteArrayInputStream(expected, i, BLOCK_SIZE);
assertEquals(i, buffer.writerIndex());
buffer.writeBytes(in, BLOCK_SIZE);
assertEquals(i + BLOCK_SIZE, buffer.writerIndex());
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
assertEquals(i, buffer.readerIndex());
buffer.readBytes(out, BLOCK_SIZE);
assertEquals(i + BLOCK_SIZE, buffer.readerIndex());
}
assertTrue(Arrays.equals(expected, out.toByteArray()));
}
@Test
public void testCopy() {
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
buffer.setByte(i, value);
}
final int readerIndex = CAPACITY / 3;
final int writerIndex = CAPACITY * 2 / 3;
buffer.setIndex(readerIndex, writerIndex);
// Make sure all properties are copied.
ByteBuf copy = buffer.copy();
assertEquals(0, copy.readerIndex());
assertEquals(buffer.readableBytes(), copy.writerIndex());
assertEquals(buffer.readableBytes(), copy.capacity());
assertSame(buffer.order(), copy.order());
for (int i = 0; i < copy.capacity(); i ++) {
assertEquals(buffer.getByte(i + readerIndex), copy.getByte(i));
}
// Make sure the buffer content is independent from each other.
buffer.setByte(readerIndex, (byte) (buffer.getByte(readerIndex) + 1));
assertTrue(buffer.getByte(readerIndex) != copy.getByte(0));
copy.setByte(1, (byte) (copy.getByte(1) + 1));
assertTrue(buffer.getByte(readerIndex + 1) != copy.getByte(1));
copy.release();
}
@Test
public void testDuplicate() {
for (int i = 0; i < buffer.capacity(); i ++) {
byte value = (byte) random.nextInt();
buffer.setByte(i, value);
}
final int readerIndex = CAPACITY / 3;
final int writerIndex = CAPACITY * 2 / 3;
buffer.setIndex(readerIndex, writerIndex);
// Make sure all properties are copied.
ByteBuf duplicate = buffer.duplicate();
assertSame(buffer.order(), duplicate.order());
assertEquals(buffer.readableBytes(), duplicate.readableBytes());
assertEquals(0, buffer.compareTo(duplicate));
// Make sure the buffer content is shared.
buffer.setByte(readerIndex, (byte) (buffer.getByte(readerIndex) + 1));
assertEquals(buffer.getByte(readerIndex), duplicate.getByte(duplicate.readerIndex()));
duplicate.setByte(duplicate.readerIndex(), (byte) (duplicate.getByte(duplicate.readerIndex()) + 1));
assertEquals(buffer.getByte(readerIndex), duplicate.getByte(duplicate.readerIndex()));
}
@Test
public void testSliceEndianness() throws Exception {
assertEquals(buffer.order(), buffer.slice(0, buffer.capacity()).order());
assertEquals(buffer.order(), buffer.slice(0, buffer.capacity() - 1).order());
assertEquals(buffer.order(), buffer.slice(1, buffer.capacity() - 1).order());
assertEquals(buffer.order(), buffer.slice(1, buffer.capacity() - 2).order());
}
@Test
public void testSliceIndex() throws Exception {
assertEquals(0, buffer.slice(0, buffer.capacity()).readerIndex());
assertEquals(0, buffer.slice(0, buffer.capacity() - 1).readerIndex());
assertEquals(0, buffer.slice(1, buffer.capacity() - 1).readerIndex());
assertEquals(0, buffer.slice(1, buffer.capacity() - 2).readerIndex());
assertEquals(buffer.capacity(), buffer.slice(0, buffer.capacity()).writerIndex());
assertEquals(buffer.capacity() - 1, buffer.slice(0, buffer.capacity() - 1).writerIndex());
assertEquals(buffer.capacity() - 1, buffer.slice(1, buffer.capacity() - 1).writerIndex());
assertEquals(buffer.capacity() - 2, buffer.slice(1, buffer.capacity() - 2).writerIndex());
}
@Test
public void testRetainedSliceIndex() throws Exception {
ByteBuf retainedSlice = buffer.retainedSlice(0, buffer.capacity());
assertEquals(0, retainedSlice.readerIndex());
retainedSlice.release();
retainedSlice = buffer.retainedSlice(0, buffer.capacity() - 1);
assertEquals(0, retainedSlice.readerIndex());
retainedSlice.release();
retainedSlice = buffer.retainedSlice(1, buffer.capacity() - 1);
assertEquals(0, retainedSlice.readerIndex());
retainedSlice.release();
retainedSlice = buffer.retainedSlice(1, buffer.capacity() - 2);
assertEquals(0, retainedSlice.readerIndex());
retainedSlice.release();
retainedSlice = buffer.retainedSlice(0, buffer.capacity());
assertEquals(buffer.capacity(), retainedSlice.writerIndex());
retainedSlice.release();
retainedSlice = buffer.retainedSlice(0, buffer.capacity() - 1);
assertEquals(buffer.capacity() - 1, retainedSlice.writerIndex());
retainedSlice.release();
retainedSlice = buffer.retainedSlice(1, buffer.capacity() - 1);
assertEquals(buffer.capacity() - 1, retainedSlice.writerIndex());
retainedSlice.release();
retainedSlice = buffer.retainedSlice(1, buffer.capacity() - 2);
assertEquals(buffer.capacity() - 2, retainedSlice.writerIndex());
retainedSlice.release();
}
@Test
@SuppressWarnings("ObjectEqualsNull")
public void testEquals() {
assertFalse(buffer.equals(null));
assertFalse(buffer.equals(new Object()));
byte[] value = new byte[32];
buffer.setIndex(0, value.length);
random.nextBytes(value);
buffer.setBytes(0, value);
assertEquals(buffer, wrappedBuffer(value));
assertEquals(buffer, wrappedBuffer(value).order(LITTLE_ENDIAN));
value[0] ++;
assertFalse(buffer.equals(wrappedBuffer(value)));
assertFalse(buffer.equals(wrappedBuffer(value).order(LITTLE_ENDIAN)));
}
@Test
public void testCompareTo() {
try {
buffer.compareTo(null);
fail();
} catch (NullPointerException e) {
// Expected
}
// Fill the random stuff
byte[] value = new byte[32];
random.nextBytes(value);
// Prevent overflow / underflow
if (value[0] == 0) {
value[0] ++;
} else if (value[0] == -1) {
value[0] --;
}
buffer.setIndex(0, value.length);
buffer.setBytes(0, value);
assertEquals(0, buffer.compareTo(wrappedBuffer(value)));
assertEquals(0, buffer.compareTo(wrappedBuffer(value).order(LITTLE_ENDIAN)));
value[0] ++;
assertTrue(buffer.compareTo(wrappedBuffer(value)) < 0);
assertTrue(buffer.compareTo(wrappedBuffer(value).order(LITTLE_ENDIAN)) < 0);
value[0] -= 2;
assertTrue(buffer.compareTo(wrappedBuffer(value)) > 0);
assertTrue(buffer.compareTo(wrappedBuffer(value).order(LITTLE_ENDIAN)) > 0);
value[0] ++;
assertTrue(buffer.compareTo(wrappedBuffer(value, 0, 31)) > 0);
assertTrue(buffer.compareTo(wrappedBuffer(value, 0, 31).order(LITTLE_ENDIAN)) > 0);
assertTrue(buffer.slice(0, 31).compareTo(wrappedBuffer(value)) < 0);
assertTrue(buffer.slice(0, 31).compareTo(wrappedBuffer(value).order(LITTLE_ENDIAN)) < 0);
ByteBuf retainedSlice = buffer.retainedSlice(0, 31);
assertTrue(retainedSlice.compareTo(wrappedBuffer(value)) < 0);
retainedSlice.release();
retainedSlice = buffer.retainedSlice(0, 31);
assertTrue(retainedSlice.compareTo(wrappedBuffer(value).order(LITTLE_ENDIAN)) < 0);
retainedSlice.release();
}
@Test
public void testCompareTo2() {
byte[] bytes = {1, 2, 3, 4};
byte[] bytesReversed = {4, 3, 2, 1};
ByteBuf buf1 = newBuffer(4).clear().writeBytes(bytes).order(ByteOrder.LITTLE_ENDIAN);
ByteBuf buf2 = newBuffer(4).clear().writeBytes(bytesReversed).order(ByteOrder.LITTLE_ENDIAN);
ByteBuf buf3 = newBuffer(4).clear().writeBytes(bytes).order(ByteOrder.BIG_ENDIAN);
ByteBuf buf4 = newBuffer(4).clear().writeBytes(bytesReversed).order(ByteOrder.BIG_ENDIAN);
try {
assertEquals(buf1.compareTo(buf2), buf3.compareTo(buf4));
assertEquals(buf2.compareTo(buf1), buf4.compareTo(buf3));
assertEquals(buf1.compareTo(buf3), buf2.compareTo(buf4));
assertEquals(buf3.compareTo(buf1), buf4.compareTo(buf2));
} finally {
buf1.release();
buf2.release();
buf3.release();
buf4.release();
}
}
@Test
public void testToString() {
ByteBuf copied = copiedBuffer("Hello, World!", CharsetUtil.ISO_8859_1);
buffer.clear();
buffer.writeBytes(copied);
assertEquals("Hello, World!", buffer.toString(CharsetUtil.ISO_8859_1));
copied.release();
}
@Test(timeout = 10000)
public void testToStringMultipleThreads() throws Throwable {
buffer.clear();
buffer.writeBytes("Hello, World!".getBytes(CharsetUtil.ISO_8859_1));
final AtomicInteger counter = new AtomicInteger(30000);
final AtomicReference<Throwable> errorRef = new AtomicReference<Throwable>();
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
while (errorRef.get() == null && counter.decrementAndGet() > 0) {
assertEquals("Hello, World!", buffer.toString(CharsetUtil.ISO_8859_1));
}
} catch (Throwable cause) {
errorRef.compareAndSet(null, cause);
}
}
});
threads.add(thread);
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
Throwable error = errorRef.get();
if (error != null) {
throw error;
}
}
@Test
public void testSWARIndexOf() {
ByteBuf buffer = newBuffer(16);
buffer.clear();
// Ensure the buffer is completely zero'ed.
buffer.setZero(0, buffer.capacity());
buffer.writeByte((byte) 0); // 0
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0); // 7
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 0);
buffer.writeByte((byte) 1); // 11
buffer.writeByte((byte) 2);
buffer.writeByte((byte) 3);
buffer.writeByte((byte) 4);
buffer.writeByte((byte) 1);
assertEquals(11, buffer.indexOf(0, 12, (byte) 1));
assertEquals(12, buffer.indexOf(0, 16, (byte) 2));
assertEquals(-1, buffer.indexOf(0, 11, (byte) 1));
assertEquals(11, buffer.indexOf(0, 16, (byte) 1));
buffer.release();
}
@Test
public void testIndexOf() {
buffer.clear();
// Ensure the buffer is completely zero'ed.
buffer.setZero(0, buffer.capacity());
buffer.writeByte((byte) 1);
buffer.writeByte((byte) 2);
buffer.writeByte((byte) 3);
buffer.writeByte((byte) 2);
buffer.writeByte((byte) 1);
assertEquals(-1, buffer.indexOf(1, 4, (byte) 1));
assertEquals(-1, buffer.indexOf(4, 1, (byte) 1));
assertEquals(1, buffer.indexOf(1, 4, (byte) 2));
assertEquals(3, buffer.indexOf(4, 1, (byte) 2));
try {
buffer.indexOf(0, buffer.capacity() + 1, (byte) 0);
fail();
} catch (IndexOutOfBoundsException expected) {
// expected
}
try {
buffer.indexOf(buffer.capacity(), -1, (byte) 0);
fail();
} catch (IndexOutOfBoundsException expected) {
// expected
}
assertEquals(4, buffer.indexOf(buffer.capacity() + 1, 0, (byte) 1));
assertEquals(0, buffer.indexOf(-1, buffer.capacity(), (byte) 1));
}
@Test
public void testIndexOfReleaseBuffer() {
ByteBuf buffer = releasedBuffer();
if (buffer.capacity() != 0) {
try {
buffer.indexOf(0, 1, (byte) 1);
fail();
} catch (IllegalReferenceCountException expected) {
// expected
}
} else {
assertEquals(-1, buffer.indexOf(0, 1, (byte) 1));
}
}
@Test
public void testNioBuffer1() {
assumeTrue(buffer.nioBufferCount() == 1);
byte[] value = new byte[buffer.capacity()];
random.nextBytes(value);
buffer.clear();
buffer.writeBytes(value);
assertRemainingEquals(ByteBuffer.wrap(value), buffer.nioBuffer());
}
@Test
public void testToByteBuffer2() {
assumeTrue(buffer.nioBufferCount() == 1);
byte[] value = new byte[buffer.capacity()];
random.nextBytes(value);
buffer.clear();
buffer.writeBytes(value);
for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) {
assertRemainingEquals(ByteBuffer.wrap(value, i, BLOCK_SIZE), buffer.nioBuffer(i, BLOCK_SIZE));
}
}
private static void assertRemainingEquals(ByteBuffer expected, ByteBuffer actual) {
int remaining = expected.remaining();
int remaining2 = actual.remaining();
assertEquals(remaining, remaining2);
byte[] array1 = new byte[remaining];
byte[] array2 = new byte[remaining2];
expected.get(array1);
actual.get(array2);
assertArrayEquals(array1, array2);
}
@Test
public void testToByteBuffer3() {
assumeTrue(buffer.nioBufferCount() == 1);
assertEquals(buffer.order(), buffer.nioBuffer().order());
}
@Test
public void testSkipBytes1() {
buffer.setIndex(CAPACITY / 4, CAPACITY / 2);
buffer.skipBytes(CAPACITY / 4);
assertEquals(CAPACITY / 4 * 2, buffer.readerIndex());
try {
buffer.skipBytes(CAPACITY / 4 + 1);
fail();
} catch (IndexOutOfBoundsException e) {
// Expected
}
// Should remain unchanged.
assertEquals(CAPACITY / 4 * 2, buffer.readerIndex());
}
@Test
public void testHashCode() {
ByteBuf elemA = buffer(15);
ByteBuf elemB = directBuffer(15);
elemA.writeBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5 });
elemB.writeBytes(new byte[] { 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9 });
Set<ByteBuf> set = new HashSet<ByteBuf>();
set.add(elemA);
set.add(elemB);
assertEquals(2, set.size());
ByteBuf elemACopy = elemA.copy();
assertTrue(set.contains(elemACopy));
ByteBuf elemBCopy = elemB.copy();
assertTrue(set.contains(elemBCopy));
buffer.clear();
buffer.writeBytes(elemA.duplicate());
assertTrue(set.remove(buffer));
assertFalse(set.contains(elemA));
assertEquals(1, set.size());
buffer.clear();
buffer.writeBytes(elemB.duplicate());
assertTrue(set.remove(buffer));
assertFalse(set.contains(elemB));
assertEquals(0, set.size());
elemA.release();
elemB.release();
elemACopy.release();
elemBCopy.release();
}
// Test case for https://github.com/netty/netty/issues/325
@Test
public void testDiscardAllReadBytes() {
buffer.writerIndex(buffer.capacity());
buffer.readerIndex(buffer.writerIndex());
buffer.discardReadBytes();
}
@Test
public void testForEachByte() {
buffer.clear();
for (int i = 0; i < CAPACITY; i ++) {
buffer.writeByte(i + 1);
}
final AtomicInteger lastIndex = new AtomicInteger();
buffer.setIndex(CAPACITY / 4, CAPACITY * 3 / 4);
assertThat(buffer.forEachByte(new ByteProcessor() {
int i = CAPACITY / 4;
@Override
public boolean process(byte value) throws Exception {
assertThat(value, is((byte) (i + 1)));
lastIndex.set(i);
i ++;
return true;
}
}), is(-1));
assertThat(lastIndex.get(), is(CAPACITY * 3 / 4 - 1));
}
@Test
public void testForEachByteAbort() {
buffer.clear();
for (int i = 0; i < CAPACITY; i ++) {
buffer.writeByte(i + 1);
}
final int stop = CAPACITY / 2;
assertThat(buffer.forEachByte(CAPACITY / 3, CAPACITY / 3, new ByteProcessor() {
int i = CAPACITY / 3;
@Override
public boolean process(byte value) throws Exception {
assertThat(value, is((byte) (i + 1)));
if (i == stop) {
return false;
}
i++;
return true;
}
}), is(stop));
}
@Test
public void testForEachByteDesc() {
buffer.clear();
for (int i = 0; i < CAPACITY; i ++) {
buffer.writeByte(i + 1);
}
final AtomicInteger lastIndex = new AtomicInteger();
assertThat(buffer.forEachByteDesc(CAPACITY / 4, CAPACITY * 2 / 4, new ByteProcessor() {
int i = CAPACITY * 3 / 4 - 1;
@Override
public boolean process(byte value) throws Exception {
assertThat(value, is((byte) (i + 1)));
lastIndex.set(i);
i --;
return true;
}
}), is(-1));
assertThat(lastIndex.get(), is(CAPACITY / 4));
}
@Test
public void testInternalNioBuffer() {
testInternalNioBuffer(128);
testInternalNioBuffer(1024);
testInternalNioBuffer(4 * 1024);
testInternalNioBuffer(64 * 1024);
testInternalNioBuffer(32 * 1024 * 1024);
testInternalNioBuffer(64 * 1024 * 1024);
}
private void testInternalNioBuffer(int a) {
ByteBuf buffer = newBuffer(2);
ByteBuffer buf = buffer.internalNioBuffer(buffer.readerIndex(), 1);
assertEquals(1, buf.remaining());
byte[] data = new byte[a];
PlatformDependent.threadLocalRandom().nextBytes(data);
buffer.writeBytes(data);
buf = buffer.internalNioBuffer(buffer.readerIndex(), a);
assertEquals(a, buf.remaining());
for (int i = 0; i < a; i++) {
assertEquals(data[i], buf.get());
}
assertFalse(buf.hasRemaining());
buffer.release();
}
@Test
public void testDuplicateReadGatheringByteChannelMultipleThreads() throws Exception {
testReadGatheringByteChannelMultipleThreads(false);
}
@Test
public void testSliceReadGatheringByteChannelMultipleThreads() throws Exception {
testReadGatheringByteChannelMultipleThreads(true);
}
private void testReadGatheringByteChannelMultipleThreads(final boolean slice) throws Exception {
final byte[] bytes = new byte[8];
random.nextBytes(bytes);
final ByteBuf buffer = newBuffer(8);
buffer.writeBytes(bytes);
final CountDownLatch latch = new CountDownLatch(60000);
final CyclicBarrier barrier = new CyclicBarrier(11);
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (latch.getCount() > 0) {
ByteBuf buf;
if (slice) {
buf = buffer.slice();
} else {
buf = buffer.duplicate();
}
TestGatheringByteChannel channel = new TestGatheringByteChannel();
while (buf.isReadable()) {
try {
buf.readBytes(channel, buf.readableBytes());
} catch (IOException e) {
// Never happens
return;
}
}
assertArrayEquals(bytes, channel.writtenBytes());
latch.countDown();
}
try {
barrier.await();
} catch (Exception e) {
// ignore
}
}
}).start();
}
latch.await(10, TimeUnit.SECONDS);
barrier.await(5, TimeUnit.SECONDS);
buffer.release();
}
@Test
public void testDuplicateReadOutputStreamMultipleThreads() throws Exception {
testReadOutputStreamMultipleThreads(false);
}
@Test
public void testSliceReadOutputStreamMultipleThreads() throws Exception {
testReadOutputStreamMultipleThreads(true);
}
private void testReadOutputStreamMultipleThreads(final boolean slice) throws Exception {
final byte[] bytes = new byte[8];
random.nextBytes(bytes);
final ByteBuf buffer = newBuffer(8);
buffer.writeBytes(bytes);
final CountDownLatch latch = new CountDownLatch(60000);
final CyclicBarrier barrier = new CyclicBarrier(11);
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (latch.getCount() > 0) {
ByteBuf buf;
if (slice) {
buf = buffer.slice();
} else {
buf = buffer.duplicate();
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
while (buf.isReadable()) {
try {
buf.readBytes(out, buf.readableBytes());
} catch (IOException e) {
// Never happens
return;
}
}
assertArrayEquals(bytes, out.toByteArray());
latch.countDown();
}
try {
barrier.await();
} catch (Exception e) {
// ignore
}
}
}).start();
}
latch.await(10, TimeUnit.SECONDS);
barrier.await(5, TimeUnit.SECONDS);
buffer.release();
}
@Test
public void testDuplicateBytesInArrayMultipleThreads() throws Exception {
testBytesInArrayMultipleThreads(false);
}
@Test
public void testSliceBytesInArrayMultipleThreads() throws Exception {
testBytesInArrayMultipleThreads(true);
}
private void testBytesInArrayMultipleThreads(final boolean slice) throws Exception {
final byte[] bytes = new byte[8];
random.nextBytes(bytes);
final ByteBuf buffer = newBuffer(8);
buffer.writeBytes(bytes);
final AtomicReference<Throwable> cause = new AtomicReference<Throwable>();
final CountDownLatch latch = new CountDownLatch(60000);
final CyclicBarrier barrier = new CyclicBarrier(11);
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (cause.get() == null && latch.getCount() > 0) {
ByteBuf buf;
if (slice) {
buf = buffer.slice();
} else {
buf = buffer.duplicate();
}
byte[] array = new byte[8];
buf.readBytes(array);
assertArrayEquals(bytes, array);
Arrays.fill(array, (byte) 0);
buf.getBytes(0, array);
assertArrayEquals(bytes, array);
latch.countDown();
}
try {
barrier.await();
} catch (Exception e) {
// ignore
}
}
}).start();
}
latch.await(10, TimeUnit.SECONDS);
barrier.await(5, TimeUnit.SECONDS);
assertNull(cause.get());
buffer.release();
}
@Test(expected = IndexOutOfBoundsException.class)
public void readByteThrowsIndexOutOfBoundsException() {
final ByteBuf buffer = newBuffer(8);
try {
buffer.writeByte(0);
assertEquals((byte) 0, buffer.readByte());
buffer.readByte();
} finally {
buffer.release();
}
}
@Test
@SuppressWarnings("ForLoopThatDoesntUseLoopVariable")
public void testNioBufferExposeOnlyRegion() {
final ByteBuf buffer = newBuffer(8);
byte[] data = new byte[8];
random.nextBytes(data);
buffer.writeBytes(data);
ByteBuffer nioBuf = buffer.nioBuffer(1, data.length - 2);
assertEquals(0, nioBuf.position());
assertEquals(6, nioBuf.remaining());
for (int i = 1; nioBuf.hasRemaining(); i++) {
assertEquals(data[i], nioBuf.get());
}
buffer.release();
}
@Test
public void ensureWritableWithForceDoesNotThrow() {
ensureWritableDoesNotThrow(true);
}
@Test
public void ensureWritableWithOutForceDoesNotThrow() {
ensureWritableDoesNotThrow(false);
}
private void ensureWritableDoesNotThrow(boolean force) {
final ByteBuf buffer = newBuffer(8);
buffer.writerIndex(buffer.capacity());
buffer.ensureWritable(8, force);
buffer.release();
}
// See:
// - https://github.com/netty/netty/issues/2587
// - https://github.com/netty/netty/issues/2580
@Test
public void testLittleEndianWithExpand() {
ByteBuf buffer = newBuffer(0).order(LITTLE_ENDIAN);
buffer.writeInt(0x12345678);
assertEquals("78563412", ByteBufUtil.hexDump(buffer));
buffer.release();
}
private ByteBuf releasedBuffer() {
ByteBuf buffer = newBuffer(8);
// Clear the buffer so we are sure the reader and writer indices are 0.
// This is important as we may return a slice from newBuffer(...).
buffer.clear();
assertTrue(buffer.release());
return buffer;
}
@Test(expected = IllegalReferenceCountException.class)
public void testDiscardReadBytesAfterRelease() {
releasedBuffer().discardReadBytes();
}
@Test(expected = IllegalReferenceCountException.class)
public void testDiscardSomeReadBytesAfterRelease() {
releasedBuffer().discardSomeReadBytes();
}
@Test(expected = IllegalReferenceCountException.class)
public void testEnsureWritableAfterRelease() {
releasedBuffer().ensureWritable(16);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBooleanAfterRelease() {
releasedBuffer().getBoolean(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetByteAfterRelease() {
releasedBuffer().getByte(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetUnsignedByteAfterRelease() {
releasedBuffer().getUnsignedByte(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetShortAfterRelease() {
releasedBuffer().getShort(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetShortLEAfterRelease() {
releasedBuffer().getShortLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetUnsignedShortAfterRelease() {
releasedBuffer().getUnsignedShort(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetUnsignedShortLEAfterRelease() {
releasedBuffer().getUnsignedShortLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetMediumAfterRelease() {
releasedBuffer().getMedium(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetMediumLEAfterRelease() {
releasedBuffer().getMediumLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetUnsignedMediumAfterRelease() {
releasedBuffer().getUnsignedMedium(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetIntAfterRelease() {
releasedBuffer().getInt(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetIntLEAfterRelease() {
releasedBuffer().getIntLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetUnsignedIntAfterRelease() {
releasedBuffer().getUnsignedInt(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetUnsignedIntLEAfterRelease() {
releasedBuffer().getUnsignedIntLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetLongAfterRelease() {
releasedBuffer().getLong(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetLongLEAfterRelease() {
releasedBuffer().getLongLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetCharAfterRelease() {
releasedBuffer().getChar(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetFloatAfterRelease() {
releasedBuffer().getFloat(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetFloatLEAfterRelease() {
releasedBuffer().getFloatLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetDoubleAfterRelease() {
releasedBuffer().getDouble(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetDoubleLEAfterRelease() {
releasedBuffer().getDoubleLE(0);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease() {
ByteBuf buffer = buffer(8);
try {
releasedBuffer().getBytes(0, buffer);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease2() {
ByteBuf buffer = buffer();
try {
releasedBuffer().getBytes(0, buffer, 1);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease3() {
ByteBuf buffer = buffer();
try {
releasedBuffer().getBytes(0, buffer, 0, 1);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease4() {
releasedBuffer().getBytes(0, new byte[8]);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease5() {
releasedBuffer().getBytes(0, new byte[8], 0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease6() {
releasedBuffer().getBytes(0, ByteBuffer.allocate(8));
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease7() throws IOException {
releasedBuffer().getBytes(0, new ByteArrayOutputStream(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testGetBytesAfterRelease8() throws IOException {
releasedBuffer().getBytes(0, new DevNullGatheringByteChannel(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBooleanAfterRelease() {
releasedBuffer().setBoolean(0, true);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetByteAfterRelease() {
releasedBuffer().setByte(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetShortAfterRelease() {
releasedBuffer().setShort(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetShortLEAfterRelease() {
releasedBuffer().setShortLE(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetMediumAfterRelease() {
releasedBuffer().setMedium(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetMediumLEAfterRelease() {
releasedBuffer().setMediumLE(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetIntAfterRelease() {
releasedBuffer().setInt(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetIntLEAfterRelease() {
releasedBuffer().setIntLE(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetLongAfterRelease() {
releasedBuffer().setLong(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetLongLEAfterRelease() {
releasedBuffer().setLongLE(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetCharAfterRelease() {
releasedBuffer().setChar(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetFloatAfterRelease() {
releasedBuffer().setFloat(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetDoubleAfterRelease() {
releasedBuffer().setDouble(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease() {
ByteBuf buffer = buffer();
try {
releasedBuffer().setBytes(0, buffer);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease2() {
ByteBuf buffer = buffer();
try {
releasedBuffer().setBytes(0, buffer, 1);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease3() {
ByteBuf buffer = buffer();
try {
releasedBuffer().setBytes(0, buffer, 0, 1);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetUsAsciiCharSequenceAfterRelease() {
testSetCharSequenceAfterRelease0(CharsetUtil.US_ASCII);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetIso88591CharSequenceAfterRelease() {
testSetCharSequenceAfterRelease0(CharsetUtil.ISO_8859_1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetUtf8CharSequenceAfterRelease() {
testSetCharSequenceAfterRelease0(CharsetUtil.UTF_8);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetUtf16CharSequenceAfterRelease() {
testSetCharSequenceAfterRelease0(CharsetUtil.UTF_16);
}
private void testSetCharSequenceAfterRelease0(Charset charset) {
releasedBuffer().setCharSequence(0, "x", charset);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease4() {
releasedBuffer().setBytes(0, new byte[8]);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease5() {
releasedBuffer().setBytes(0, new byte[8], 0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease6() {
releasedBuffer().setBytes(0, ByteBuffer.allocate(8));
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease7() throws IOException {
releasedBuffer().setBytes(0, new ByteArrayInputStream(new byte[8]), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetBytesAfterRelease8() throws IOException {
releasedBuffer().setBytes(0, new TestScatteringByteChannel(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testSetZeroAfterRelease() {
releasedBuffer().setZero(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBooleanAfterRelease() {
releasedBuffer().readBoolean();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadByteAfterRelease() {
releasedBuffer().readByte();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadUnsignedByteAfterRelease() {
releasedBuffer().readUnsignedByte();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadShortAfterRelease() {
releasedBuffer().readShort();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadShortLEAfterRelease() {
releasedBuffer().readShortLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadUnsignedShortAfterRelease() {
releasedBuffer().readUnsignedShort();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadUnsignedShortLEAfterRelease() {
releasedBuffer().readUnsignedShortLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadMediumAfterRelease() {
releasedBuffer().readMedium();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadMediumLEAfterRelease() {
releasedBuffer().readMediumLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadUnsignedMediumAfterRelease() {
releasedBuffer().readUnsignedMedium();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadUnsignedMediumLEAfterRelease() {
releasedBuffer().readUnsignedMediumLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadIntAfterRelease() {
releasedBuffer().readInt();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadIntLEAfterRelease() {
releasedBuffer().readIntLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadUnsignedIntAfterRelease() {
releasedBuffer().readUnsignedInt();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadUnsignedIntLEAfterRelease() {
releasedBuffer().readUnsignedIntLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadLongAfterRelease() {
releasedBuffer().readLong();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadLongLEAfterRelease() {
releasedBuffer().readLongLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadCharAfterRelease() {
releasedBuffer().readChar();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadFloatAfterRelease() {
releasedBuffer().readFloat();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadFloatLEAfterRelease() {
releasedBuffer().readFloatLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadDoubleAfterRelease() {
releasedBuffer().readDouble();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadDoubleLEAfterRelease() {
releasedBuffer().readDoubleLE();
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease() {
releasedBuffer().readBytes(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease2() {
ByteBuf buffer = buffer(8);
try {
releasedBuffer().readBytes(buffer);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease3() {
ByteBuf buffer = buffer(8);
try {
releasedBuffer().readBytes(buffer);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease4() {
ByteBuf buffer = buffer(8);
try {
releasedBuffer().readBytes(buffer, 0, 1);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease5() {
releasedBuffer().readBytes(new byte[8]);
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease6() {
releasedBuffer().readBytes(new byte[8], 0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease7() {
releasedBuffer().readBytes(ByteBuffer.allocate(8));
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease8() throws IOException {
releasedBuffer().readBytes(new ByteArrayOutputStream(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease9() throws IOException {
releasedBuffer().readBytes(new ByteArrayOutputStream(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testReadBytesAfterRelease10() throws IOException {
releasedBuffer().readBytes(new DevNullGatheringByteChannel(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBooleanAfterRelease() {
releasedBuffer().writeBoolean(true);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteByteAfterRelease() {
releasedBuffer().writeByte(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteShortAfterRelease() {
releasedBuffer().writeShort(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteShortLEAfterRelease() {
releasedBuffer().writeShortLE(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteMediumAfterRelease() {
releasedBuffer().writeMedium(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteMediumLEAfterRelease() {
releasedBuffer().writeMediumLE(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteIntAfterRelease() {
releasedBuffer().writeInt(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteIntLEAfterRelease() {
releasedBuffer().writeIntLE(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteLongAfterRelease() {
releasedBuffer().writeLong(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteLongLEAfterRelease() {
releasedBuffer().writeLongLE(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteCharAfterRelease() {
releasedBuffer().writeChar(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteFloatAfterRelease() {
releasedBuffer().writeFloat(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteFloatLEAfterRelease() {
releasedBuffer().writeFloatLE(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteDoubleAfterRelease() {
releasedBuffer().writeDouble(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteDoubleLEAfterRelease() {
releasedBuffer().writeDoubleLE(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease() {
ByteBuf buffer = buffer(8);
try {
releasedBuffer().writeBytes(buffer);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease2() {
ByteBuf buffer = copiedBuffer(new byte[8]);
try {
releasedBuffer().writeBytes(buffer, 1);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease3() {
ByteBuf buffer = buffer(8);
try {
releasedBuffer().writeBytes(buffer, 0, 1);
} finally {
buffer.release();
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease4() {
releasedBuffer().writeBytes(new byte[8]);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease5() {
releasedBuffer().writeBytes(new byte[8], 0 , 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease6() {
releasedBuffer().writeBytes(ByteBuffer.allocate(8));
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease7() throws IOException {
releasedBuffer().writeBytes(new ByteArrayInputStream(new byte[8]), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteBytesAfterRelease8() throws IOException {
releasedBuffer().writeBytes(new TestScatteringByteChannel(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteZeroAfterRelease() throws IOException {
releasedBuffer().writeZero(1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteUsAsciiCharSequenceAfterRelease() {
testWriteCharSequenceAfterRelease0(CharsetUtil.US_ASCII);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteIso88591CharSequenceAfterRelease() {
testWriteCharSequenceAfterRelease0(CharsetUtil.ISO_8859_1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteUtf8CharSequenceAfterRelease() {
testWriteCharSequenceAfterRelease0(CharsetUtil.UTF_8);
}
@Test(expected = IllegalReferenceCountException.class)
public void testWriteUtf16CharSequenceAfterRelease() {
testWriteCharSequenceAfterRelease0(CharsetUtil.UTF_16);
}
private void testWriteCharSequenceAfterRelease0(Charset charset) {
releasedBuffer().writeCharSequence("x", charset);
}
@Test(expected = IllegalReferenceCountException.class)
public void testForEachByteAfterRelease() {
releasedBuffer().forEachByte(new TestByteProcessor());
}
@Test(expected = IllegalReferenceCountException.class)
public void testForEachByteAfterRelease1() {
releasedBuffer().forEachByte(0, 1, new TestByteProcessor());
}
@Test(expected = IllegalReferenceCountException.class)
public void testForEachByteDescAfterRelease() {
releasedBuffer().forEachByteDesc(new TestByteProcessor());
}
@Test(expected = IllegalReferenceCountException.class)
public void testForEachByteDescAfterRelease1() {
releasedBuffer().forEachByteDesc(0, 1, new TestByteProcessor());
}
@Test(expected = IllegalReferenceCountException.class)
public void testCopyAfterRelease() {
releasedBuffer().copy();
}
@Test(expected = IllegalReferenceCountException.class)
public void testCopyAfterRelease1() {
releasedBuffer().copy();
}
@Test(expected = IllegalReferenceCountException.class)
public void testNioBufferAfterRelease() {
releasedBuffer().nioBuffer();
}
@Test(expected = IllegalReferenceCountException.class)
public void testNioBufferAfterRelease1() {
releasedBuffer().nioBuffer(0, 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testInternalNioBufferAfterRelease() {
ByteBuf releasedBuffer = releasedBuffer();
releasedBuffer.internalNioBuffer(releasedBuffer.readerIndex(), 1);
}
@Test(expected = IllegalReferenceCountException.class)
public void testNioBuffersAfterRelease() {
releasedBuffer().nioBuffers();
}
@Test(expected = IllegalReferenceCountException.class)
public void testNioBuffersAfterRelease2() {
releasedBuffer().nioBuffers(0, 1);
}
@Test
public void testArrayAfterRelease() {
ByteBuf buf = releasedBuffer();
if (buf.hasArray()) {
try {
buf.array();
fail();
} catch (IllegalReferenceCountException e) {
// expected
}
}
}
@Test
public void testMemoryAddressAfterRelease() {
ByteBuf buf = releasedBuffer();
if (buf.hasMemoryAddress()) {
try {
buf.memoryAddress();
fail();
} catch (IllegalReferenceCountException e) {
// expected
}
}
}
@Test(expected = IllegalReferenceCountException.class)
public void testSliceAfterRelease() {
releasedBuffer().slice();
}
@Test(expected = IllegalReferenceCountException.class)
public void testSliceAfterRelease2() {
releasedBuffer().slice(0, 1);
}
private static void assertSliceFailAfterRelease(ByteBuf... bufs) {
for (ByteBuf buf : bufs) {
if (buf.refCnt() > 0) {
buf.release();
}
}
for (ByteBuf buf : bufs) {
try {
assertEquals(0, buf.refCnt());
buf.slice();
fail();
} catch (IllegalReferenceCountException ignored) {
// as expected
}
}
}
@Test
public void testSliceAfterReleaseRetainedSlice() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
assertSliceFailAfterRelease(buf, buf2);
}
@Test
public void testSliceAfterReleaseRetainedSliceDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
ByteBuf buf3 = buf2.duplicate();
assertSliceFailAfterRelease(buf, buf2, buf3);
}
@Test
public void testSliceAfterReleaseRetainedSliceRetainedDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
ByteBuf buf3 = buf2.retainedDuplicate();
assertSliceFailAfterRelease(buf, buf2, buf3);
}
@Test
public void testSliceAfterReleaseRetainedDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedDuplicate();
assertSliceFailAfterRelease(buf, buf2);
}
@Test
public void testSliceAfterReleaseRetainedDuplicateSlice() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedDuplicate();
ByteBuf buf3 = buf2.slice(0, 1);
assertSliceFailAfterRelease(buf, buf2, buf3);
}
@Test(expected = IllegalReferenceCountException.class)
public void testRetainedSliceAfterRelease() {
releasedBuffer().retainedSlice();
}
@Test(expected = IllegalReferenceCountException.class)
public void testRetainedSliceAfterRelease2() {
releasedBuffer().retainedSlice(0, 1);
}
private static void assertRetainedSliceFailAfterRelease(ByteBuf... bufs) {
for (ByteBuf buf : bufs) {
if (buf.refCnt() > 0) {
buf.release();
}
}
for (ByteBuf buf : bufs) {
try {
assertEquals(0, buf.refCnt());
buf.retainedSlice();
fail();
} catch (IllegalReferenceCountException ignored) {
// as expected
}
}
}
@Test
public void testRetainedSliceAfterReleaseRetainedSlice() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
assertRetainedSliceFailAfterRelease(buf, buf2);
}
@Test
public void testRetainedSliceAfterReleaseRetainedSliceDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
ByteBuf buf3 = buf2.duplicate();
assertRetainedSliceFailAfterRelease(buf, buf2, buf3);
}
@Test
public void testRetainedSliceAfterReleaseRetainedSliceRetainedDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
ByteBuf buf3 = buf2.retainedDuplicate();
assertRetainedSliceFailAfterRelease(buf, buf2, buf3);
}
@Test
public void testRetainedSliceAfterReleaseRetainedDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedDuplicate();
assertRetainedSliceFailAfterRelease(buf, buf2);
}
@Test
public void testRetainedSliceAfterReleaseRetainedDuplicateSlice() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedDuplicate();
ByteBuf buf3 = buf2.slice(0, 1);
assertRetainedSliceFailAfterRelease(buf, buf2, buf3);
}
@Test(expected = IllegalReferenceCountException.class)
public void testDuplicateAfterRelease() {
releasedBuffer().duplicate();
}
@Test(expected = IllegalReferenceCountException.class)
public void testRetainedDuplicateAfterRelease() {
releasedBuffer().retainedDuplicate();
}
private static void assertDuplicateFailAfterRelease(ByteBuf... bufs) {
for (ByteBuf buf : bufs) {
if (buf.refCnt() > 0) {
buf.release();
}
}
for (ByteBuf buf : bufs) {
try {
assertEquals(0, buf.refCnt());
buf.duplicate();
fail();
} catch (IllegalReferenceCountException ignored) {
// as expected
}
}
}
@Test
public void testDuplicateAfterReleaseRetainedSliceDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
ByteBuf buf3 = buf2.duplicate();
assertDuplicateFailAfterRelease(buf, buf2, buf3);
}
@Test
public void testDuplicateAfterReleaseRetainedDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedDuplicate();
assertDuplicateFailAfterRelease(buf, buf2);
}
@Test
public void testDuplicateAfterReleaseRetainedDuplicateSlice() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedDuplicate();
ByteBuf buf3 = buf2.slice(0, 1);
assertDuplicateFailAfterRelease(buf, buf2, buf3);
}
private static void assertRetainedDuplicateFailAfterRelease(ByteBuf... bufs) {
for (ByteBuf buf : bufs) {
if (buf.refCnt() > 0) {
buf.release();
}
}
for (ByteBuf buf : bufs) {
try {
assertEquals(0, buf.refCnt());
buf.retainedDuplicate();
fail();
} catch (IllegalReferenceCountException ignored) {
// as expected
}
}
}
@Test
public void testRetainedDuplicateAfterReleaseRetainedDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedDuplicate();
assertRetainedDuplicateFailAfterRelease(buf, buf2);
}
@Test
public void testRetainedDuplicateAfterReleaseDuplicate() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.duplicate();
assertRetainedDuplicateFailAfterRelease(buf, buf2);
}
@Test
public void testRetainedDuplicateAfterReleaseRetainedSlice() {
ByteBuf buf = newBuffer(1);
ByteBuf buf2 = buf.retainedSlice(0, 1);
assertRetainedDuplicateFailAfterRelease(buf, buf2);
}
@Test
public void testSliceRelease() {
ByteBuf buf = newBuffer(8);
assertEquals(1, buf.refCnt());
assertTrue(buf.slice().release());
assertEquals(0, buf.refCnt());
}
@Test(expected = IndexOutOfBoundsException.class)
public void testReadSliceOutOfBounds() {
testReadSliceOutOfBounds(false);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testReadRetainedSliceOutOfBounds() {
testReadSliceOutOfBounds(true);
}
private void testReadSliceOutOfBounds(boolean retainedSlice) {
ByteBuf buf = newBuffer(100);
try {
buf.writeZero(50);
if (retainedSlice) {
buf.readRetainedSlice(51);
} else {
buf.readSlice(51);
}
fail();
} finally {
buf.release();
}
}
@Test
public void testWriteUsAsciiCharSequenceExpand() {
testWriteCharSequenceExpand(CharsetUtil.US_ASCII);
}
@Test
public void testWriteUtf8CharSequenceExpand() {
testWriteCharSequenceExpand(CharsetUtil.UTF_8);
}
@Test
public void testWriteIso88591CharSequenceExpand() {
testWriteCharSequenceExpand(CharsetUtil.ISO_8859_1);
}
@Test
public void testWriteUtf16CharSequenceExpand() {
testWriteCharSequenceExpand(CharsetUtil.UTF_16);
}
private void testWriteCharSequenceExpand(Charset charset) {
ByteBuf buf = newBuffer(1);
try {
int writerIndex = buf.capacity() - 1;
buf.writerIndex(writerIndex);
int written = buf.writeCharSequence("AB", charset);
assertEquals(writerIndex, buf.writerIndex() - written);
} finally {
buf.release();
}
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSetUsAsciiCharSequenceNoExpand() {
testSetCharSequenceNoExpand(CharsetUtil.US_ASCII);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSetUtf8CharSequenceNoExpand() {
testSetCharSequenceNoExpand(CharsetUtil.UTF_8);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSetIso88591CharSequenceNoExpand() {
testSetCharSequenceNoExpand(CharsetUtil.ISO_8859_1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSetUtf16CharSequenceNoExpand() {
testSetCharSequenceNoExpand(CharsetUtil.UTF_16);
}
private void testSetCharSequenceNoExpand(Charset charset) {
ByteBuf buf = newBuffer(1);
try {
buf.setCharSequence(0, "AB", charset);
} finally {
buf.release();
}
}
@Test
public void testSetUsAsciiCharSequence() {
testSetGetCharSequence(CharsetUtil.US_ASCII);
}
@Test
public void testSetUtf8CharSequence() {
testSetGetCharSequence(CharsetUtil.UTF_8);
}
@Test
public void testSetIso88591CharSequence() {
testSetGetCharSequence(CharsetUtil.ISO_8859_1);
}
@Test
public void testSetUtf16CharSequence() {
testSetGetCharSequence(CharsetUtil.UTF_16);
}
private static final CharBuffer EXTENDED_ASCII_CHARS, ASCII_CHARS;
static {
char[] chars = new char[256];
for (char c = 0; c < chars.length; c++) {
chars[c] = c;
}
EXTENDED_ASCII_CHARS = CharBuffer.wrap(chars);
ASCII_CHARS = CharBuffer.wrap(chars, 0, 128);
}
private void testSetGetCharSequence(Charset charset) {
ByteBuf buf = newBuffer(1024);
CharBuffer sequence = CharsetUtil.US_ASCII.equals(charset)
? ASCII_CHARS : EXTENDED_ASCII_CHARS;
int bytes = buf.setCharSequence(1, sequence, charset);
assertEquals(sequence, CharBuffer.wrap(buf.getCharSequence(1, bytes, charset)));
buf.release();
}
@Test
public void testWriteReadUsAsciiCharSequence() {
testWriteReadCharSequence(CharsetUtil.US_ASCII);
}
@Test
public void testWriteReadUtf8CharSequence() {
testWriteReadCharSequence(CharsetUtil.UTF_8);
}
@Test
public void testWriteReadIso88591CharSequence() {
testWriteReadCharSequence(CharsetUtil.ISO_8859_1);
}
@Test
public void testWriteReadUtf16CharSequence() {
testWriteReadCharSequence(CharsetUtil.UTF_16);
}
private void testWriteReadCharSequence(Charset charset) {
ByteBuf buf = newBuffer(1024);
CharBuffer sequence = CharsetUtil.US_ASCII.equals(charset)
? ASCII_CHARS : EXTENDED_ASCII_CHARS;
buf.writerIndex(1);
int bytes = buf.writeCharSequence(sequence, charset);
buf.readerIndex(1);
assertEquals(sequence, CharBuffer.wrap(buf.readCharSequence(bytes, charset)));
buf.release();
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRetainedSliceIndexOutOfBounds() {
testSliceOutOfBounds(true, true, true);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRetainedSliceLengthOutOfBounds() {
testSliceOutOfBounds(true, true, false);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testMixedSliceAIndexOutOfBounds() {
testSliceOutOfBounds(true, false, true);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testMixedSliceALengthOutOfBounds() {
testSliceOutOfBounds(true, false, false);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testMixedSliceBIndexOutOfBounds() {
testSliceOutOfBounds(false, true, true);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testMixedSliceBLengthOutOfBounds() {
testSliceOutOfBounds(false, true, false);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSliceIndexOutOfBounds() {
testSliceOutOfBounds(false, false, true);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSliceLengthOutOfBounds() {
testSliceOutOfBounds(false, false, false);
}
@Test
public void testRetainedSliceAndRetainedDuplicateContentIsExpected() {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected1 = newBuffer(6).resetWriterIndex();
ByteBuf expected2 = newBuffer(5).resetWriterIndex();
ByteBuf expected3 = newBuffer(4).resetWriterIndex();
ByteBuf expected4 = newBuffer(3).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected1.writeBytes(new byte[] {2, 3, 4, 5, 6, 7});
expected2.writeBytes(new byte[] {3, 4, 5, 6, 7});
expected3.writeBytes(new byte[] {4, 5, 6, 7});
expected4.writeBytes(new byte[] {5, 6, 7});
ByteBuf slice1 = buf.retainedSlice(buf.readerIndex() + 1, 6);
assertEquals(0, slice1.compareTo(expected1));
assertEquals(0, slice1.compareTo(buf.slice(buf.readerIndex() + 1, 6)));
// Simulate a handler that releases the original buffer, and propagates a slice.
buf.release();
// Advance the reader index on the slice.
slice1.readByte();
ByteBuf dup1 = slice1.retainedDuplicate();
assertEquals(0, dup1.compareTo(expected2));
assertEquals(0, dup1.compareTo(slice1.duplicate()));
// Advance the reader index on dup1.
dup1.readByte();
ByteBuf dup2 = dup1.duplicate();
assertEquals(0, dup2.compareTo(expected3));
// Advance the reader index on dup2.
dup2.readByte();
ByteBuf slice2 = dup2.retainedSlice(dup2.readerIndex(), 3);
assertEquals(0, slice2.compareTo(expected4));
assertEquals(0, slice2.compareTo(dup2.slice(dup2.readerIndex(), 3)));
// Cleanup the expected buffers used for testing.
assertTrue(expected1.release());
assertTrue(expected2.release());
assertTrue(expected3.release());
assertTrue(expected4.release());
slice2.release();
dup2.release();
assertEquals(slice2.refCnt(), dup2.refCnt());
assertEquals(dup2.refCnt(), dup1.refCnt());
// The handler is now done with the original slice
assertTrue(slice1.release());
// Reference counting may be shared, or may be independently tracked, but at this point all buffers should
// be deallocated and have a reference count of 0.
assertEquals(0, buf.refCnt());
assertEquals(0, slice1.refCnt());
assertEquals(0, slice2.refCnt());
assertEquals(0, dup1.refCnt());
assertEquals(0, dup2.refCnt());
}
@Test
public void testRetainedDuplicateAndRetainedSliceContentIsExpected() {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected1 = newBuffer(6).resetWriterIndex();
ByteBuf expected2 = newBuffer(5).resetWriterIndex();
ByteBuf expected3 = newBuffer(4).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected1.writeBytes(new byte[] {2, 3, 4, 5, 6, 7});
expected2.writeBytes(new byte[] {3, 4, 5, 6, 7});
expected3.writeBytes(new byte[] {5, 6, 7});
ByteBuf dup1 = buf.retainedDuplicate();
assertEquals(0, dup1.compareTo(buf));
assertEquals(0, dup1.compareTo(buf.slice()));
// Simulate a handler that releases the original buffer, and propagates a slice.
buf.release();
// Advance the reader index on the dup.
dup1.readByte();
ByteBuf slice1 = dup1.retainedSlice(dup1.readerIndex(), 6);
assertEquals(0, slice1.compareTo(expected1));
assertEquals(0, slice1.compareTo(slice1.duplicate()));
// Advance the reader index on slice1.
slice1.readByte();
ByteBuf dup2 = slice1.duplicate();
assertEquals(0, dup2.compareTo(slice1));
// Advance the reader index on dup2.
dup2.readByte();
ByteBuf slice2 = dup2.retainedSlice(dup2.readerIndex() + 1, 3);
assertEquals(0, slice2.compareTo(expected3));
assertEquals(0, slice2.compareTo(dup2.slice(dup2.readerIndex() + 1, 3)));
// Cleanup the expected buffers used for testing.
assertTrue(expected1.release());
assertTrue(expected2.release());
assertTrue(expected3.release());
slice2.release();
slice1.release();
assertEquals(slice2.refCnt(), dup2.refCnt());
assertEquals(dup2.refCnt(), slice1.refCnt());
// The handler is now done with the original slice
assertTrue(dup1.release());
// Reference counting may be shared, or may be independently tracked, but at this point all buffers should
// be deallocated and have a reference count of 0.
assertEquals(0, buf.refCnt());
assertEquals(0, slice1.refCnt());
assertEquals(0, slice2.refCnt());
assertEquals(0, dup1.refCnt());
assertEquals(0, dup2.refCnt());
}
@Test
public void testRetainedSliceContents() {
testSliceContents(true);
}
@Test
public void testMultipleLevelRetainedSlice1() {
testMultipleLevelRetainedSliceWithNonRetained(true, true);
}
@Test
public void testMultipleLevelRetainedSlice2() {
testMultipleLevelRetainedSliceWithNonRetained(true, false);
}
@Test
public void testMultipleLevelRetainedSlice3() {
testMultipleLevelRetainedSliceWithNonRetained(false, true);
}
@Test
public void testMultipleLevelRetainedSlice4() {
testMultipleLevelRetainedSliceWithNonRetained(false, false);
}
@Test
public void testRetainedSliceReleaseOriginal1() {
testSliceReleaseOriginal(true, true);
}
@Test
public void testRetainedSliceReleaseOriginal2() {
testSliceReleaseOriginal(true, false);
}
@Test
public void testRetainedSliceReleaseOriginal3() {
testSliceReleaseOriginal(false, true);
}
@Test
public void testRetainedSliceReleaseOriginal4() {
testSliceReleaseOriginal(false, false);
}
@Test
public void testRetainedDuplicateReleaseOriginal1() {
testDuplicateReleaseOriginal(true, true);
}
@Test
public void testRetainedDuplicateReleaseOriginal2() {
testDuplicateReleaseOriginal(true, false);
}
@Test
public void testRetainedDuplicateReleaseOriginal3() {
testDuplicateReleaseOriginal(false, true);
}
@Test
public void testRetainedDuplicateReleaseOriginal4() {
testDuplicateReleaseOriginal(false, false);
}
@Test
public void testMultipleRetainedSliceReleaseOriginal1() {
testMultipleRetainedSliceReleaseOriginal(true, true);
}
@Test
public void testMultipleRetainedSliceReleaseOriginal2() {
testMultipleRetainedSliceReleaseOriginal(true, false);
}
@Test
public void testMultipleRetainedSliceReleaseOriginal3() {
testMultipleRetainedSliceReleaseOriginal(false, true);
}
@Test
public void testMultipleRetainedSliceReleaseOriginal4() {
testMultipleRetainedSliceReleaseOriginal(false, false);
}
@Test
public void testMultipleRetainedDuplicateReleaseOriginal1() {
testMultipleRetainedDuplicateReleaseOriginal(true, true);
}
@Test
public void testMultipleRetainedDuplicateReleaseOriginal2() {
testMultipleRetainedDuplicateReleaseOriginal(true, false);
}
@Test
public void testMultipleRetainedDuplicateReleaseOriginal3() {
testMultipleRetainedDuplicateReleaseOriginal(false, true);
}
@Test
public void testMultipleRetainedDuplicateReleaseOriginal4() {
testMultipleRetainedDuplicateReleaseOriginal(false, false);
}
@Test
public void testSliceContents() {
testSliceContents(false);
}
@Test
public void testRetainedDuplicateContents() {
testDuplicateContents(true);
}
@Test
public void testDuplicateContents() {
testDuplicateContents(false);
}
@Test
public void testDuplicateCapacityChange() {
testDuplicateCapacityChange(false);
}
@Test
public void testRetainedDuplicateCapacityChange() {
testDuplicateCapacityChange(true);
}
@Test(expected = UnsupportedOperationException.class)
public void testSliceCapacityChange() {
testSliceCapacityChange(false);
}
@Test(expected = UnsupportedOperationException.class)
public void testRetainedSliceCapacityChange() {
testSliceCapacityChange(true);
}
@Test
public void testRetainedSliceUnreleasable1() {
testRetainedSliceUnreleasable(true, true);
}
@Test
public void testRetainedSliceUnreleasable2() {
testRetainedSliceUnreleasable(true, false);
}
@Test
public void testRetainedSliceUnreleasable3() {
testRetainedSliceUnreleasable(false, true);
}
@Test
public void testRetainedSliceUnreleasable4() {
testRetainedSliceUnreleasable(false, false);
}
@Test
public void testReadRetainedSliceUnreleasable1() {
testReadRetainedSliceUnreleasable(true, true);
}
@Test
public void testReadRetainedSliceUnreleasable2() {
testReadRetainedSliceUnreleasable(true, false);
}
@Test
public void testReadRetainedSliceUnreleasable3() {
testReadRetainedSliceUnreleasable(false, true);
}
@Test
public void testReadRetainedSliceUnreleasable4() {
testReadRetainedSliceUnreleasable(false, false);
}
@Test
public void testRetainedDuplicateUnreleasable1() {
testRetainedDuplicateUnreleasable(true, true);
}
@Test
public void testRetainedDuplicateUnreleasable2() {
testRetainedDuplicateUnreleasable(true, false);
}
@Test
public void testRetainedDuplicateUnreleasable3() {
testRetainedDuplicateUnreleasable(false, true);
}
@Test
public void testRetainedDuplicateUnreleasable4() {
testRetainedDuplicateUnreleasable(false, false);
}
private void testRetainedSliceUnreleasable(boolean initRetainedSlice, boolean finalRetainedSlice) {
ByteBuf buf = newBuffer(8);
ByteBuf buf1 = initRetainedSlice ? buf.retainedSlice() : buf.slice().retain();
ByteBuf buf2 = unreleasableBuffer(buf1);
ByteBuf buf3 = finalRetainedSlice ? buf2.retainedSlice() : buf2.slice().retain();
assertFalse(buf3.release());
assertFalse(buf2.release());
buf1.release();
assertTrue(buf.release());
assertEquals(0, buf1.refCnt());
assertEquals(0, buf.refCnt());
}
private void testReadRetainedSliceUnreleasable(boolean initRetainedSlice, boolean finalRetainedSlice) {
ByteBuf buf = newBuffer(8);
ByteBuf buf1 = initRetainedSlice ? buf.retainedSlice() : buf.slice().retain();
ByteBuf buf2 = unreleasableBuffer(buf1);
ByteBuf buf3 = finalRetainedSlice ? buf2.readRetainedSlice(buf2.readableBytes())
: buf2.readSlice(buf2.readableBytes()).retain();
assertFalse(buf3.release());
assertFalse(buf2.release());
buf1.release();
assertTrue(buf.release());
assertEquals(0, buf1.refCnt());
assertEquals(0, buf.refCnt());
}
private void testRetainedDuplicateUnreleasable(boolean initRetainedDuplicate, boolean finalRetainedDuplicate) {
ByteBuf buf = newBuffer(8);
ByteBuf buf1 = initRetainedDuplicate ? buf.retainedDuplicate() : buf.duplicate().retain();
ByteBuf buf2 = unreleasableBuffer(buf1);
ByteBuf buf3 = finalRetainedDuplicate ? buf2.retainedDuplicate() : buf2.duplicate().retain();
assertFalse(buf3.release());
assertFalse(buf2.release());
buf1.release();
assertTrue(buf.release());
assertEquals(0, buf1.refCnt());
assertEquals(0, buf.refCnt());
}
private void testDuplicateCapacityChange(boolean retainedDuplicate) {
ByteBuf buf = newBuffer(8);
ByteBuf dup = retainedDuplicate ? buf.retainedDuplicate() : buf.duplicate();
try {
dup.capacity(10);
assertEquals(buf.capacity(), dup.capacity());
dup.capacity(5);
assertEquals(buf.capacity(), dup.capacity());
} finally {
if (retainedDuplicate) {
dup.release();
}
buf.release();
}
}
private void testSliceCapacityChange(boolean retainedSlice) {
ByteBuf buf = newBuffer(8);
ByteBuf slice = retainedSlice ? buf.retainedSlice(buf.readerIndex() + 1, 3)
: buf.slice(buf.readerIndex() + 1, 3);
try {
slice.capacity(10);
} finally {
if (retainedSlice) {
slice.release();
}
buf.release();
}
}
private void testSliceOutOfBounds(boolean initRetainedSlice, boolean finalRetainedSlice, boolean indexOutOfBounds) {
ByteBuf buf = newBuffer(8);
ByteBuf slice = initRetainedSlice ? buf.retainedSlice(buf.readerIndex() + 1, 2)
: buf.slice(buf.readerIndex() + 1, 2);
try {
assertEquals(2, slice.capacity());
assertEquals(2, slice.maxCapacity());
final int index = indexOutOfBounds ? 3 : 0;
final int length = indexOutOfBounds ? 0 : 3;
if (finalRetainedSlice) {
// This is expected to fail ... so no need to release.
slice.retainedSlice(index, length);
} else {
slice.slice(index, length);
}
} finally {
if (initRetainedSlice) {
slice.release();
}
buf.release();
}
}
private void testSliceContents(boolean retainedSlice) {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected = newBuffer(3).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected.writeBytes(new byte[] {4, 5, 6});
ByteBuf slice = retainedSlice ? buf.retainedSlice(buf.readerIndex() + 3, 3)
: buf.slice(buf.readerIndex() + 3, 3);
try {
assertEquals(0, slice.compareTo(expected));
assertEquals(0, slice.compareTo(slice.duplicate()));
ByteBuf b = slice.retainedDuplicate();
assertEquals(0, slice.compareTo(b));
b.release();
assertEquals(0, slice.compareTo(slice.slice(0, slice.capacity())));
} finally {
if (retainedSlice) {
slice.release();
}
buf.release();
expected.release();
}
}
private void testSliceReleaseOriginal(boolean retainedSlice1, boolean retainedSlice2) {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected1 = newBuffer(3).resetWriterIndex();
ByteBuf expected2 = newBuffer(2).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected1.writeBytes(new byte[] {6, 7, 8});
expected2.writeBytes(new byte[] {7, 8});
ByteBuf slice1 = retainedSlice1 ? buf.retainedSlice(buf.readerIndex() + 5, 3)
: buf.slice(buf.readerIndex() + 5, 3).retain();
assertEquals(0, slice1.compareTo(expected1));
// Simulate a handler that releases the original buffer, and propagates a slice.
buf.release();
ByteBuf slice2 = retainedSlice2 ? slice1.retainedSlice(slice1.readerIndex() + 1, 2)
: slice1.slice(slice1.readerIndex() + 1, 2).retain();
assertEquals(0, slice2.compareTo(expected2));
// Cleanup the expected buffers used for testing.
assertTrue(expected1.release());
assertTrue(expected2.release());
// The handler created a slice of the slice and is now done with it.
slice2.release();
// The handler is now done with the original slice
assertTrue(slice1.release());
// Reference counting may be shared, or may be independently tracked, but at this point all buffers should
// be deallocated and have a reference count of 0.
assertEquals(0, buf.refCnt());
assertEquals(0, slice1.refCnt());
assertEquals(0, slice2.refCnt());
}
private void testMultipleLevelRetainedSliceWithNonRetained(boolean doSlice1, boolean doSlice2) {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected1 = newBuffer(6).resetWriterIndex();
ByteBuf expected2 = newBuffer(4).resetWriterIndex();
ByteBuf expected3 = newBuffer(2).resetWriterIndex();
ByteBuf expected4SliceSlice = newBuffer(1).resetWriterIndex();
ByteBuf expected4DupSlice = newBuffer(1).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected1.writeBytes(new byte[] {2, 3, 4, 5, 6, 7});
expected2.writeBytes(new byte[] {3, 4, 5, 6});
expected3.writeBytes(new byte[] {4, 5});
expected4SliceSlice.writeBytes(new byte[] {5});
expected4DupSlice.writeBytes(new byte[] {4});
ByteBuf slice1 = buf.retainedSlice(buf.readerIndex() + 1, 6);
assertEquals(0, slice1.compareTo(expected1));
// Simulate a handler that releases the original buffer, and propagates a slice.
buf.release();
ByteBuf slice2 = slice1.retainedSlice(slice1.readerIndex() + 1, 4);
assertEquals(0, slice2.compareTo(expected2));
assertEquals(0, slice2.compareTo(slice2.duplicate()));
assertEquals(0, slice2.compareTo(slice2.slice()));
ByteBuf tmpBuf = slice2.retainedDuplicate();
assertEquals(0, slice2.compareTo(tmpBuf));
tmpBuf.release();
tmpBuf = slice2.retainedSlice();
assertEquals(0, slice2.compareTo(tmpBuf));
tmpBuf.release();
ByteBuf slice3 = doSlice1 ? slice2.slice(slice2.readerIndex() + 1, 2) : slice2.duplicate();
if (doSlice1) {
assertEquals(0, slice3.compareTo(expected3));
} else {
assertEquals(0, slice3.compareTo(expected2));
}
ByteBuf slice4 = doSlice2 ? slice3.slice(slice3.readerIndex() + 1, 1) : slice3.duplicate();
if (doSlice1 && doSlice2) {
assertEquals(0, slice4.compareTo(expected4SliceSlice));
} else if (doSlice2) {
assertEquals(0, slice4.compareTo(expected4DupSlice));
} else {
assertEquals(0, slice3.compareTo(slice4));
}
// Cleanup the expected buffers used for testing.
assertTrue(expected1.release());
assertTrue(expected2.release());
assertTrue(expected3.release());
assertTrue(expected4SliceSlice.release());
assertTrue(expected4DupSlice.release());
// Slice 4, 3, and 2 should effectively "share" a reference count.
slice4.release();
assertEquals(slice3.refCnt(), slice2.refCnt());
assertEquals(slice3.refCnt(), slice4.refCnt());
// Slice 1 should also release the original underlying buffer without throwing exceptions
assertTrue(slice1.release());
// Reference counting may be shared, or may be independently tracked, but at this point all buffers should
// be deallocated and have a reference count of 0.
assertEquals(0, buf.refCnt());
assertEquals(0, slice1.refCnt());
assertEquals(0, slice2.refCnt());
assertEquals(0, slice3.refCnt());
}
private void testDuplicateReleaseOriginal(boolean retainedDuplicate1, boolean retainedDuplicate2) {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected = newBuffer(8).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected.writeBytes(buf, buf.readerIndex(), buf.readableBytes());
ByteBuf dup1 = retainedDuplicate1 ? buf.retainedDuplicate()
: buf.duplicate().retain();
assertEquals(0, dup1.compareTo(expected));
// Simulate a handler that releases the original buffer, and propagates a slice.
buf.release();
ByteBuf dup2 = retainedDuplicate2 ? dup1.retainedDuplicate()
: dup1.duplicate().retain();
assertEquals(0, dup2.compareTo(expected));
// Cleanup the expected buffers used for testing.
assertTrue(expected.release());
// The handler created a slice of the slice and is now done with it.
dup2.release();
// The handler is now done with the original slice
assertTrue(dup1.release());
// Reference counting may be shared, or may be independently tracked, but at this point all buffers should
// be deallocated and have a reference count of 0.
assertEquals(0, buf.refCnt());
assertEquals(0, dup1.refCnt());
assertEquals(0, dup2.refCnt());
}
private void testMultipleRetainedSliceReleaseOriginal(boolean retainedSlice1, boolean retainedSlice2) {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected1 = newBuffer(3).resetWriterIndex();
ByteBuf expected2 = newBuffer(2).resetWriterIndex();
ByteBuf expected3 = newBuffer(2).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected1.writeBytes(new byte[] {6, 7, 8});
expected2.writeBytes(new byte[] {7, 8});
expected3.writeBytes(new byte[] {6, 7});
ByteBuf slice1 = retainedSlice1 ? buf.retainedSlice(buf.readerIndex() + 5, 3)
: buf.slice(buf.readerIndex() + 5, 3).retain();
assertEquals(0, slice1.compareTo(expected1));
// Simulate a handler that releases the original buffer, and propagates a slice.
buf.release();
ByteBuf slice2 = retainedSlice2 ? slice1.retainedSlice(slice1.readerIndex() + 1, 2)
: slice1.slice(slice1.readerIndex() + 1, 2).retain();
assertEquals(0, slice2.compareTo(expected2));
// The handler created a slice of the slice and is now done with it.
slice2.release();
ByteBuf slice3 = slice1.retainedSlice(slice1.readerIndex(), 2);
assertEquals(0, slice3.compareTo(expected3));
// The handler created another slice of the slice and is now done with it.
slice3.release();
// The handler is now done with the original slice
assertTrue(slice1.release());
// Cleanup the expected buffers used for testing.
assertTrue(expected1.release());
assertTrue(expected2.release());
assertTrue(expected3.release());
// Reference counting may be shared, or may be independently tracked, but at this point all buffers should
// be deallocated and have a reference count of 0.
assertEquals(0, buf.refCnt());
assertEquals(0, slice1.refCnt());
assertEquals(0, slice2.refCnt());
assertEquals(0, slice3.refCnt());
}
private void testMultipleRetainedDuplicateReleaseOriginal(boolean retainedDuplicate1, boolean retainedDuplicate2) {
ByteBuf buf = newBuffer(8).resetWriterIndex();
ByteBuf expected = newBuffer(8).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
expected.writeBytes(buf, buf.readerIndex(), buf.readableBytes());
ByteBuf dup1 = retainedDuplicate1 ? buf.retainedDuplicate()
: buf.duplicate().retain();
assertEquals(0, dup1.compareTo(expected));
// Simulate a handler that releases the original buffer, and propagates a slice.
buf.release();
ByteBuf dup2 = retainedDuplicate2 ? dup1.retainedDuplicate()
: dup1.duplicate().retain();
assertEquals(0, dup2.compareTo(expected));
assertEquals(0, dup2.compareTo(dup2.duplicate()));
assertEquals(0, dup2.compareTo(dup2.slice()));
ByteBuf tmpBuf = dup2.retainedDuplicate();
assertEquals(0, dup2.compareTo(tmpBuf));
tmpBuf.release();
tmpBuf = dup2.retainedSlice();
assertEquals(0, dup2.compareTo(tmpBuf));
tmpBuf.release();
// The handler created a slice of the slice and is now done with it.
dup2.release();
ByteBuf dup3 = dup1.retainedDuplicate();
assertEquals(0, dup3.compareTo(expected));
// The handler created another slice of the slice and is now done with it.
dup3.release();
// The handler is now done with the original slice
assertTrue(dup1.release());
// Cleanup the expected buffers used for testing.
assertTrue(expected.release());
// Reference counting may be shared, or may be independently tracked, but at this point all buffers should
// be deallocated and have a reference count of 0.
assertEquals(0, buf.refCnt());
assertEquals(0, dup1.refCnt());
assertEquals(0, dup2.refCnt());
assertEquals(0, dup3.refCnt());
}
private void testDuplicateContents(boolean retainedDuplicate) {
ByteBuf buf = newBuffer(8).resetWriterIndex();
buf.writeBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
ByteBuf dup = retainedDuplicate ? buf.retainedDuplicate() : buf.duplicate();
try {
assertEquals(0, dup.compareTo(buf));
assertEquals(0, dup.compareTo(dup.duplicate()));
ByteBuf b = dup.retainedDuplicate();
assertEquals(0, dup.compareTo(b));
b.release();
assertEquals(0, dup.compareTo(dup.slice(dup.readerIndex(), dup.readableBytes())));
} finally {
if (retainedDuplicate) {
dup.release();
}
buf.release();
}
}
@Test
public void testDuplicateRelease() {
ByteBuf buf = newBuffer(8);
assertEquals(1, buf.refCnt());
assertTrue(buf.duplicate().release());
assertEquals(0, buf.refCnt());
}
// Test-case trying to reproduce:
// https://github.com/netty/netty/issues/2843
@Test
public void testRefCnt() throws Exception {
testRefCnt0(false);
}
// Test-case trying to reproduce:
// https://github.com/netty/netty/issues/2843
@Test
public void testRefCnt2() throws Exception {
testRefCnt0(true);
}
@Test
public void testEmptyNioBuffers() throws Exception {
ByteBuf buffer = newBuffer(8);
buffer.clear();
assertFalse(buffer.isReadable());
ByteBuffer[] nioBuffers = buffer.nioBuffers();
assertEquals(1, nioBuffers.length);
assertFalse(nioBuffers[0].hasRemaining());
buffer.release();
}
@Test
public void testGetReadOnlyDirectDst() {
testGetReadOnlyDst(true);
}
@Test
public void testGetReadOnlyHeapDst() {
testGetReadOnlyDst(false);
}
private void testGetReadOnlyDst(boolean direct) {
byte[] bytes = { 'a', 'b', 'c', 'd' };
ByteBuf buffer = newBuffer(bytes.length);
buffer.writeBytes(bytes);
ByteBuffer dst = direct ? ByteBuffer.allocateDirect(bytes.length) : ByteBuffer.allocate(bytes.length);
ByteBuffer readOnlyDst = dst.asReadOnlyBuffer();
try {
buffer.getBytes(0, readOnlyDst);
fail();
} catch (ReadOnlyBufferException e) {
// expected
}
assertEquals(0, readOnlyDst.position());
buffer.release();
}
@Test
public void testReadBytesAndWriteBytesWithFileChannel() throws IOException {
File file = File.createTempFile("file-channel", ".tmp");
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel channel = randomAccessFile.getChannel();
// channelPosition should never be changed
long channelPosition = channel.position();
byte[] bytes = {'a', 'b', 'c', 'd'};
int len = bytes.length;
ByteBuf buffer = newBuffer(len);
buffer.resetReaderIndex();
buffer.resetWriterIndex();
buffer.writeBytes(bytes);
int oldReaderIndex = buffer.readerIndex();
assertEquals(len, buffer.readBytes(channel, 10, len));
assertEquals(oldReaderIndex + len, buffer.readerIndex());
assertEquals(channelPosition, channel.position());
ByteBuf buffer2 = newBuffer(len);
buffer2.resetReaderIndex();
buffer2.resetWriterIndex();
int oldWriterIndex = buffer2.writerIndex();
assertEquals(len, buffer2.writeBytes(channel, 10, len));
assertEquals(channelPosition, channel.position());
assertEquals(oldWriterIndex + len, buffer2.writerIndex());
assertEquals('a', buffer2.getByte(0));
assertEquals('b', buffer2.getByte(1));
assertEquals('c', buffer2.getByte(2));
assertEquals('d', buffer2.getByte(3));
buffer.release();
buffer2.release();
} finally {
if (randomAccessFile != null) {
randomAccessFile.close();
}
file.delete();
}
}
@Test
public void testGetBytesAndSetBytesWithFileChannel() throws IOException {
File file = File.createTempFile("file-channel", ".tmp");
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel channel = randomAccessFile.getChannel();
// channelPosition should never be changed
long channelPosition = channel.position();
byte[] bytes = {'a', 'b', 'c', 'd'};
int len = bytes.length;
ByteBuf buffer = newBuffer(len);
buffer.resetReaderIndex();
buffer.resetWriterIndex();
buffer.writeBytes(bytes);
int oldReaderIndex = buffer.readerIndex();
assertEquals(len, buffer.getBytes(oldReaderIndex, channel, 10, len));
assertEquals(oldReaderIndex, buffer.readerIndex());
assertEquals(channelPosition, channel.position());
ByteBuf buffer2 = newBuffer(len);
buffer2.resetReaderIndex();
buffer2.resetWriterIndex();
int oldWriterIndex = buffer2.writerIndex();
assertEquals(buffer2.setBytes(oldWriterIndex, channel, 10, len), len);
assertEquals(channelPosition, channel.position());
assertEquals(oldWriterIndex, buffer2.writerIndex());
assertEquals('a', buffer2.getByte(oldWriterIndex));
assertEquals('b', buffer2.getByte(oldWriterIndex + 1));
assertEquals('c', buffer2.getByte(oldWriterIndex + 2));
assertEquals('d', buffer2.getByte(oldWriterIndex + 3));
buffer.release();
buffer2.release();
} finally {
if (randomAccessFile != null) {
randomAccessFile.close();
}
file.delete();
}
}
@Test
public void testReadBytes() {
ByteBuf buffer = newBuffer(8);
byte[] bytes = new byte[8];
buffer.writeBytes(bytes);
ByteBuf buffer2 = buffer.readBytes(4);
assertSame(buffer.alloc(), buffer2.alloc());
assertEquals(4, buffer.readerIndex());
assertTrue(buffer.release());
assertEquals(0, buffer.refCnt());
assertTrue(buffer2.release());
assertEquals(0, buffer2.refCnt());
}
@Test
public void testForEachByteDesc2() {
byte[] expected = {1, 2, 3, 4};
ByteBuf buf = newBuffer(expected.length);
try {
buf.writeBytes(expected);
final byte[] bytes = new byte[expected.length];
int i = buf.forEachByteDesc(new ByteProcessor() {
private int index = bytes.length - 1;
@Override
public boolean process(byte value) throws Exception {
bytes[index--] = value;
return true;
}
});
assertEquals(-1, i);
assertArrayEquals(expected, bytes);
} finally {
buf.release();
}
}
@Test
public void testForEachByte2() {
byte[] expected = {1, 2, 3, 4};
ByteBuf buf = newBuffer(expected.length);
try {
buf.writeBytes(expected);
final byte[] bytes = new byte[expected.length];
int i = buf.forEachByte(new ByteProcessor() {
private int index;
@Override
public boolean process(byte value) throws Exception {
bytes[index++] = value;
return true;
}
});
assertEquals(-1, i);
assertArrayEquals(expected, bytes);
} finally {
buf.release();
}
}
@Test(expected = IndexOutOfBoundsException.class)
public void testGetBytesByteBuffer() {
byte[] bytes = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
// Ensure destination buffer is bigger then what is in the ByteBuf.
ByteBuffer nioBuffer = ByteBuffer.allocate(bytes.length + 1);
ByteBuf buffer = newBuffer(bytes.length);
try {
buffer.writeBytes(bytes);
buffer.getBytes(buffer.readerIndex(), nioBuffer);
} finally {
buffer.release();
}
}
private void testRefCnt0(final boolean parameter) throws Exception {
for (int i = 0; i < 10; i++) {
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch innerLatch = new CountDownLatch(1);
final ByteBuf buffer = newBuffer(4);
assertEquals(1, buffer.refCnt());
final AtomicInteger cnt = new AtomicInteger(Integer.MAX_VALUE);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
boolean released;
if (parameter) {
released = buffer.release(buffer.refCnt());
} else {
released = buffer.release();
}
assertTrue(released);
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
cnt.set(buffer.refCnt());
latch.countDown();
}
});
t2.start();
try {
// Keep Thread alive a bit so the ThreadLocal caches are not freed
innerLatch.await();
} catch (InterruptedException ignore) {
// ignore
}
}
});
t1.start();
latch.await();
assertEquals(0, cnt.get());
innerLatch.countDown();
}
}
static final class TestGatheringByteChannel implements GatheringByteChannel {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
private final WritableByteChannel channel = Channels.newChannel(out);
private final int limit;
TestGatheringByteChannel(int limit) {
this.limit = limit;
}
TestGatheringByteChannel() {
this(Integer.MAX_VALUE);
}
@Override
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {
long written = 0;
for (; offset < length; offset++) {
written += write(srcs[offset]);
if (written >= limit) {
break;
}
}
return written;
}
@Override
public long write(ByteBuffer[] srcs) throws IOException {
return write(srcs, 0, srcs.length);
}
@Override
public int write(ByteBuffer src) throws IOException {
int oldLimit = src.limit();
if (limit < src.remaining()) {
src.limit(src.position() + limit);
}
int w = channel.write(src);
src.limit(oldLimit);
return w;
}
@Override
public boolean isOpen() {
return channel.isOpen();
}
@Override
public void close() throws IOException {
channel.close();
}
public byte[] writtenBytes() {
return out.toByteArray();
}
}
private static final class DevNullGatheringByteChannel implements GatheringByteChannel {
@Override
public long write(ByteBuffer[] srcs, int offset, int length) {
throw new UnsupportedOperationException();
}
@Override
public long write(ByteBuffer[] srcs) {
throw new UnsupportedOperationException();
}
@Override
public int write(ByteBuffer src) {
throw new UnsupportedOperationException();
}
@Override
public boolean isOpen() {
return false;
}
@Override
public void close() {
throw new UnsupportedOperationException();
}
}
private static final class TestScatteringByteChannel implements ScatteringByteChannel {
@Override
public long read(ByteBuffer[] dsts, int offset, int length) {
throw new UnsupportedOperationException();
}
@Override
public long read(ByteBuffer[] dsts) {
throw new UnsupportedOperationException();
}
@Override
public int read(ByteBuffer dst) {
throw new UnsupportedOperationException();
}
@Override
public boolean isOpen() {
return false;
}
@Override
public void close() {
throw new UnsupportedOperationException();
}
}
private static final class TestByteProcessor implements ByteProcessor {
@Override
public boolean process(byte value) throws Exception {
return true;
}
}
@Test(expected = IllegalArgumentException.class)
public void testCapacityEnforceMaxCapacity() {
ByteBuf buffer = newBuffer(3, 13);
assertEquals(13, buffer.maxCapacity());
assertEquals(3, buffer.capacity());
try {
buffer.capacity(14);
} finally {
buffer.release();
}
}
@Test(expected = IllegalArgumentException.class)
public void testCapacityNegative() {
ByteBuf buffer = newBuffer(3, 13);
assertEquals(13, buffer.maxCapacity());
assertEquals(3, buffer.capacity());
try {
buffer.capacity(-1);
} finally {
buffer.release();
}
}
@Test
public void testCapacityDecrease() {
ByteBuf buffer = newBuffer(3, 13);
assertEquals(13, buffer.maxCapacity());
assertEquals(3, buffer.capacity());
try {
buffer.capacity(2);
assertEquals(2, buffer.capacity());
assertEquals(13, buffer.maxCapacity());
} finally {
buffer.release();
}
}
@Test
public void testCapacityIncrease() {
ByteBuf buffer = newBuffer(3, 13);
assertEquals(13, buffer.maxCapacity());
assertEquals(3, buffer.capacity());
try {
buffer.capacity(4);
assertEquals(4, buffer.capacity());
assertEquals(13, buffer.maxCapacity());
} finally {
buffer.release();
}
}
@Test(expected = IndexOutOfBoundsException.class)
public void testReaderIndexLargerThanWriterIndex() {
String content1 = "hello";
String content2 = "world";
int length = content1.length() + content2.length();
ByteBuf buffer = newBuffer(length);
buffer.setIndex(0, 0);
buffer.writeCharSequence(content1, CharsetUtil.US_ASCII);
buffer.markWriterIndex();
buffer.skipBytes(content1.length());
buffer.writeCharSequence(content2, CharsetUtil.US_ASCII);
buffer.skipBytes(content2.length());
assertTrue(buffer.readerIndex() <= buffer.writerIndex());
try {
buffer.resetWriterIndex();
} finally {
buffer.release();
}
}
@Test
public void testMaxFastWritableBytes() {
ByteBuf buffer = newBuffer(150, 500).writerIndex(100);
assertEquals(50, buffer.writableBytes());
assertEquals(150, buffer.capacity());
assertEquals(500, buffer.maxCapacity());
assertEquals(400, buffer.maxWritableBytes());
// Default implementation has fast writable == writable
assertEquals(50, buffer.maxFastWritableBytes());
buffer.release();
}
@Test
public void testEnsureWritableIntegerOverflow() {
ByteBuf buffer = newBuffer(CAPACITY);
buffer.writerIndex(buffer.readerIndex());
buffer.writeByte(1);
try {
buffer.ensureWritable(Integer.MAX_VALUE);
fail();
} catch (IndexOutOfBoundsException e) {
// expected
} finally {
buffer.release();
}
}
@Test
public void testEndiannessIndexOf() {
buffer.clear();
final int v = 0x02030201;
buffer.writeIntLE(v);
buffer.writeByte(0x01);
assertEquals(-1, buffer.indexOf(1, 4, (byte) 1));
assertEquals(-1, buffer.indexOf(4, 1, (byte) 1));
assertEquals(1, buffer.indexOf(1, 4, (byte) 2));
assertEquals(3, buffer.indexOf(4, 1, (byte) 2));
}
@Test
public void explicitLittleEndianReadMethodsMustAlwaysUseLittleEndianByteOrder() {
buffer.clear();
buffer.writeBytes(new byte[] {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08});
assertEquals(0x0201, buffer.readShortLE());
buffer.readerIndex(0);
assertEquals(0x0201, buffer.readUnsignedShortLE());
buffer.readerIndex(0);
assertEquals(0x030201, buffer.readMediumLE());
buffer.readerIndex(0);
assertEquals(0x030201, buffer.readUnsignedMediumLE());
buffer.readerIndex(0);
assertEquals(0x04030201, buffer.readIntLE());
buffer.readerIndex(0);
assertEquals(0x04030201, buffer.readUnsignedIntLE());
buffer.readerIndex(0);
assertEquals(0x04030201, Float.floatToRawIntBits(buffer.readFloatLE()));
buffer.readerIndex(0);
assertEquals(0x0807060504030201L, buffer.readLongLE());
buffer.readerIndex(0);
assertEquals(0x0807060504030201L, Double.doubleToRawLongBits(buffer.readDoubleLE()));
buffer.readerIndex(0);
}
@Test
public void explicitLittleEndianWriteMethodsMustAlwaysUseLittleEndianByteOrder() {
buffer.clear();
buffer.writeShortLE(0x0102);
assertEquals(0x0102, buffer.readShortLE());
buffer.clear();
buffer.writeMediumLE(0x010203);
assertEquals(0x010203, buffer.readMediumLE());
buffer.clear();
buffer.writeIntLE(0x01020304);
assertEquals(0x01020304, buffer.readIntLE());
buffer.clear();
buffer.writeFloatLE(Float.intBitsToFloat(0x01020304));
assertEquals(0x01020304, Float.floatToRawIntBits(buffer.readFloatLE()));
buffer.clear();
buffer.writeLongLE(0x0102030405060708L);
assertEquals(0x0102030405060708L, buffer.readLongLE());
buffer.clear();
buffer.writeDoubleLE(Double.longBitsToDouble(0x0102030405060708L));
assertEquals(0x0102030405060708L, Double.doubleToRawLongBits(buffer.readDoubleLE()));
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_0 |
crossvul-java_data_bad_1927_2 | /*
* Copyright 2012 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 io.netty.handler.codec.http.multipart;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.HttpConstants;
import io.netty.util.internal.EmptyArrays;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import static io.netty.buffer.Unpooled.EMPTY_BUFFER;
import static io.netty.buffer.Unpooled.wrappedBuffer;
/**
* Abstract Disk HttpData implementation
*/
public abstract class AbstractDiskHttpData extends AbstractHttpData {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractDiskHttpData.class);
private File file;
private boolean isRenamed;
private FileChannel fileChannel;
protected AbstractDiskHttpData(String name, Charset charset, long size) {
super(name, charset, size);
}
/**
*
* @return the real DiskFilename (basename)
*/
protected abstract String getDiskFilename();
/**
*
* @return the default prefix
*/
protected abstract String getPrefix();
/**
*
* @return the default base Directory
*/
protected abstract String getBaseDirectory();
/**
*
* @return the default postfix
*/
protected abstract String getPostfix();
/**
*
* @return True if the file should be deleted on Exit by default
*/
protected abstract boolean deleteOnExit();
/**
* @return a new Temp File from getDiskFilename(), default prefix, postfix and baseDirectory
*/
private File tempFile() throws IOException {
String newpostfix;
String diskFilename = getDiskFilename();
if (diskFilename != null) {
newpostfix = '_' + diskFilename;
} else {
newpostfix = getPostfix();
}
File tmpFile;
if (getBaseDirectory() == null) {
// create a temporary file
tmpFile = File.createTempFile(getPrefix(), newpostfix);
} else {
tmpFile = File.createTempFile(getPrefix(), newpostfix, new File(
getBaseDirectory()));
}
if (deleteOnExit()) {
// See https://github.com/netty/netty/issues/10351
DeleteFileOnExitHook.add(tmpFile.getPath());
}
return tmpFile;
}
@Override
public void setContent(ByteBuf buffer) throws IOException {
ObjectUtil.checkNotNull(buffer, "buffer");
try {
size = buffer.readableBytes();
checkSize(size);
if (definedSize > 0 && definedSize < size) {
throw new IOException("Out of size: " + size + " > " + definedSize);
}
if (file == null) {
file = tempFile();
}
if (buffer.readableBytes() == 0) {
// empty file
if (!file.createNewFile()) {
if (file.length() == 0) {
return;
} else {
if (!file.delete() || !file.createNewFile()) {
throw new IOException("file exists already: " + file);
}
}
}
return;
}
RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
try {
accessFile.setLength(0);
FileChannel localfileChannel = accessFile.getChannel();
ByteBuffer byteBuffer = buffer.nioBuffer();
int written = 0;
while (written < size) {
written += localfileChannel.write(byteBuffer);
}
buffer.readerIndex(buffer.readerIndex() + written);
localfileChannel.force(false);
} finally {
accessFile.close();
}
setCompleted();
} finally {
// Release the buffer as it was retained before and we not need a reference to it at all
// See https://github.com/netty/netty/issues/1516
buffer.release();
}
}
@Override
public void addContent(ByteBuf buffer, boolean last)
throws IOException {
if (buffer != null) {
try {
int localsize = buffer.readableBytes();
checkSize(size + localsize);
if (definedSize > 0 && definedSize < size + localsize) {
throw new IOException("Out of size: " + (size + localsize) +
" > " + definedSize);
}
if (file == null) {
file = tempFile();
}
if (fileChannel == null) {
RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
fileChannel = accessFile.getChannel();
}
int remaining = localsize;
long position = fileChannel.position();
int index = buffer.readerIndex();
while (remaining > 0) {
int written = buffer.getBytes(index, fileChannel, position, remaining);
if (written < 0) {
break;
}
remaining -= written;
position += written;
index += written;
}
fileChannel.position(position);
buffer.readerIndex(index);
size += localsize - remaining;
} finally {
// Release the buffer as it was retained before and we not need a reference to it at all
// See https://github.com/netty/netty/issues/1516
buffer.release();
}
}
if (last) {
if (file == null) {
file = tempFile();
}
if (fileChannel == null) {
RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
fileChannel = accessFile.getChannel();
}
try {
fileChannel.force(false);
} finally {
fileChannel.close();
}
fileChannel = null;
setCompleted();
} else {
ObjectUtil.checkNotNull(buffer, "buffer");
}
}
@Override
public void setContent(File file) throws IOException {
long size = file.length();
checkSize(size);
this.size = size;
if (this.file != null) {
delete();
}
this.file = file;
isRenamed = true;
setCompleted();
}
@Override
public void setContent(InputStream inputStream) throws IOException {
ObjectUtil.checkNotNull(inputStream, "inputStream");
if (file != null) {
delete();
}
file = tempFile();
RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
int written = 0;
try {
accessFile.setLength(0);
FileChannel localfileChannel = accessFile.getChannel();
byte[] bytes = new byte[4096 * 4];
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
int read = inputStream.read(bytes);
while (read > 0) {
byteBuffer.position(read).flip();
written += localfileChannel.write(byteBuffer);
checkSize(written);
read = inputStream.read(bytes);
}
localfileChannel.force(false);
} finally {
accessFile.close();
}
size = written;
if (definedSize > 0 && definedSize < size) {
if (!file.delete()) {
logger.warn("Failed to delete: {}", file);
}
file = null;
throw new IOException("Out of size: " + size + " > " + definedSize);
}
isRenamed = true;
setCompleted();
}
@Override
public void delete() {
if (fileChannel != null) {
try {
fileChannel.force(false);
} catch (IOException e) {
logger.warn("Failed to force.", e);
} finally {
try {
fileChannel.close();
} catch (IOException e) {
logger.warn("Failed to close a file.", e);
}
}
fileChannel = null;
}
if (!isRenamed) {
String filePath = null;
if (file != null && file.exists()) {
filePath = file.getPath();
if (!file.delete()) {
filePath = null;
logger.warn("Failed to delete: {}", file);
}
}
// If you turn on deleteOnExit make sure it is executed.
if (deleteOnExit() && filePath != null) {
DeleteFileOnExitHook.remove(filePath);
}
file = null;
}
}
@Override
public byte[] get() throws IOException {
if (file == null) {
return EmptyArrays.EMPTY_BYTES;
}
return readFrom(file);
}
@Override
public ByteBuf getByteBuf() throws IOException {
if (file == null) {
return EMPTY_BUFFER;
}
byte[] array = readFrom(file);
return wrappedBuffer(array);
}
@Override
public ByteBuf getChunk(int length) throws IOException {
if (file == null || length == 0) {
return EMPTY_BUFFER;
}
if (fileChannel == null) {
RandomAccessFile accessFile = new RandomAccessFile(file, "r");
fileChannel = accessFile.getChannel();
}
int read = 0;
ByteBuffer byteBuffer = ByteBuffer.allocate(length);
try {
while (read < length) {
int readnow = fileChannel.read(byteBuffer);
if (readnow == -1) {
fileChannel.close();
fileChannel = null;
break;
}
read += readnow;
}
} catch (IOException e) {
fileChannel.close();
fileChannel = null;
throw e;
}
if (read == 0) {
return EMPTY_BUFFER;
}
byteBuffer.flip();
ByteBuf buffer = wrappedBuffer(byteBuffer);
buffer.readerIndex(0);
buffer.writerIndex(read);
return buffer;
}
@Override
public String getString() throws IOException {
return getString(HttpConstants.DEFAULT_CHARSET);
}
@Override
public String getString(Charset encoding) throws IOException {
if (file == null) {
return "";
}
if (encoding == null) {
byte[] array = readFrom(file);
return new String(array, HttpConstants.DEFAULT_CHARSET.name());
}
byte[] array = readFrom(file);
return new String(array, encoding.name());
}
@Override
public boolean isInMemory() {
return false;
}
@Override
public boolean renameTo(File dest) throws IOException {
ObjectUtil.checkNotNull(dest, "dest");
if (file == null) {
throw new IOException("No file defined so cannot be renamed");
}
if (!file.renameTo(dest)) {
// must copy
IOException exception = null;
RandomAccessFile inputAccessFile = null;
RandomAccessFile outputAccessFile = null;
long chunkSize = 8196;
long position = 0;
try {
inputAccessFile = new RandomAccessFile(file, "r");
outputAccessFile = new RandomAccessFile(dest, "rw");
FileChannel in = inputAccessFile.getChannel();
FileChannel out = outputAccessFile.getChannel();
while (position < size) {
if (chunkSize < size - position) {
chunkSize = size - position;
}
position += in.transferTo(position, chunkSize, out);
}
} catch (IOException e) {
exception = e;
} finally {
if (inputAccessFile != null) {
try {
inputAccessFile.close();
} catch (IOException e) {
if (exception == null) { // Choose to report the first exception
exception = e;
} else {
logger.warn("Multiple exceptions detected, the following will be suppressed {}", e);
}
}
}
if (outputAccessFile != null) {
try {
outputAccessFile.close();
} catch (IOException e) {
if (exception == null) { // Choose to report the first exception
exception = e;
} else {
logger.warn("Multiple exceptions detected, the following will be suppressed {}", e);
}
}
}
}
if (exception != null) {
throw exception;
}
if (position == size) {
if (!file.delete()) {
logger.warn("Failed to delete: {}", file);
}
file = dest;
isRenamed = true;
return true;
} else {
if (!dest.delete()) {
logger.warn("Failed to delete: {}", dest);
}
return false;
}
}
file = dest;
isRenamed = true;
return true;
}
/**
* Utility function
*
* @return the array of bytes
*/
private static byte[] readFrom(File src) throws IOException {
long srcsize = src.length();
if (srcsize > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"File too big to be loaded in memory");
}
RandomAccessFile accessFile = new RandomAccessFile(src, "r");
byte[] array = new byte[(int) srcsize];
try {
FileChannel fileChannel = accessFile.getChannel();
ByteBuffer byteBuffer = ByteBuffer.wrap(array);
int read = 0;
while (read < srcsize) {
read += fileChannel.read(byteBuffer);
}
} finally {
accessFile.close();
}
return array;
}
@Override
public File getFile() throws IOException {
return file;
}
@Override
public HttpData touch() {
return this;
}
@Override
public HttpData touch(Object hint) {
return this;
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_2 |
crossvul-java_data_bad_1927_10 | /*
* Copyright 2012 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 io.netty.handler.stream;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import org.junit.Assert;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.Channels;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static java.util.concurrent.TimeUnit.*;
import static org.junit.Assert.*;
public class ChunkedWriteHandlerTest {
private static final byte[] BYTES = new byte[1024 * 64];
private static final File TMP;
static {
for (int i = 0; i < BYTES.length; i++) {
BYTES[i] = (byte) i;
}
FileOutputStream out = null;
try {
TMP = File.createTempFile("netty-chunk-", ".tmp");
TMP.deleteOnExit();
out = new FileOutputStream(TMP);
out.write(BYTES);
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignore
}
}
}
}
// See #310
@Test
public void testChunkedStream() {
check(new ChunkedStream(new ByteArrayInputStream(BYTES)));
check(new ChunkedStream(new ByteArrayInputStream(BYTES)),
new ChunkedStream(new ByteArrayInputStream(BYTES)),
new ChunkedStream(new ByteArrayInputStream(BYTES)));
}
@Test
public void testChunkedNioStream() {
check(new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))));
check(new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))),
new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))),
new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))));
}
@Test
public void testChunkedFile() throws IOException {
check(new ChunkedFile(TMP));
check(new ChunkedFile(TMP), new ChunkedFile(TMP), new ChunkedFile(TMP));
}
@Test
public void testChunkedNioFile() throws IOException {
check(new ChunkedNioFile(TMP));
check(new ChunkedNioFile(TMP), new ChunkedNioFile(TMP), new ChunkedNioFile(TMP));
}
@Test
public void testChunkedNioFileLeftPositionUnchanged() throws IOException {
FileChannel in = null;
final long expectedPosition = 10;
try {
in = new RandomAccessFile(TMP, "r").getChannel();
in.position(expectedPosition);
check(new ChunkedNioFile(in) {
@Override
public void close() throws Exception {
//no op
}
});
Assert.assertTrue(in.isOpen());
Assert.assertEquals(expectedPosition, in.position());
} finally {
if (in != null) {
in.close();
}
}
}
@Test(expected = ClosedChannelException.class)
public void testChunkedNioFileFailOnClosedFileChannel() throws IOException {
final FileChannel in = new RandomAccessFile(TMP, "r").getChannel();
in.close();
check(new ChunkedNioFile(in) {
@Override
public void close() throws Exception {
//no op
}
});
Assert.fail();
}
@Test
public void testUnchunkedData() throws IOException {
check(Unpooled.wrappedBuffer(BYTES));
check(Unpooled.wrappedBuffer(BYTES), Unpooled.wrappedBuffer(BYTES), Unpooled.wrappedBuffer(BYTES));
}
// Test case which shows that there is not a bug like stated here:
// https://stackoverflow.com/a/10426305
@Test
public void testListenerNotifiedWhenIsEnd() {
ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.ISO_8859_1);
ChunkedInput<ByteBuf> input = new ChunkedInput<ByteBuf>() {
private boolean done;
private final ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.ISO_8859_1);
@Override
public boolean isEndOfInput() throws Exception {
return done;
}
@Override
public void close() throws Exception {
buffer.release();
}
@Deprecated
@Override
public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
return readChunk(ctx.alloc());
}
@Override
public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {
if (done) {
return null;
}
done = true;
return buffer.retainedDuplicate();
}
@Override
public long length() {
return -1;
}
@Override
public long progress() {
return 1;
}
};
final AtomicBoolean listenerNotified = new AtomicBoolean(false);
final ChannelFutureListener listener = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
listenerNotified.set(true);
}
};
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
ch.writeAndFlush(input).addListener(listener).syncUninterruptibly();
assertTrue(ch.finish());
// the listener should have been notified
assertTrue(listenerNotified.get());
ByteBuf buffer2 = ch.readOutbound();
assertEquals(buffer, buffer2);
assertNull(ch.readOutbound());
buffer.release();
buffer2.release();
}
@Test
public void testChunkedMessageInput() {
ChunkedInput<Object> input = new ChunkedInput<Object>() {
private boolean done;
@Override
public boolean isEndOfInput() throws Exception {
return done;
}
@Override
public void close() throws Exception {
// NOOP
}
@Deprecated
@Override
public Object readChunk(ChannelHandlerContext ctx) throws Exception {
return readChunk(ctx.alloc());
}
@Override
public Object readChunk(ByteBufAllocator ctx) throws Exception {
if (done) {
return false;
}
done = true;
return 0;
}
@Override
public long length() {
return -1;
}
@Override
public long progress() {
return 1;
}
};
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
ch.writeAndFlush(input).syncUninterruptibly();
assertTrue(ch.finish());
assertEquals(0, ch.readOutbound());
assertNull(ch.readOutbound());
}
@Test
public void testWriteFailureChunkedStream() throws IOException {
checkFirstFailed(new ChunkedStream(new ByteArrayInputStream(BYTES)));
}
@Test
public void testWriteFailureChunkedNioStream() throws IOException {
checkFirstFailed(new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))));
}
@Test
public void testWriteFailureChunkedFile() throws IOException {
checkFirstFailed(new ChunkedFile(TMP));
}
@Test
public void testWriteFailureChunkedNioFile() throws IOException {
checkFirstFailed(new ChunkedNioFile(TMP));
}
@Test
public void testWriteFailureUnchunkedData() throws IOException {
checkFirstFailed(Unpooled.wrappedBuffer(BYTES));
}
@Test
public void testSkipAfterFailedChunkedStream() throws IOException {
checkSkipFailed(new ChunkedStream(new ByteArrayInputStream(BYTES)),
new ChunkedStream(new ByteArrayInputStream(BYTES)));
}
@Test
public void testSkipAfterFailedChunkedNioStream() throws IOException {
checkSkipFailed(new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))),
new ChunkedNioStream(Channels.newChannel(new ByteArrayInputStream(BYTES))));
}
@Test
public void testSkipAfterFailedChunkedFile() throws IOException {
checkSkipFailed(new ChunkedFile(TMP), new ChunkedFile(TMP));
}
@Test
public void testSkipAfterFailedChunkedNioFile() throws IOException {
checkSkipFailed(new ChunkedNioFile(TMP), new ChunkedFile(TMP));
}
// See https://github.com/netty/netty/issues/8700.
@Test
public void testFailureWhenLastChunkFailed() throws IOException {
ChannelOutboundHandlerAdapter failLast = new ChannelOutboundHandlerAdapter() {
private int passedWrites;
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
if (++this.passedWrites < 4) {
ctx.write(msg, promise);
} else {
ReferenceCountUtil.release(msg);
promise.tryFailure(new RuntimeException());
}
}
};
EmbeddedChannel ch = new EmbeddedChannel(failLast, new ChunkedWriteHandler());
ChannelFuture r = ch.writeAndFlush(new ChunkedFile(TMP, 1024 * 16)); // 4 chunks
assertTrue(ch.finish());
assertFalse(r.isSuccess());
assertTrue(r.cause() instanceof RuntimeException);
// 3 out of 4 chunks were already written
int read = 0;
for (;;) {
ByteBuf buffer = ch.readOutbound();
if (buffer == null) {
break;
}
read += buffer.readableBytes();
buffer.release();
}
assertEquals(1024 * 16 * 3, read);
}
@Test
public void testDiscardPendingWritesOnInactive() throws IOException {
final AtomicBoolean closeWasCalled = new AtomicBoolean(false);
ChunkedInput<ByteBuf> notifiableInput = new ChunkedInput<ByteBuf>() {
private boolean done;
private final ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.ISO_8859_1);
@Override
public boolean isEndOfInput() throws Exception {
return done;
}
@Override
public void close() throws Exception {
buffer.release();
closeWasCalled.set(true);
}
@Deprecated
@Override
public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
return readChunk(ctx.alloc());
}
@Override
public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {
if (done) {
return null;
}
done = true;
return buffer.retainedDuplicate();
}
@Override
public long length() {
return -1;
}
@Override
public long progress() {
return 1;
}
};
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
// Write 3 messages and close channel before flushing
ChannelFuture r1 = ch.write(new ChunkedFile(TMP));
ChannelFuture r2 = ch.write(new ChunkedNioFile(TMP));
ch.write(notifiableInput);
// Should be `false` as we do not expect any messages to be written
assertFalse(ch.finish());
assertFalse(r1.isSuccess());
assertFalse(r2.isSuccess());
assertTrue(closeWasCalled.get());
}
// See https://github.com/netty/netty/issues/8700.
@Test
public void testStopConsumingChunksWhenFailed() {
final ByteBuf buffer = Unpooled.copiedBuffer("Test", CharsetUtil.ISO_8859_1);
final AtomicInteger chunks = new AtomicInteger(0);
ChunkedInput<ByteBuf> nonClosableInput = new ChunkedInput<ByteBuf>() {
@Override
public boolean isEndOfInput() throws Exception {
return chunks.get() >= 5;
}
@Override
public void close() throws Exception {
// no-op
}
@Deprecated
@Override
public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
return readChunk(ctx.alloc());
}
@Override
public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {
chunks.incrementAndGet();
return buffer.retainedDuplicate();
}
@Override
public long length() {
return -1;
}
@Override
public long progress() {
return 1;
}
};
ChannelOutboundHandlerAdapter noOpWrites = new ChannelOutboundHandlerAdapter() {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
ReferenceCountUtil.release(msg);
promise.tryFailure(new RuntimeException());
}
};
EmbeddedChannel ch = new EmbeddedChannel(noOpWrites, new ChunkedWriteHandler());
ch.writeAndFlush(nonClosableInput).awaitUninterruptibly();
// Should be `false` as we do not expect any messages to be written
assertFalse(ch.finish());
buffer.release();
// We should expect only single chunked being read from the input.
// It's possible to get a race condition here between resolving a promise and
// allocating a new chunk, but should be fine when working with embedded channels.
assertEquals(1, chunks.get());
}
@Test
public void testCloseSuccessfulChunkedInput() {
int chunks = 10;
TestChunkedInput input = new TestChunkedInput(chunks);
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
assertTrue(ch.writeOutbound(input));
for (int i = 0; i < chunks; i++) {
ByteBuf buf = ch.readOutbound();
assertEquals(i, buf.readInt());
buf.release();
}
assertTrue(input.isClosed());
assertFalse(ch.finish());
}
@Test
public void testCloseFailedChunkedInput() {
Exception error = new Exception("Unable to produce a chunk");
ThrowingChunkedInput input = new ThrowingChunkedInput(error);
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
try {
ch.writeOutbound(input);
fail("Exception expected");
} catch (Exception e) {
assertEquals(error, e);
}
assertTrue(input.isClosed());
assertFalse(ch.finish());
}
@Test
public void testWriteListenerInvokedAfterSuccessfulChunkedInputClosed() throws Exception {
final TestChunkedInput input = new TestChunkedInput(2);
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
final AtomicBoolean inputClosedWhenListenerInvoked = new AtomicBoolean();
final CountDownLatch listenerInvoked = new CountDownLatch(1);
ChannelFuture writeFuture = ch.write(input);
writeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
inputClosedWhenListenerInvoked.set(input.isClosed());
listenerInvoked.countDown();
}
});
ch.flush();
assertTrue(listenerInvoked.await(10, SECONDS));
assertTrue(writeFuture.isSuccess());
assertTrue(inputClosedWhenListenerInvoked.get());
assertTrue(ch.finishAndReleaseAll());
}
@Test
public void testWriteListenerInvokedAfterFailedChunkedInputClosed() throws Exception {
final ThrowingChunkedInput input = new ThrowingChunkedInput(new RuntimeException());
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
final AtomicBoolean inputClosedWhenListenerInvoked = new AtomicBoolean();
final CountDownLatch listenerInvoked = new CountDownLatch(1);
ChannelFuture writeFuture = ch.write(input);
writeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
inputClosedWhenListenerInvoked.set(input.isClosed());
listenerInvoked.countDown();
}
});
ch.flush();
assertTrue(listenerInvoked.await(10, SECONDS));
assertFalse(writeFuture.isSuccess());
assertTrue(inputClosedWhenListenerInvoked.get());
assertFalse(ch.finish());
}
@Test
public void testWriteListenerInvokedAfterChannelClosedAndInputFullyConsumed() throws Exception {
// use empty input which has endOfInput = true
final TestChunkedInput input = new TestChunkedInput(0);
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
final AtomicBoolean inputClosedWhenListenerInvoked = new AtomicBoolean();
final CountDownLatch listenerInvoked = new CountDownLatch(1);
ChannelFuture writeFuture = ch.write(input);
writeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
inputClosedWhenListenerInvoked.set(input.isClosed());
listenerInvoked.countDown();
}
});
ch.close(); // close channel to make handler discard the input on subsequent flush
ch.flush();
assertTrue(listenerInvoked.await(10, SECONDS));
assertTrue(writeFuture.isSuccess());
assertTrue(inputClosedWhenListenerInvoked.get());
assertFalse(ch.finish());
}
@Test
public void testWriteListenerInvokedAfterChannelClosedAndInputNotFullyConsumed() throws Exception {
// use non-empty input which has endOfInput = false
final TestChunkedInput input = new TestChunkedInput(42);
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
final AtomicBoolean inputClosedWhenListenerInvoked = new AtomicBoolean();
final CountDownLatch listenerInvoked = new CountDownLatch(1);
ChannelFuture writeFuture = ch.write(input);
writeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
inputClosedWhenListenerInvoked.set(input.isClosed());
listenerInvoked.countDown();
}
});
ch.close(); // close channel to make handler discard the input on subsequent flush
ch.flush();
assertTrue(listenerInvoked.await(10, SECONDS));
assertFalse(writeFuture.isSuccess());
assertTrue(inputClosedWhenListenerInvoked.get());
assertFalse(ch.finish());
}
private static void check(Object... inputs) {
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
for (Object input: inputs) {
ch.writeOutbound(input);
}
assertTrue(ch.finish());
int i = 0;
int read = 0;
for (;;) {
ByteBuf buffer = ch.readOutbound();
if (buffer == null) {
break;
}
while (buffer.isReadable()) {
assertEquals(BYTES[i++], buffer.readByte());
read++;
if (i == BYTES.length) {
i = 0;
}
}
buffer.release();
}
assertEquals(BYTES.length * inputs.length, read);
}
private static void checkFirstFailed(Object input) {
ChannelOutboundHandlerAdapter noOpWrites = new ChannelOutboundHandlerAdapter() {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
ReferenceCountUtil.release(msg);
promise.tryFailure(new RuntimeException());
}
};
EmbeddedChannel ch = new EmbeddedChannel(noOpWrites, new ChunkedWriteHandler());
ChannelFuture r = ch.writeAndFlush(input);
// Should be `false` as we do not expect any messages to be written
assertFalse(ch.finish());
assertTrue(r.cause() instanceof RuntimeException);
}
private static void checkSkipFailed(Object input1, Object input2) {
ChannelOutboundHandlerAdapter failFirst = new ChannelOutboundHandlerAdapter() {
private boolean alreadyFailed;
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
if (alreadyFailed) {
ctx.write(msg, promise);
} else {
this.alreadyFailed = true;
ReferenceCountUtil.release(msg);
promise.tryFailure(new RuntimeException());
}
}
};
EmbeddedChannel ch = new EmbeddedChannel(failFirst, new ChunkedWriteHandler());
ChannelFuture r1 = ch.write(input1);
ChannelFuture r2 = ch.writeAndFlush(input2).awaitUninterruptibly();
assertTrue(ch.finish());
assertTrue(r1.cause() instanceof RuntimeException);
assertTrue(r2.isSuccess());
// note, that after we've "skipped" the first write,
// we expect to see the second message, chunk by chunk
int i = 0;
int read = 0;
for (;;) {
ByteBuf buffer = ch.readOutbound();
if (buffer == null) {
break;
}
while (buffer.isReadable()) {
assertEquals(BYTES[i++], buffer.readByte());
read++;
if (i == BYTES.length) {
i = 0;
}
}
buffer.release();
}
assertEquals(BYTES.length, read);
}
private static final class TestChunkedInput implements ChunkedInput<ByteBuf> {
private final int chunksToProduce;
private int chunksProduced;
private volatile boolean closed;
TestChunkedInput(int chunksToProduce) {
this.chunksToProduce = chunksToProduce;
}
@Override
public boolean isEndOfInput() {
return chunksProduced >= chunksToProduce;
}
@Override
public void close() {
closed = true;
}
@Override
public ByteBuf readChunk(ChannelHandlerContext ctx) {
return readChunk(ctx.alloc());
}
@Override
public ByteBuf readChunk(ByteBufAllocator allocator) {
ByteBuf buf = allocator.buffer();
buf.writeInt(chunksProduced);
chunksProduced++;
return buf;
}
@Override
public long length() {
return chunksToProduce;
}
@Override
public long progress() {
return chunksProduced;
}
boolean isClosed() {
return closed;
}
}
private static final class ThrowingChunkedInput implements ChunkedInput<ByteBuf> {
private final Exception error;
private volatile boolean closed;
ThrowingChunkedInput(Exception error) {
this.error = error;
}
@Override
public boolean isEndOfInput() {
return false;
}
@Override
public void close() {
closed = true;
}
@Override
public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
return readChunk(ctx.alloc());
}
@Override
public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {
throw error;
}
@Override
public long length() {
return -1;
}
@Override
public long progress() {
return -1;
}
boolean isClosed() {
return closed;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/bad_1927_10 |
crossvul-java_data_good_1927_14 | /*
* Copyright 2016 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 io.netty.channel.unix.tests;
import io.netty.channel.unix.DomainSocketAddress;
import io.netty.channel.unix.Socket;
import io.netty.util.internal.PlatformDependent;
import java.io.File;
import java.io.IOException;
public final class UnixTestUtils {
public static DomainSocketAddress newSocketAddress() {
try {
File file;
do {
file = PlatformDependent.createTempFile("NETTY", "UDS", null);
if (!file.delete()) {
throw new IOException("failed to delete: " + file);
}
} while (file.getAbsolutePath().length() > 128);
return new DomainSocketAddress(file);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private UnixTestUtils() { }
}
| ./CrossVul/dataset_final_sorted/CWE-379/java/good_1927_14 |
crossvul-java_data_good_5634_0 | /*******************************************************************************
* Copyright (C) 2009-2011 FuseSource Corp.
* Copyright (c) 2000, 2009 IBM Corporation and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.fusesource.hawtjni.runtime;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.util.regex.Pattern;
/**
* Used to optionally extract and load a JNI library.
*
* It will search for the library in order at the following locations:
* <ol>
* <li> in the custom library path: If the "library.${name}.path" System property is set to a directory
* <ol>
* <li> "${name}-${version}" if the version can be determined.
* <li> "${name}"
* </ol>
* <li> system library path: This is where the JVM looks for JNI libraries by default.
* <ol>
* <li> "${name}-${version}" if the version can be determined.
* <li> "${name}"
* </ol>
* <li> classpath path: If the JNI library can be found on the classpath, it will get extracted
* and and then loaded. This way you can embed your JNI libraries into your packaged JAR files.
* They are looked up as resources in this order:
* <ol>
* <li> "META-INF/native/${platform}/${library}" : Store your library here if you want to embed more
* than one platform JNI library in the jar.
* <li> "META-INF/native/${library}": Store your library here if your JAR is only going to embedding one
* platform library.
* </ol>
* The file extraction is attempted until it succeeds in the following directories.
* <ol>
* <li> The directory pointed to by the "library.${name}.path" System property (if set)
* <li> a temporary directory (uses the "java.io.tmpdir" System property)
* </ol>
* </ol>
*
* where:
* <ul>
* <li>"${name}" is the name of library
* <li>"${version}" is the value of "library.${name}.version" System property if set.
* Otherwise it is set to the ImplementationVersion property of the JAR's Manifest</li>
* <li>"${os}" is your operating system, for example "osx", "linux", or "windows"</li>
* <li>"${bit-model}" is "64" if the JVM process is a 64 bit process, otherwise it's "32" if the
* JVM is a 32 bit process</li>
* <li>"${platform}" is "${os}${bit-model}", for example "linux32" or "osx64" </li>
* <li>"${library}": is the normal jni library name for the platform. For example "${name}.dll" on
* windows, "lib${name}.jnilib" on OS X, and "lib${name}.so" on linux</li>
* </ul>
*
* @author <a href="http://hiramchirino.com">Hiram Chirino</a>
*/
public class Library {
static final String SLASH = System.getProperty("file.separator");
final private String name;
final private String version;
final private ClassLoader classLoader;
private boolean loaded;
public Library(String name) {
this(name, null, null);
}
public Library(String name, Class<?> clazz) {
this(name, version(clazz), clazz.getClassLoader());
}
public Library(String name, String version) {
this(name, version, null);
}
public Library(String name, String version, ClassLoader classLoader) {
if( name == null ) {
throw new IllegalArgumentException("name cannot be null");
}
this.name = name;
this.version = version;
this.classLoader= classLoader;
}
private static String version(Class<?> clazz) {
try {
return clazz.getPackage().getImplementationVersion();
} catch (Throwable e) {
}
return null;
}
public static String getOperatingSystem() {
String name = System.getProperty("os.name").toLowerCase().trim();
if( name.startsWith("linux") ) {
return "linux";
}
if( name.startsWith("mac os x") ) {
return "osx";
}
if( name.startsWith("win") ) {
return "windows";
}
return name.replaceAll("\\W+", "_");
}
public static String getPlatform() {
return getOperatingSystem()+getBitModel();
}
public static int getBitModel() {
String prop = System.getProperty("sun.arch.data.model");
if (prop == null) {
prop = System.getProperty("com.ibm.vm.bitmode");
}
if( prop!=null ) {
return Integer.parseInt(prop);
}
return -1; // we don't know..
}
/**
*
*/
synchronized public void load() {
if( loaded ) {
return;
}
doLoad();
loaded = true;
}
private void doLoad() {
/* Perhaps a custom version is specified */
String version = System.getProperty("library."+name+".version");
if (version == null) {
version = this.version;
}
ArrayList<String> errors = new ArrayList<String>();
/* Try loading library from a custom library path */
String customPath = System.getProperty("library."+name+".path");
if (customPath != null) {
if( version!=null && load(errors, file(customPath, map(name + "-" + version))) )
return;
if( load(errors, file(customPath, map(name))) )
return;
}
/* Try loading library from java library path */
if( version!=null && load(errors, name + getBitModel() + "-" + version) )
return;
if( version!=null && load(errors, name + "-" + version) )
return;
if( load(errors, name ) )
return;
/* Try extracting the library from the jar */
if( classLoader!=null ) {
if( exractAndLoad(errors, version, customPath, getPlatformSpecifcResourcePath()) )
return;
if( exractAndLoad(errors, version, customPath, getOperatingSystemSpecifcResourcePath()) )
return;
// For the simpler case where only 1 platform lib is getting packed into the jar
if( exractAndLoad(errors, version, customPath, getResorucePath()) )
return;
}
/* Failed to find the library */
throw new UnsatisfiedLinkError("Could not load library. Reasons: " + errors.toString());
}
final public String getOperatingSystemSpecifcResourcePath() {
return getPlatformSpecifcResourcePath(getOperatingSystem());
}
final public String getPlatformSpecifcResourcePath() {
return getPlatformSpecifcResourcePath(getPlatform());
}
final public String getPlatformSpecifcResourcePath(String platform) {
return "META-INF/native/"+platform+"/"+map(name);
}
final public String getResorucePath() {
return "META-INF/native/"+map(name);
}
final public String getLibraryFileName() {
return map(name);
}
private boolean exractAndLoad(ArrayList<String> errors, String version, String customPath, String resourcePath) {
URL resource = classLoader.getResource(resourcePath);
if( resource !=null ) {
String libName = name + "-" + getBitModel();
if( version !=null) {
libName += "-" + version;
}
String []libNameParts = map(libName).split("\\.");
String prefix = libNameParts[0]+"-";
String suffix = "."+libNameParts[1];
if( customPath!=null ) {
// Try to extract it to the custom path...
File target = extract(errors, resource, prefix, suffix, file(customPath));
if( target!=null ) {
if( load(errors, target) ) {
return true;
}
}
}
// Fall back to extracting to the tmp dir
customPath = System.getProperty("java.io.tmpdir");
File target = extract(errors, resource, prefix, suffix, file(customPath));
if( target!=null ) {
if( load(errors, target) ) {
return true;
}
}
}
return false;
}
private File file(String ...paths) {
File rc = null ;
for (String path : paths) {
if( rc == null ) {
rc = new File(path);
} else {
rc = new File(rc, path);
}
}
return rc;
}
private String map(String libName) {
/*
* libraries in the Macintosh use the extension .jnilib but the some
* VMs map to .dylib.
*/
libName = System.mapLibraryName(libName);
String ext = ".dylib";
if (libName.endsWith(ext)) {
libName = libName.substring(0, libName.length() - ext.length()) + ".jnilib";
}
return libName;
}
private File extract(ArrayList<String> errors, URL source, String prefix, String suffix, File directory) {
File target = null;
try {
FileOutputStream os = null;
InputStream is = null;
try {
target = File.createTempFile(prefix, suffix, directory);
is = source.openStream();
if (is != null) {
byte[] buffer = new byte[4096];
os = new FileOutputStream(target);
int read;
while ((read = is.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
chmod("755", target);
}
target.deleteOnExit();
return target;
} finally {
close(os);
close(is);
}
} catch (Throwable e) {
if( target!=null ) {
target.delete();
}
errors.add(e.getMessage());
}
return null;
}
static private void close(Closeable file) {
if(file!=null) {
try {
file.close();
} catch (Exception ignore) {
}
}
}
private void chmod(String permision, File path) {
if (getPlatform().startsWith("windows"))
return;
try {
Runtime.getRuntime().exec(new String[] { "chmod", permision, path.getCanonicalPath() }).waitFor();
} catch (Throwable e) {
}
}
private boolean load(ArrayList<String> errors, File lib) {
try {
System.load(lib.getPath());
return true;
} catch (UnsatisfiedLinkError e) {
errors.add(e.getMessage());
}
return false;
}
private boolean load(ArrayList<String> errors, String lib) {
try {
System.loadLibrary(lib);
return true;
} catch (UnsatisfiedLinkError e) {
errors.add(e.getMessage());
}
return false;
}
}
| ./CrossVul/dataset_final_sorted/CWE-94/java/good_5634_0 |
crossvul-java_data_bad_5634_0 | /*******************************************************************************
* Copyright (C) 2009-2011 FuseSource Corp.
* Copyright (c) 2000, 2009 IBM Corporation and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.fusesource.hawtjni.runtime;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Pattern;
/**
* Used to optionally extract and load a JNI library.
*
* It will search for the library in order at the following locations:
* <ol>
* <li> in the custom library path: If the "library.${name}.path" System property is set to a directory
* <ol>
* <li> "${name}-${version}" if the version can be determined.
* <li> "${name}"
* </ol>
* <li> system library path: This is where the JVM looks for JNI libraries by default.
* <ol>
* <li> "${name}-${version}" if the version can be determined.
* <li> "${name}"
* </ol>
* <li> classpath path: If the JNI library can be found on the classpath, it will get extracted
* and and then loaded. This way you can embed your JNI libraries into your packaged JAR files.
* They are looked up as resources in this order:
* <ol>
* <li> "META-INF/native/${platform}/${library}" : Store your library here if you want to embed more
* than one platform JNI library in the jar.
* <li> "META-INF/native/${library}": Store your library here if your JAR is only going to embedding one
* platform library.
* </ol>
* The file extraction is attempted until it succeeds in the following directories.
* <ol>
* <li> The directory pointed to by the "library.${name}.path" System property (if set)
* <li> a temporary directory (uses the "java.io.tmpdir" System property)
* </ol>
* </ol>
*
* where:
* <ul>
* <li>"${name}" is the name of library
* <li>"${version}" is the value of "library.${name}.version" System property if set.
* Otherwise it is set to the ImplementationVersion property of the JAR's Manifest</li>
* <li>"${os}" is your operating system, for example "osx", "linux", or "windows"</li>
* <li>"${bit-model}" is "64" if the JVM process is a 64 bit process, otherwise it's "32" if the
* JVM is a 32 bit process</li>
* <li>"${platform}" is "${os}${bit-model}", for example "linux32" or "osx64" </li>
* <li>"${library}": is the normal jni library name for the platform. For example "${name}.dll" on
* windows, "lib${name}.jnilib" on OS X, and "lib${name}.so" on linux</li>
* </ul>
*
* @author <a href="http://hiramchirino.com">Hiram Chirino</a>
*/
public class Library {
static final String SLASH = System.getProperty("file.separator");
final private String name;
final private String version;
final private ClassLoader classLoader;
private boolean loaded;
public Library(String name) {
this(name, null, null);
}
public Library(String name, Class<?> clazz) {
this(name, version(clazz), clazz.getClassLoader());
}
public Library(String name, String version) {
this(name, version, null);
}
public Library(String name, String version, ClassLoader classLoader) {
if( name == null ) {
throw new IllegalArgumentException("name cannot be null");
}
this.name = name;
this.version = version;
this.classLoader= classLoader;
}
private static String version(Class<?> clazz) {
try {
return clazz.getPackage().getImplementationVersion();
} catch (Throwable e) {
}
return null;
}
public static String getOperatingSystem() {
String name = System.getProperty("os.name").toLowerCase().trim();
if( name.startsWith("linux") ) {
return "linux";
}
if( name.startsWith("mac os x") ) {
return "osx";
}
if( name.startsWith("win") ) {
return "windows";
}
return name.replaceAll("\\W+", "_");
}
public static String getPlatform() {
return getOperatingSystem()+getBitModel();
}
public static int getBitModel() {
String prop = System.getProperty("sun.arch.data.model");
if (prop == null) {
prop = System.getProperty("com.ibm.vm.bitmode");
}
if( prop!=null ) {
return Integer.parseInt(prop);
}
return -1; // we don't know..
}
/**
*
*/
synchronized public void load() {
if( loaded ) {
return;
}
doLoad();
loaded = true;
}
private void doLoad() {
/* Perhaps a custom version is specified */
String version = System.getProperty("library."+name+".version");
if (version == null) {
version = this.version;
}
ArrayList<String> errors = new ArrayList<String>();
/* Try loading library from a custom library path */
String customPath = System.getProperty("library."+name+".path");
if (customPath != null) {
if( version!=null && load(errors, file(customPath, map(name + "-" + version))) )
return;
if( load(errors, file(customPath, map(name))) )
return;
}
/* Try loading library from java library path */
if( version!=null && load(errors, name + getBitModel() + "-" + version) )
return;
if( version!=null && load(errors, name + "-" + version) )
return;
if( load(errors, name ) )
return;
/* Try extracting the library from the jar */
if( classLoader!=null ) {
if( exractAndLoad(errors, version, customPath, getPlatformSpecifcResourcePath()) )
return;
if( exractAndLoad(errors, version, customPath, getOperatingSystemSpecifcResourcePath()) )
return;
// For the simpler case where only 1 platform lib is getting packed into the jar
if( exractAndLoad(errors, version, customPath, getResorucePath()) )
return;
}
/* Failed to find the library */
throw new UnsatisfiedLinkError("Could not load library. Reasons: " + errors.toString());
}
final public String getOperatingSystemSpecifcResourcePath() {
return getPlatformSpecifcResourcePath(getOperatingSystem());
}
final public String getPlatformSpecifcResourcePath() {
return getPlatformSpecifcResourcePath(getPlatform());
}
final public String getPlatformSpecifcResourcePath(String platform) {
return "META-INF/native/"+platform+"/"+map(name);
}
final public String getResorucePath() {
return "META-INF/native/"+map(name);
}
final public String getLibraryFileName() {
return map(name);
}
private boolean exractAndLoad(ArrayList<String> errors, String version, String customPath, String resourcePath) {
URL resource = classLoader.getResource(resourcePath);
if( resource !=null ) {
String libName = name + "-" + getBitModel();
if( version !=null) {
libName += "-" + version;
}
if( customPath!=null ) {
// Try to extract it to the custom path...
File target = file(customPath, map(libName));
if( extract(errors, resource, target) ) {
if( load(errors, target) ) {
return true;
}
}
}
// Fall back to extracting to the tmp dir
customPath = System.getProperty("java.io.tmpdir");
File target = file(customPath, map(libName));
if( extract(errors, resource, target) ) {
if( load(errors, target) ) {
return true;
}
}
}
return false;
}
private File file(String ...paths) {
File rc = null ;
for (String path : paths) {
if( rc == null ) {
rc = new File(path);
} else {
rc = new File(rc, path);
}
}
return rc;
}
private String map(String libName) {
/*
* libraries in the Macintosh use the extension .jnilib but the some
* VMs map to .dylib.
*/
libName = System.mapLibraryName(libName);
String ext = ".dylib";
if (libName.endsWith(ext)) {
libName = libName.substring(0, libName.length() - ext.length()) + ".jnilib";
}
return libName;
}
private boolean extract(ArrayList<String> errors, URL source, File target) {
FileOutputStream os = null;
InputStream is = null;
boolean extracting = false;
try {
if (!target.exists() || isStale(source, target) ) {
is = source.openStream();
if (is != null) {
byte[] buffer = new byte[4096];
os = new FileOutputStream(target);
extracting = true;
int read;
while ((read = is.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
os.close();
is.close();
chmod("755", target);
}
}
} catch (Throwable e) {
try {
if (os != null)
os.close();
} catch (IOException e1) {
}
try {
if (is != null)
is.close();
} catch (IOException e1) {
}
if (extracting && target.exists())
target.delete();
errors.add(e.getMessage());
return false;
}
return true;
}
private boolean isStale(URL source, File target) {
if( source.getProtocol().equals("jar") ) {
// unwrap the jar protocol...
try {
String parts[] = source.getFile().split(Pattern.quote("!"));
source = new URL(parts[0]);
} catch (MalformedURLException e) {
return false;
}
}
File sourceFile=null;
if( source.getProtocol().equals("file") ) {
sourceFile = new File(source.getFile());
}
if( sourceFile!=null && sourceFile.exists() ) {
if( sourceFile.lastModified() > target.lastModified() ) {
return true;
}
}
return false;
}
private void chmod(String permision, File path) {
if (getPlatform().startsWith("windows"))
return;
try {
Runtime.getRuntime().exec(new String[] { "chmod", permision, path.getCanonicalPath() }).waitFor();
} catch (Throwable e) {
}
}
private boolean load(ArrayList<String> errors, File lib) {
try {
System.load(lib.getPath());
return true;
} catch (UnsatisfiedLinkError e) {
errors.add(e.getMessage());
}
return false;
}
private boolean load(ArrayList<String> errors, String lib) {
try {
System.loadLibrary(lib);
return true;
} catch (UnsatisfiedLinkError e) {
errors.add(e.getMessage());
}
return false;
}
}
| ./CrossVul/dataset_final_sorted/CWE-94/java/bad_5634_0 |
crossvul-java_data_good_3052_4 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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.ExtensionPoint;
import hudson.ExtensionList;
import hudson.Extension;
import hudson.ExtensionPoint.LegacyInstancesAreScopedToHudson;
import hudson.triggers.SCMTrigger;
import hudson.triggers.TimerTrigger;
import java.util.Set;
import java.io.IOException;
import jenkins.model.Jenkins;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* Checks the health of a subsystem of Jenkins and if there's something
* that requires administrator's attention, notify the administrator.
*
* <h2>How to implement?</h2>
* <p>
* Plugins who wish to contribute such notifications can implement this
* class and put {@link Extension} on it to register it to Jenkins.
*
* <p>
* Once installed, it's the implementer's responsibility to perform
* monitoring and activate/deactivate the monitor accordingly. Sometimes
* this can be done by updating a flag from code (see {@link SCMTrigger}
* for one such example), while other times it's more convenient to do
* so by running some code periodically (for this, use {@link TimerTrigger#timer})
*
* <p>
* {@link AdministrativeMonitor}s are bound to URL by {@link Jenkins#getAdministrativeMonitor(String)}.
* See {@link #getUrl()}.
*
* <h3>Views</h3>
* <dl>
* <dt>message.jelly</dt>
* <dd>
* If {@link #isActivated()} returns true, Jenkins will use the <tt>message.jelly</tt>
* view of this object to render the warning text. This happens in the
* <tt>http://SERVER/jenkins/manage</tt> page. This view should typically render
* a DIV box with class='error' or class='warning' with a human-readable text
* inside it. It often also contains a link to a page that provides more details
* about the problem.
* </dd>
* </dl>
*
* @author Kohsuke Kawaguchi
* @since 1.273
* @see Jenkins#administrativeMonitors
*/
@LegacyInstancesAreScopedToHudson
public abstract class AdministrativeMonitor extends AbstractModelObject implements ExtensionPoint, StaplerProxy {
/**
* Human-readable ID of this monitor, which needs to be unique within the system.
*
* <p>
* This ID is used to remember persisted setting for this monitor,
* so the ID should remain consistent beyond the Hudson JVM lifespan.
*/
public final String id;
protected AdministrativeMonitor(String id) {
this.id = id;
}
protected AdministrativeMonitor() {
this.id = this.getClass().getName();
}
/**
* Returns the URL of this monitor, relative to the context path, like "administrativeMonitor/foobar".
*/
public String getUrl() {
return "administrativeMonitor/"+id;
}
public String getDisplayName() {
return id;
}
public final String getSearchUrl() {
return getUrl();
}
/**
* Mark this monitor as disabled, to prevent this from showing up in the UI.
*/
public void disable(boolean value) throws IOException {
AbstractCIBase hudson = Jenkins.getInstance();
Set<String> set = hudson.disabledAdministrativeMonitors;
if(value) set.add(id);
else set.remove(id);
hudson.save();
}
/**
* Returns true if this monitor {@link #disable(boolean) isn't disabled} earlier.
*
* <p>
* This flag implements the ability for the admin to say "no thank you" to the monitor that
* he wants to ignore.
*/
public boolean isEnabled() {
return !((AbstractCIBase)Jenkins.getInstance()).disabledAdministrativeMonitors.contains(id);
}
/**
* Returns true if this monitor is activated and
* wants to produce a warning message.
*
* <p>
* This method is called from the HTML rendering thread,
* so it should run efficiently.
*/
public abstract boolean isActivated();
/**
* URL binding to disable this monitor.
*/
@RequirePOST
public void doDisable(StaplerRequest req, StaplerResponse rsp) throws IOException {
disable(true);
rsp.sendRedirect2(req.getContextPath()+"/manage");
}
/**
* Requires ADMINISTER permission for any operation in here.
*/
@Restricted(NoExternalUse.class)
public Object getTarget() {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
return this;
}
/**
* All registered {@link AdministrativeMonitor} instances.
*/
public static ExtensionList<AdministrativeMonitor> all() {
return ExtensionList.lookup(AdministrativeMonitor.class);
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_3052_4 |
crossvul-java_data_good_2094_0 | package jenkins.security;
import hudson.model.User;
import hudson.security.ACL;
import hudson.security.UserMayOrMayNotExistException;
import hudson.util.Scrambler;
import jenkins.model.Jenkins;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* {@link Filter} that performs HTTP basic authentication based on API token.
*
* <p>
* Normally the filter chain would also contain another filter that handles BASIC
* auth with the real password. Care must be taken to ensure that this doesn't
* interfere with the other.
*
* @author Kohsuke Kawaguchi
*/
public class ApiTokenFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse rsp = (HttpServletResponse) response;
String authorization = req.getHeader("Authorization");
if (authorization!=null) {
// authenticate the user
String uidpassword = Scrambler.descramble(authorization.substring(6));
int idx = uidpassword.indexOf(':');
if (idx >= 0) {
String username = uidpassword.substring(0, idx);
try {
Jenkins.getInstance().getSecurityRealm().loadUserByUsername(username);
} catch (UserMayOrMayNotExistException x) {
// OK, give them the benefit of the doubt.
} catch (UsernameNotFoundException x) {
// Not/no longer a user; deny the API token. (But do not leak the information that this happened.)
chain.doFilter(request, response);
return;
} catch (DataAccessException x) {
throw new ServletException(x);
}
String password = uidpassword.substring(idx+1);
// attempt to authenticate as API token
User u = User.get(username);
ApiTokenProperty t = u.getProperty(ApiTokenProperty.class);
if (t!=null && t.matchesPassword(password)) {
// even if we fail to match the password, we aren't rejecting it.
// as the user might be passing in a real password.
SecurityContext oldContext = ACL.impersonate(u.impersonate());
try {
request.setAttribute(ApiTokenProperty.class.getName(), u);
chain.doFilter(request,response);
return;
} finally {
SecurityContextHolder.setContext(oldContext);
}
}
}
}
chain.doFilter(request,response);
}
public void destroy() {
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_2094_0 |
crossvul-java_data_bad_3052_11 | package hudson.diagnosis;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.xml.sax.SAXException;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import java.io.IOException;
/**
* @author Kohsuke Kawaguchi
*/
public class HudsonHomeDiskUsageMonitorTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Test
public void flow() throws Exception {
// manually activate this
HudsonHomeDiskUsageMonitor mon = HudsonHomeDiskUsageMonitor.get();
mon.activated = true;
// clicking yes should take us to somewhere
j.submit(getForm(mon), "yes");
assertTrue(mon.isEnabled());
// now dismiss
// submit(getForm(mon),"no"); TODO: figure out why this test is fragile
mon.doAct("no");
assertFalse(mon.isEnabled());
// and make sure it's gone
try {
fail(getForm(mon)+" shouldn't be there");
} catch (ElementNotFoundException e) {
// as expected
}
}
/**
* Gets the warning form.
*/
private HtmlForm getForm(HudsonHomeDiskUsageMonitor mon) throws IOException, SAXException {
HtmlPage p = j.createWebClient().goTo("manage");
return p.getFormByName(mon.id);
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/bad_3052_11 |
crossvul-java_data_good_3052_2 | /*
* The MIT License
*
* Copyright (c) 2010, InfraDNA, Inc.
*
* 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.diagnosis;
import hudson.Extension;
import hudson.Util;
import hudson.model.AdministrativeMonitor;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* Looks out for a broken reverse proxy setup that doesn't rewrite the location header correctly.
*
* <p>
* Have the JavaScript make an AJAX call, to which we respond with 302 redirect. If the reverse proxy
* is done correctly, this will be handled by {@link #doFoo()}, but otherwise we'll report that as an error.
* Unfortunately, {@code XmlHttpRequest} doesn't expose properties that allow the client-side JavaScript
* to learn the details of the failure, so we have to make do with limited information.
*
* @author Kohsuke Kawaguchi
*/
@Extension
public class ReverseProxySetupMonitor extends AdministrativeMonitor {
private static final Logger LOGGER = Logger.getLogger(ReverseProxySetupMonitor.class.getName());
@Override
public boolean isActivated() {
// return true to always inject an HTML fragment to perform a test
return true;
}
public HttpResponse doTest() {
String referer = Stapler.getCurrentRequest().getReferer();
Jenkins j = Jenkins.getInstance();
assert j != null;
// May need to send an absolute URL, since handling of HttpRedirect with a relative URL does not currently honor X-Forwarded-Proto/Port at all.
String redirect = j.getRootUrl() + "administrativeMonitor/" + id + "/testForReverseProxySetup/" + (referer != null ? Util.rawEncode(referer) : "NO-REFERER") + "/";
LOGGER.log(Level.FINE, "coming from {0} and redirecting to {1}", new Object[] {referer, redirect});
return new HttpRedirect(redirect);
}
public void getTestForReverseProxySetup(String rest) {
Jenkins j = Jenkins.getInstance();
assert j != null;
String inferred = j.getRootUrlFromRequest() + "manage";
// TODO this could also verify that j.getRootUrl() has been properly configured, and send a different message if not
if (rest.startsWith(inferred)) { // not using equals due to JENKINS-24014
throw HttpResponses.ok();
} else {
LOGGER.log(Level.WARNING, "{0} vs. {1}", new Object[] {inferred, rest});
throw HttpResponses.errorWithoutStack(404, inferred + " vs. " + rest);
}
}
/**
* Depending on whether the user said "yes" or "no", send him to the right place.
*/
@RequirePOST
public HttpResponse doAct(@QueryParameter String no) throws IOException {
if(no!=null) { // dismiss
disable(true);
// of course the irony is that this redirect won't work
return HttpResponses.redirectViaContextPath("/manage");
} else {
return new HttpRedirect("https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+says+my+reverse+proxy+setup+is+broken");
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_3052_2 |
crossvul-java_data_good_2098_0 | /*
* 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.
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());
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_2098_0 |
crossvul-java_data_bad_3052_8 | package jenkins.security.s2m;
import hudson.Extension;
import hudson.model.AdministrativeMonitor;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import javax.inject.Inject;
import java.io.IOException;
/**
* If {@link AdminWhitelistRule#masterKillSwitch} is on, warn the user.
*
* @author Kohsuke Kawaguchi
* @since 1.THU
*/
@Extension
public class MasterKillSwitchWarning extends AdministrativeMonitor {
@Inject
AdminWhitelistRule rule;
@Inject
MasterKillSwitchConfiguration config;
@Override
public boolean isActivated() {
return rule.getMasterKillSwitch() && config.isRelevant();
}
public HttpResponse doAct(@QueryParameter String dismiss) throws IOException {
if(dismiss!=null) {
disable(true);
return HttpResponses.redirectViaContextPath("/manage");
} else {
return HttpResponses.redirectViaContextPath("configureSecurity");
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/bad_3052_8 |
crossvul-java_data_good_2029_6 | package io.hawt.web;
import java.io.IOException;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import javax.security.auth.Subject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import io.hawt.system.Authenticator;
import io.hawt.system.ConfigManager;
import io.hawt.system.Helpers;
import io.hawt.system.PrivilegedCallback;
import io.hawt.web.tomcat.TomcatAuthenticationContainerDiscovery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Filter for authentication. If the filter is enabled, then the login screen is shown.
*/
public class AuthenticationFilter implements Filter {
private static final transient Logger LOG = LoggerFactory.getLogger(AuthenticationFilter.class);
// JVM system properties
public static final String HAWTIO_AUTHENTICATION_ENABLED = "hawtio.authenticationEnabled";
public static final String HAWTIO_REALM = "hawtio.realm";
public static final String HAWTIO_ROLE = "hawtio.role";
public static final String HAWTIO_ROLE_PRINCIPAL_CLASSES = "hawtio.rolePrincipalClasses";
private final AuthenticationConfiguration configuration = new AuthenticationConfiguration();
// add known SPI authentication container discovery
private final AuthenticationContainerDiscovery[] discoveries = new AuthenticationContainerDiscovery[]{
new TomcatAuthenticationContainerDiscovery()
};
@Override
public void init(FilterConfig filterConfig) throws ServletException {
ConfigManager config = (ConfigManager) filterConfig.getServletContext().getAttribute("ConfigManager");
if (config != null) {
configuration.setRealm(config.get("realm", "karaf"));
configuration.setRole(config.get("role", "admin"));
configuration.setRolePrincipalClasses(config.get("rolePrincipalClasses", ""));
configuration.setEnabled(Boolean.parseBoolean(config.get("authenticationEnabled", "true")));
}
// JVM system properties can override always
if (System.getProperty(HAWTIO_AUTHENTICATION_ENABLED) != null) {
configuration.setEnabled(Boolean.getBoolean(HAWTIO_AUTHENTICATION_ENABLED));
}
if (System.getProperty(HAWTIO_REALM) != null) {
configuration.setRealm(System.getProperty(HAWTIO_REALM));
}
if (System.getProperty(HAWTIO_ROLE) != null) {
configuration.setRole(System.getProperty(HAWTIO_ROLE));
}
if (System.getProperty(HAWTIO_ROLE_PRINCIPAL_CLASSES) != null) {
configuration.setRolePrincipalClasses(System.getProperty(HAWTIO_ROLE_PRINCIPAL_CLASSES));
}
if (configuration.isEnabled()) {
for (AuthenticationContainerDiscovery discovery : discoveries) {
if (discovery.canAuthenticate(configuration)) {
LOG.info("Discovered container {} to use with hawtio authentication filter", discovery.getContainerName());
break;
}
}
}
if (configuration.isEnabled()) {
LOG.info("Starting hawtio authentication filter, JAAS realm: \"{}\" authorized role: \"{}\" role principal classes: \"{}\"",
new Object[]{configuration.getRealm(), configuration.getRole(), configuration.getRolePrincipalClasses()});
} else {
LOG.info("Starting hawtio authentication filter, JAAS authentication disabled");
}
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String path = httpRequest.getServletPath();
LOG.debug("Handling request for path {}", path);
if (configuration.getRealm() == null || configuration.getRealm().equals("") || !configuration.isEnabled()) {
LOG.debug("No authentication needed for path {}", path);
chain.doFilter(request, response);
return;
}
HttpSession session = httpRequest.getSession(false);
if (session != null) {
Subject subject = (Subject) session.getAttribute("subject");
if (subject != null) {
LOG.debug("Session subject {}", subject);
executeAs(request, response, chain, subject);
return;
}
}
boolean doAuthenticate = true;
if (doAuthenticate) {
LOG.debug("Doing authentication and authorization for path {}", path);
switch (Authenticator.authenticate(configuration.getRealm(), configuration.getRole(), configuration.getRolePrincipalClasses(),
configuration.getConfiguration(), httpRequest, new PrivilegedCallback() {
public void execute(Subject subject) throws Exception {
executeAs(request, response, chain, subject);
}
})) {
case AUTHORIZED:
// request was executed using the authenticated subject, nothing more to do
break;
case NOT_AUTHORIZED:
Helpers.doForbidden((HttpServletResponse) response);
break;
case NO_CREDENTIALS:
//doAuthPrompt((HttpServletResponse)response);
Helpers.doForbidden((HttpServletResponse) response);
break;
}
} else {
LOG.warn("No authentication needed for path {}", path);
chain.doFilter(request, response);
}
}
private static void executeAs(final ServletRequest request, final ServletResponse response, final FilterChain chain, Subject subject) {
try {
Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
chain.doFilter(request, response);
return null;
}
});
} catch (PrivilegedActionException e) {
LOG.info("Failed to invoke action " + ((HttpServletRequest) request).getPathInfo() + " due to:", e);
}
}
@Override
public void destroy() {
LOG.info("Destroying hawtio authentication filter");
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_2029_6 |
crossvul-java_data_good_3052_6 | package jenkins.security;
import hudson.Extension;
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import hudson.model.TaskListener;
import hudson.util.HttpResponses;
import hudson.util.SecretRewriter;
import hudson.util.VersionNumber;
import jenkins.management.AsynchronousAdministrativeMonitor;
import jenkins.model.Jenkins;
import jenkins.util.io.FileBoolean;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.interceptor.RequirePOST;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Warns the administrator to run {@link SecretRewriter}
*
* @author Kohsuke Kawaguchi
*/
@Extension
public class RekeySecretAdminMonitor extends AsynchronousAdministrativeMonitor {
/**
* Whether we detected a need to run the rewrite program.
* Once we set it to true, we'll never turn it off.
*
* If the admin decides to dismiss this warning, we use {@link #isEnabled()} for that.
*
* In this way we can correctly differentiate all the different states.
*/
private final FileBoolean needed = state("needed");
/**
* If the scanning process has run to the completion, we set to this true.
*/
private final FileBoolean done = state("done");
/**
* If the rewrite process is scheduled upon the next boot.
*/
private final FileBoolean scanOnBoot = state("scanOnBoot");
public RekeySecretAdminMonitor() throws IOException {
// if JENKINS_HOME existed <1.497, we need to offer rewrite
// this computation needs to be done and the value be captured,
// since $JENKINS_HOME/config.xml can be saved later before the user has
// actually rewritten XML files.
Jenkins j = Jenkins.getInstance();
if (j.isUpgradedFromBefore(new VersionNumber("1.496.*"))
&& new FileBoolean(new File(j.getRootDir(),"secret.key.not-so-secret")).isOff())
needed.on();
}
@Override
public boolean isActivated() {
return needed.isOn();
}
/**
* Indicates that the re-keying has run to the completion.
*/
public boolean isDone() {
return done.isOn();
}
public void setNeeded() {
needed.on();
}
public boolean isScanOnBoot() {
return scanOnBoot.isOn();
}
@RequirePOST
public HttpResponse doScan(StaplerRequest req) throws IOException, GeneralSecurityException {
if(req.hasParameter("background")) {
start(false);
} else
if(req.hasParameter("schedule")) {
scanOnBoot.on();
} else
if(req.hasParameter("dismiss")) {
disable(true);
} else
throw HttpResponses.error(400,"Invalid request submission: " + req.getParameterMap());
return HttpResponses.redirectViaContextPath("/manage");
}
private FileBoolean state(String name) {
return new FileBoolean(new File(getBaseDir(),name));
}
@Initializer(fatal=false,after=InitMilestone.PLUGINS_STARTED,before=InitMilestone.EXTENSIONS_AUGMENTED)
// as early as possible, but this needs to be late enough that the ConfidentialStore is available
public static void scanOnReboot() throws InterruptedException, IOException, GeneralSecurityException {
RekeySecretAdminMonitor m = new RekeySecretAdminMonitor(); // throw-away instance
FileBoolean flag = m.scanOnBoot;
if (flag.isOn()) {
flag.off();
m.start(false).join();
// block the boot until the rewrite process is complete
// don't let the failure in RekeyThread block Jenkins boot.
}
}
@Override
public String getDisplayName() {
return Messages.RekeySecretAdminMonitor_DisplayName();
}
/**
* Rewrite log file.
*/
@Override
protected File getLogFile() {
return new File(getBaseDir(),"rekey.log");
}
@Override
protected void fix(TaskListener listener) throws Exception {
LOGGER.info("Initiating a re-keying of secrets. See "+getLogFile());
SecretRewriter rewriter = new SecretRewriter(new File(getBaseDir(),"backups"));
try {
PrintStream log = listener.getLogger();
log.println("Started re-keying " + new Date());
int count = rewriter.rewriteRecursive(Jenkins.getInstance().getRootDir(), listener);
log.printf("Completed re-keying %d files on %s\n",count,new Date());
new RekeySecretAdminMonitor().done.on();
LOGGER.info("Secret re-keying completed");
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Fatal failure in re-keying secrets",e);
e.printStackTrace(listener.error("Fatal failure in rewriting secrets"));
}
}
private static final Logger LOGGER = Logger.getLogger(RekeySecretAdminMonitor.class.getName());
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_3052_6 |
crossvul-java_data_good_3052_7 | package jenkins.security.s2m;
import hudson.Extension;
import hudson.FilePath;
import hudson.model.AdministrativeMonitor;
import hudson.remoting.Callable;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.inject.Inject;
import java.io.IOException;
/**
* Report any rejected {@link Callable}s and {@link FilePath} executions and allow
* admins to whitelist them.
*
* @since 1.THU
* @author Kohsuke Kawaguchi
*/
@Extension
public class AdminCallableMonitor extends AdministrativeMonitor {
@Inject
Jenkins jenkins;
@Inject
AdminWhitelistRule rule;
public AdminCallableMonitor() {
super("slaveToMasterAccessControl");
}
@Override
public boolean isActivated() {
return !rule.rejected.describe().isEmpty();
}
@Override
public String getDisplayName() {
return "Slave \u2192 Master Access Control";
}
// bind this to URL
public AdminWhitelistRule getRule() {
return rule;
}
/**
* Depending on whether the user said "examin" or "dismiss", send him to the right place.
*/
@RequirePOST
public HttpResponse doAct(@QueryParameter String dismiss) throws IOException {
if(dismiss!=null) {
disable(true);
return HttpResponses.redirectViaContextPath("/manage");
} else {
return HttpResponses.redirectTo("rule/");
}
}
public HttpResponse doIndex() {
return HttpResponses.redirectTo("rule/");
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_3052_7 |
crossvul-java_data_bad_2029_1 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-287/java/bad_2029_1 |
crossvul-java_data_bad_2098_0 | /*
* 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.
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());
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/bad_2098_0 |
crossvul-java_data_good_2029_2 | package io.hawt.web.plugin.karaf.terminal;
import io.hawt.system.Helpers;
import org.apache.felix.service.command.CommandProcessor;
import org.apache.felix.service.command.CommandSession;
import org.apache.felix.service.threadio.ThreadIO;
import org.apache.karaf.shell.console.jline.Console;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.Subject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.lang.reflect.Constructor;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.util.zip.GZIPOutputStream;
/**
*
*/
public class TerminalServlet extends HttpServlet {
public static final int TERM_WIDTH = 120;
public static final int TERM_HEIGHT = 39;
private final static Logger LOG = LoggerFactory.getLogger(TerminalServlet.class);
/**
* Pseudo class version ID to keep the IDE quite.
*/
private static final long serialVersionUID = 1L;
public CommandProcessor getCommandProcessor() {
return CommandProcessorHolder.getCommandProcessor();
}
public ThreadIO getThreadIO() {
return ThreadIOHolder.getThreadIO();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session == null) {
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
if (subject == null) {
Helpers.doForbidden(response);
return;
}
session = request.getSession(true);
session.setAttribute("subject", subject);
} else {
Subject subject = (Subject) session.getAttribute("subject");
if (subject == null) {
session.invalidate();
Helpers.doForbidden(response);
return;
}
}
String encoding = request.getHeader("Accept-Encoding");
boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1);
SessionTerminal st = (SessionTerminal) session.getAttribute("terminal");
if (st == null || st.isClosed()) {
st = new SessionTerminal(getCommandProcessor(), getThreadIO());
session.setAttribute("terminal", st);
}
String str = request.getParameter("k");
String f = request.getParameter("f");
String dump = st.handle(str, f != null && f.length() > 0);
if (dump != null) {
if (supportsGzip) {
response.setHeader("Content-Encoding", "gzip");
response.setHeader("Content-Type", "text/html");
try {
GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
gzos.write(dump.getBytes());
gzos.close();
} catch (IOException ie) {
LOG.info("Exception writing response: ", ie);
}
} else {
response.getOutputStream().write(dump.getBytes());
}
}
}
public class SessionTerminal implements Runnable {
private Terminal terminal;
private Console console;
private PipedOutputStream in;
private PipedInputStream out;
private boolean closed;
public SessionTerminal(CommandProcessor commandProcessor, ThreadIO threadIO) throws IOException {
try {
this.terminal = new Terminal(TERM_WIDTH, TERM_HEIGHT);
terminal.write("\u001b\u005B20\u0068"); // set newline mode on
in = new PipedOutputStream();
out = new PipedInputStream();
PrintStream pipedOut = new PrintStream(new PipedOutputStream(out), true);
Constructor ctr = Console.class.getConstructors()[0];
if (ctr.getParameterTypes().length <= 7) {
LOG.debug("Using old Karaf Console API");
// the old API does not have the threadIO parameter, so its only 7 parameters
console = (Console) ctr.newInstance(commandProcessor,
new PipedInputStream(in),
pipedOut,
pipedOut,
new WebTerminal(TERM_WIDTH, TERM_HEIGHT),
null,
null);
} else {
LOG.debug("Using new Karaf Console API");
// use the new api directly which we compile against
console = new Console(commandProcessor,
threadIO,
new PipedInputStream(in),
pipedOut,
pipedOut,
new WebTerminal(TERM_WIDTH, TERM_HEIGHT),
null,
null);
}
CommandSession session = console.getSession();
session.put("APPLICATION", System.getProperty("karaf.name", "root"));
session.put("USER", "karaf");
session.put("COLUMNS", Integer.toString(TERM_WIDTH));
session.put("LINES", Integer.toString(TERM_HEIGHT));
} catch (IOException e) {
LOG.info("Exception attaching to console", e);
throw e;
} catch (Exception e) {
LOG.info("Exception attaching to console", e);
throw (IOException) new IOException().initCause(e);
}
new Thread(console).start();
new Thread(this).start();
}
public boolean isClosed() {
return closed;
}
public String handle(String str, boolean forceDump) throws IOException {
try {
if (str != null && str.length() > 0) {
String d = terminal.pipe(str);
for (byte b : d.getBytes()) {
in.write(b);
}
in.flush();
}
} catch (IOException e) {
closed = true;
throw e;
}
try {
return terminal.dump(10, forceDump);
} catch (InterruptedException e) {
throw new InterruptedIOException(e.toString());
}
}
public void run() {
try {
for (; ; ) {
byte[] buf = new byte[8192];
int l = out.read(buf);
InputStreamReader r = new InputStreamReader(new ByteArrayInputStream(buf, 0, l));
StringBuilder sb = new StringBuilder();
for (; ; ) {
int c = r.read();
if (c == -1) {
break;
}
sb.append((char) c);
}
if (sb.length() > 0) {
terminal.write(sb.toString());
}
String s = terminal.read();
if (s != null && s.length() > 0) {
for (byte b : s.getBytes()) {
in.write(b);
}
}
}
} catch (IOException e) {
closed = true;
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_2029_2 |
crossvul-java_data_good_3052_8 | package jenkins.security.s2m;
import hudson.Extension;
import hudson.model.AdministrativeMonitor;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.inject.Inject;
import java.io.IOException;
/**
* If {@link AdminWhitelistRule#masterKillSwitch} is on, warn the user.
*
* @author Kohsuke Kawaguchi
* @since 1.THU
*/
@Extension
public class MasterKillSwitchWarning extends AdministrativeMonitor {
@Inject
AdminWhitelistRule rule;
@Inject
MasterKillSwitchConfiguration config;
@Override
public boolean isActivated() {
return rule.getMasterKillSwitch() && config.isRelevant();
}
@RequirePOST
public HttpResponse doAct(@QueryParameter String dismiss) throws IOException {
if(dismiss!=null) {
disable(true);
return HttpResponses.redirectViaContextPath("/manage");
} else {
return HttpResponses.redirectViaContextPath("configureSecurity");
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_3052_8 |
crossvul-java_data_bad_3052_5 | package jenkins.diagnostics;
import hudson.Extension;
import hudson.model.AdministrativeMonitor;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import java.io.IOException;
/**
* Unsecured Jenkins is, well, insecure.
*
* <p>
* Call attention to the fact that Jenkins is not secured, and encourage the administrator
* to take an action.
*
* @author Kohsuke Kawaguchi
*/
@Extension
public class SecurityIsOffMonitor extends AdministrativeMonitor {
@Override
public boolean isActivated() {
return !Jenkins.getInstance().isUseSecurity();
}
/**
* Depending on whether the user said "yes" or "no", send him to the right place.
*/
public void doAct(StaplerRequest req, StaplerResponse rsp) throws IOException {
if(req.hasParameter("no")) {
disable(true);
rsp.sendRedirect(req.getContextPath()+"/manage");
} else {
rsp.sendRedirect(req.getContextPath()+"/configureSecurity");
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/bad_3052_5 |
crossvul-java_data_bad_2094_0 | package jenkins.security;
import hudson.model.User;
import hudson.security.ACL;
import hudson.util.Scrambler;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* {@link Filter} that performs HTTP basic authentication based on API token.
*
* <p>
* Normally the filter chain would also contain another filter that handles BASIC
* auth with the real password. Care must be taken to ensure that this doesn't
* interfere with the other.
*
* @author Kohsuke Kawaguchi
*/
public class ApiTokenFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse rsp = (HttpServletResponse) response;
String authorization = req.getHeader("Authorization");
if (authorization!=null) {
// authenticate the user
String uidpassword = Scrambler.descramble(authorization.substring(6));
int idx = uidpassword.indexOf(':');
if (idx >= 0) {
String username = uidpassword.substring(0, idx);
String password = uidpassword.substring(idx+1);
// attempt to authenticate as API token
User u = User.get(username);
ApiTokenProperty t = u.getProperty(ApiTokenProperty.class);
if (t!=null && t.matchesPassword(password)) {
// even if we fail to match the password, we aren't rejecting it.
// as the user might be passing in a real password.
SecurityContext oldContext = ACL.impersonate(u.impersonate());
try {
request.setAttribute(ApiTokenProperty.class.getName(), u);
chain.doFilter(request,response);
return;
} finally {
SecurityContextHolder.setContext(oldContext);
}
}
}
}
chain.doFilter(request,response);
}
public void destroy() {
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/bad_2094_0 |
crossvul-java_data_bad_3052_6 | package jenkins.security;
import hudson.Extension;
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import hudson.model.TaskListener;
import hudson.util.HttpResponses;
import hudson.util.SecretRewriter;
import hudson.util.VersionNumber;
import jenkins.management.AsynchronousAdministrativeMonitor;
import jenkins.model.Jenkins;
import jenkins.util.io.FileBoolean;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.interceptor.RequirePOST;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Warns the administrator to run {@link SecretRewriter}
*
* @author Kohsuke Kawaguchi
*/
@Extension
public class RekeySecretAdminMonitor extends AsynchronousAdministrativeMonitor implements StaplerProxy {
/**
* Whether we detected a need to run the rewrite program.
* Once we set it to true, we'll never turn it off.
*
* If the admin decides to dismiss this warning, we use {@link #isEnabled()} for that.
*
* In this way we can correctly differentiate all the different states.
*/
private final FileBoolean needed = state("needed");
/**
* If the scanning process has run to the completion, we set to this true.
*/
private final FileBoolean done = state("done");
/**
* If the rewrite process is scheduled upon the next boot.
*/
private final FileBoolean scanOnBoot = state("scanOnBoot");
public RekeySecretAdminMonitor() throws IOException {
// if JENKINS_HOME existed <1.497, we need to offer rewrite
// this computation needs to be done and the value be captured,
// since $JENKINS_HOME/config.xml can be saved later before the user has
// actually rewritten XML files.
Jenkins j = Jenkins.getInstance();
if (j.isUpgradedFromBefore(new VersionNumber("1.496.*"))
&& new FileBoolean(new File(j.getRootDir(),"secret.key.not-so-secret")).isOff())
needed.on();
}
/**
* Requires ADMINISTER permission for any operation in here.
*/
public Object getTarget() {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
return this;
}
@Override
public boolean isActivated() {
return needed.isOn();
}
/**
* Indicates that the re-keying has run to the completion.
*/
public boolean isDone() {
return done.isOn();
}
public void setNeeded() {
needed.on();
}
public boolean isScanOnBoot() {
return scanOnBoot.isOn();
}
@RequirePOST
public HttpResponse doScan(StaplerRequest req) throws IOException, GeneralSecurityException {
if(req.hasParameter("background")) {
start(false);
} else
if(req.hasParameter("schedule")) {
scanOnBoot.on();
} else
if(req.hasParameter("dismiss")) {
disable(true);
} else
throw HttpResponses.error(400,"Invalid request submission: " + req.getParameterMap());
return HttpResponses.redirectViaContextPath("/manage");
}
private FileBoolean state(String name) {
return new FileBoolean(new File(getBaseDir(),name));
}
@Initializer(fatal=false,after=InitMilestone.PLUGINS_STARTED,before=InitMilestone.EXTENSIONS_AUGMENTED)
// as early as possible, but this needs to be late enough that the ConfidentialStore is available
public static void scanOnReboot() throws InterruptedException, IOException, GeneralSecurityException {
RekeySecretAdminMonitor m = new RekeySecretAdminMonitor(); // throw-away instance
FileBoolean flag = m.scanOnBoot;
if (flag.isOn()) {
flag.off();
m.start(false).join();
// block the boot until the rewrite process is complete
// don't let the failure in RekeyThread block Jenkins boot.
}
}
@Override
public String getDisplayName() {
return Messages.RekeySecretAdminMonitor_DisplayName();
}
/**
* Rewrite log file.
*/
@Override
protected File getLogFile() {
return new File(getBaseDir(),"rekey.log");
}
@Override
protected void fix(TaskListener listener) throws Exception {
LOGGER.info("Initiating a re-keying of secrets. See "+getLogFile());
SecretRewriter rewriter = new SecretRewriter(new File(getBaseDir(),"backups"));
try {
PrintStream log = listener.getLogger();
log.println("Started re-keying " + new Date());
int count = rewriter.rewriteRecursive(Jenkins.getInstance().getRootDir(), listener);
log.printf("Completed re-keying %d files on %s\n",count,new Date());
new RekeySecretAdminMonitor().done.on();
LOGGER.info("Secret re-keying completed");
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Fatal failure in re-keying secrets",e);
e.printStackTrace(listener.error("Fatal failure in rewriting secrets"));
}
}
private static final Logger LOGGER = Logger.getLogger(RekeySecretAdminMonitor.class.getName());
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/bad_3052_6 |
crossvul-java_data_bad_3052_4 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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.ExtensionPoint;
import hudson.ExtensionList;
import hudson.Extension;
import hudson.ExtensionPoint.LegacyInstancesAreScopedToHudson;
import hudson.triggers.SCMTrigger;
import hudson.triggers.TimerTrigger;
import java.util.Set;
import java.io.IOException;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
/**
* Checks the health of a subsystem of Jenkins and if there's something
* that requires administrator's attention, notify the administrator.
*
* <h2>How to implement?</h2>
* <p>
* Plugins who wish to contribute such notifications can implement this
* class and put {@link Extension} on it to register it to Jenkins.
*
* <p>
* Once installed, it's the implementer's responsibility to perform
* monitoring and activate/deactivate the monitor accordingly. Sometimes
* this can be done by updating a flag from code (see {@link SCMTrigger}
* for one such example), while other times it's more convenient to do
* so by running some code periodically (for this, use {@link TimerTrigger#timer})
*
* <p>
* {@link AdministrativeMonitor}s are bound to URL by {@link Jenkins#getAdministrativeMonitor(String)}.
* See {@link #getUrl()}.
*
* <h3>Views</h3>
* <dl>
* <dt>message.jelly</dt>
* <dd>
* If {@link #isActivated()} returns true, Jenkins will use the <tt>message.jelly</tt>
* view of this object to render the warning text. This happens in the
* <tt>http://SERVER/jenkins/manage</tt> page. This view should typically render
* a DIV box with class='error' or class='warning' with a human-readable text
* inside it. It often also contains a link to a page that provides more details
* about the problem.
* </dd>
* </dl>
*
* @author Kohsuke Kawaguchi
* @since 1.273
* @see Jenkins#administrativeMonitors
*/
@LegacyInstancesAreScopedToHudson
public abstract class AdministrativeMonitor extends AbstractModelObject implements ExtensionPoint {
/**
* Human-readable ID of this monitor, which needs to be unique within the system.
*
* <p>
* This ID is used to remember persisted setting for this monitor,
* so the ID should remain consistent beyond the Hudson JVM lifespan.
*/
public final String id;
protected AdministrativeMonitor(String id) {
this.id = id;
}
protected AdministrativeMonitor() {
this.id = this.getClass().getName();
}
/**
* Returns the URL of this monitor, relative to the context path, like "administrativeMonitor/foobar".
*/
public String getUrl() {
return "administrativeMonitor/"+id;
}
public String getDisplayName() {
return id;
}
public final String getSearchUrl() {
return getUrl();
}
/**
* Mark this monitor as disabled, to prevent this from showing up in the UI.
*/
public void disable(boolean value) throws IOException {
AbstractCIBase hudson = Jenkins.getInstance();
Set<String> set = hudson.disabledAdministrativeMonitors;
if(value) set.add(id);
else set.remove(id);
hudson.save();
}
/**
* Returns true if this monitor {@link #disable(boolean) isn't disabled} earlier.
*
* <p>
* This flag implements the ability for the admin to say "no thank you" to the monitor that
* he wants to ignore.
*/
public boolean isEnabled() {
return !((AbstractCIBase)Jenkins.getInstance()).disabledAdministrativeMonitors.contains(id);
}
/**
* Returns true if this monitor is activated and
* wants to produce a warning message.
*
* <p>
* This method is called from the HTML rendering thread,
* so it should run efficiently.
*/
public abstract boolean isActivated();
/**
* URL binding to disable this monitor.
*/
public void doDisable(StaplerRequest req, StaplerResponse rsp) throws IOException {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
disable(true);
rsp.sendRedirect2(req.getContextPath()+"/manage");
}
/**
* All registered {@link AdministrativeMonitor} instances.
*/
public static ExtensionList<AdministrativeMonitor> all() {
return ExtensionList.lookup(AdministrativeMonitor.class);
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/bad_3052_4 |
crossvul-java_data_good_3052_1 | /*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Alan Harder
*
* 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.diagnosis;
import com.google.common.base.Predicate;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import hudson.Extension;
import hudson.XmlFile;
import hudson.model.AdministrativeMonitor;
import hudson.model.Item;
import hudson.model.Job;
import hudson.model.ManagementLink;
import hudson.model.Run;
import hudson.model.Saveable;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.RunListener;
import hudson.model.listeners.SaveableListener;
import hudson.security.ACL;
import hudson.util.RobustReflectionConverter;
import hudson.util.VersionNumber;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import jenkins.model.Jenkins;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* Tracks whether any data structure changes were corrected when loading XML,
* that could be resaved to migrate that data to the new format.
*
* @author Alan.Harder@Sun.Com
*/
@Extension
public class OldDataMonitor extends AdministrativeMonitor {
private static final Logger LOGGER = Logger.getLogger(OldDataMonitor.class.getName());
private ConcurrentMap<SaveableReference,VersionRange> data = new ConcurrentHashMap<SaveableReference,VersionRange>();
static OldDataMonitor get(Jenkins j) {
return (OldDataMonitor) j.getAdministrativeMonitor("OldData");
}
public OldDataMonitor() {
super("OldData");
}
@Override
public String getDisplayName() {
return Messages.OldDataMonitor_DisplayName();
}
public boolean isActivated() {
return !data.isEmpty();
}
public Map<Saveable,VersionRange> getData() {
Map<Saveable,VersionRange> r = new HashMap<Saveable,VersionRange>();
for (Map.Entry<SaveableReference,VersionRange> entry : this.data.entrySet()) {
Saveable s = entry.getKey().get();
if (s != null) {
r.put(s, entry.getValue());
}
}
return r;
}
private static void remove(Saveable obj, boolean isDelete) {
Jenkins j = Jenkins.getInstance();
if (j != null) {
OldDataMonitor odm = get(j);
SecurityContext oldContext = ACL.impersonate(ACL.SYSTEM);
try {
odm.data.remove(referTo(obj));
if (isDelete && obj instanceof Job<?, ?>) {
for (Run r : ((Job<?, ?>) obj).getBuilds()) {
odm.data.remove(referTo(r));
}
}
} finally {
SecurityContextHolder.setContext(oldContext);
}
}
}
// Listeners to remove data here if resaved or deleted in regular Hudson usage
@Extension
public static final SaveableListener changeListener = new SaveableListener() {
@Override
public void onChange(Saveable obj, XmlFile file) {
remove(obj, false);
}
};
@Extension
public static final ItemListener itemDeleteListener = new ItemListener() {
@Override
public void onDeleted(Item item) {
remove(item, true);
}
};
@Extension
public static final RunListener<Run> runDeleteListener = new RunListener<Run>() {
@Override
public void onDeleted(Run run) {
remove(run, true);
}
};
/**
* Inform monitor that some data in a deprecated format has been loaded,
* and converted in-memory to a new structure.
* @param obj Saveable object; calling save() on this object will persist
* the data in its new format to disk.
* @param version Hudson release when the data structure changed.
*/
public static void report(Saveable obj, String version) {
OldDataMonitor odm = get(Jenkins.getInstance());
try {
SaveableReference ref = referTo(obj);
while (true) {
VersionRange vr = odm.data.get(ref);
if (vr != null && odm.data.replace(ref, vr, new VersionRange(vr, version, null))) {
break;
} else if (odm.data.putIfAbsent(ref, new VersionRange(null, version, null)) == null) {
break;
}
}
} catch (IllegalArgumentException ex) {
LOGGER.log(Level.WARNING, "Bad parameter given to OldDataMonitor", ex);
}
}
/**
* Inform monitor that some data in a deprecated format has been loaded, during
* XStream unmarshalling when the Saveable containing this object is not available.
* @param context XStream unmarshalling context
* @param version Hudson release when the data structure changed.
*/
public static void report(UnmarshallingContext context, String version) {
RobustReflectionConverter.addErrorInContext(context, new ReportException(version));
}
private static class ReportException extends Exception {
private String version;
private ReportException(String version) {
this.version = version;
}
}
/**
* Inform monitor that some unreadable data was found while loading.
* @param obj Saveable object; calling save() on this object will discard the unreadable data.
* @param errors Exception(s) thrown while loading, regarding the unreadable classes/fields.
*/
public static void report(Saveable obj, Collection<Throwable> errors) {
StringBuilder buf = new StringBuilder();
int i = 0;
for (Throwable e : errors) {
if (e instanceof ReportException) {
report(obj, ((ReportException)e).version);
} else {
if (++i > 1) buf.append(", ");
buf.append(e.getClass().getSimpleName()).append(": ").append(e.getMessage());
}
}
if (buf.length() == 0) return;
Jenkins j = Jenkins.getInstance();
if (j == null) {
// Startup failed, something is very broken, so report what we can.
for (Throwable t : errors) {
LOGGER.log(Level.WARNING, "could not read " + obj + " (and Jenkins did not start up)", t);
}
return;
}
OldDataMonitor odm = get(j);
SaveableReference ref = referTo(obj);
while (true) {
VersionRange vr = odm.data.get(ref);
if (vr != null && odm.data.replace(ref, vr, new VersionRange(vr, null, buf.toString()))) {
break;
} else if (odm.data.putIfAbsent(ref, new VersionRange(null, null, buf.toString())) == null) {
break;
}
}
}
public static class VersionRange {
private static VersionNumber currentVersion = Jenkins.getVersion();
final VersionNumber min;
final VersionNumber max;
final boolean single;
final public String extra;
public VersionRange(VersionRange previous, String version, String extra) {
if (previous == null) {
min = max = version != null ? new VersionNumber(version) : null;
this.single = true;
this.extra = extra;
} else if (version == null) {
min = previous.min;
max = previous.max;
single = previous.single;
this.extra = extra;
} else {
VersionNumber ver = new VersionNumber(version);
if (previous.min == null || ver.isOlderThan(previous.min)) {
this.min = ver;
} else {
this.min = previous.min;
}
if (previous.max == null || ver.isNewerThan(previous.max)) {
this.max = ver;
} else {
this.max = previous.max;
}
this.single = this.max.isNewerThan(this.min);
this.extra = extra;
}
}
@Override
public String toString() {
return min==null ? "" : min.toString() + (single ? "" : " - " + max.toString());
}
/**
* Does this version range contain a version more than the given number of releases ago?
* @param threshold Number of releases
* @return True if the major version# differs or the minor# differs by >= threshold
*/
public boolean isOld(int threshold) {
return currentVersion != null && min != null && (currentVersion.digit(0) > min.digit(0)
|| (currentVersion.digit(0) == min.digit(0)
&& currentVersion.digit(1) - min.digit(1) >= threshold));
}
}
/**
* Sorted list of unique max-versions in the data set. For select list in jelly.
*/
@Restricted(NoExternalUse.class)
public Iterator<VersionNumber> getVersionList() {
TreeSet<VersionNumber> set = new TreeSet<VersionNumber>();
for (VersionRange vr : data.values()) {
if (vr.max != null) {
set.add(vr.max);
}
}
return set.iterator();
}
/**
* Depending on whether the user said "yes" or "no", send him to the right place.
*/
@RequirePOST
public HttpResponse doAct(StaplerRequest req, StaplerResponse rsp) throws IOException {
if (req.hasParameter("no")) {
disable(true);
return HttpResponses.redirectViaContextPath("/manage");
} else {
return new HttpRedirect("manage");
}
}
/**
* Save all or some of the files to persist data in the new forms.
* Remove those items from the data map.
*/
@RequirePOST
public HttpResponse doUpgrade(StaplerRequest req, StaplerResponse rsp) {
final String thruVerParam = req.getParameter("thruVer");
final VersionNumber thruVer = thruVerParam.equals("all") ? null : new VersionNumber(thruVerParam);
saveAndRemoveEntries(new Predicate<Map.Entry<SaveableReference, VersionRange>>() {
@Override
public boolean apply(Map.Entry<SaveableReference, VersionRange> entry) {
VersionNumber version = entry.getValue().max;
return version != null && (thruVer == null || !version.isNewerThan(thruVer));
}
});
return HttpResponses.forwardToPreviousPage();
}
/**
* Save all files containing only unreadable data (no data upgrades), which discards this data.
* Remove those items from the data map.
*/
@RequirePOST
public HttpResponse doDiscard(StaplerRequest req, StaplerResponse rsp) {
saveAndRemoveEntries( new Predicate<Map.Entry<SaveableReference,VersionRange>>() {
@Override
public boolean apply(Map.Entry<SaveableReference, VersionRange> entry) {
return entry.getValue().max == null;
}
});
return HttpResponses.forwardToPreviousPage();
}
private void saveAndRemoveEntries(Predicate<Map.Entry<SaveableReference, VersionRange>> matchingPredicate) {
/*
* Note that there a race condition here: we acquire the lock and get localCopy which includes some
* project (say); then we go through our loop and save that project; then someone POSTs a new
* config.xml for the project with some old data, causing remove to be called and the project to be
* added to data (in the new version); then we hit the end of this method and the project is removed
* from data again, even though it again has old data.
*
* In practice this condition is extremely unlikely, and not a major problem even if it
* does occur: just means the user will be prompted to discard less than they should have been (and
* would see the warning again after next restart).
*/
List<SaveableReference> removed = new ArrayList<SaveableReference>();
for (Map.Entry<SaveableReference,VersionRange> entry : data.entrySet()) {
if (matchingPredicate.apply(entry)) {
Saveable s = entry.getKey().get();
if (s != null) {
try {
s.save();
} catch (Exception x) {
LOGGER.log(Level.WARNING, "failed to save " + s, x);
}
}
removed.add(entry.getKey());
}
}
data.keySet().removeAll(removed);
}
public HttpResponse doIndex(StaplerResponse rsp) throws IOException {
return new HttpRedirect("manage");
}
/** Reference to a saveable object that need not actually hold it in heap. */
private interface SaveableReference {
@CheckForNull Saveable get();
// must also define equals, hashCode
}
private static SaveableReference referTo(Saveable s) {
if (s instanceof Run) {
Job parent = ((Run) s).getParent();
if (Jenkins.getInstance().getItemByFullName(parent.getFullName()) == parent) {
return new RunSaveableReference((Run) s);
}
}
return new SimpleSaveableReference(s);
}
private static final class SimpleSaveableReference implements SaveableReference {
private final Saveable instance;
SimpleSaveableReference(Saveable instance) {
this.instance = instance;
}
@Override public Saveable get() {
return instance;
}
@Override public int hashCode() {
return instance.hashCode();
}
@Override public boolean equals(Object obj) {
return obj instanceof SimpleSaveableReference && instance.equals(((SimpleSaveableReference) obj).instance);
}
}
// could easily make an ItemSaveableReference, but Jenkins holds all these strongly, so why bother
private static final class RunSaveableReference implements SaveableReference {
private final String id;
RunSaveableReference(Run<?,?> r) {
id = r.getExternalizableId();
}
@Override public Saveable get() {
try {
return Run.fromExternalizableId(id);
} catch (IllegalArgumentException x) {
// Typically meaning the job or build was since deleted.
LOGGER.log(Level.FINE, null, x);
return null;
}
}
@Override public int hashCode() {
return id.hashCode();
}
@Override public boolean equals(Object obj) {
return obj instanceof RunSaveableReference && id.equals(((RunSaveableReference) obj).id);
}
}
@Extension
public static class ManagementLinkImpl extends ManagementLink {
@Override
public String getIconFileName() {
return "document.png";
}
@Override
public String getUrlName() {
return "administrativeMonitor/OldData/";
}
@Override
public String getDescription() {
return Messages.OldDataMonitor_Description();
}
public String getDisplayName() {
return Messages.OldDataMonitor_DisplayName();
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_3052_1 |
crossvul-java_data_good_2029_1 | package io.hawt.web.plugin.karaf.terminal;
import io.hawt.system.ConfigManager;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* @author Stan Lewis
*/
public class KarafTerminalContextListener implements ServletContextListener {
private ConfigManager configManager = new ConfigManager();
@Override
public void contextInitialized(ServletContextEvent sce) {
try {
configManager.init();
} catch (Exception e) {
throw createServletException(e);
}
sce.getServletContext().setAttribute("ConfigManager", configManager);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
try {
configManager.destroy();
} catch (Exception e) {
throw createServletException(e);
}
}
protected RuntimeException createServletException(Exception e) {
return new RuntimeException(e);
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_2029_1 |
crossvul-java_data_good_4521_0 | /**
* 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.kernel.security;
import org.opencastproject.security.api.JaxbOrganization;
import org.opencastproject.security.api.JaxbRole;
import org.opencastproject.security.api.JaxbUser;
import org.opencastproject.security.api.Organization;
import org.opencastproject.security.api.SecurityService;
import org.opencastproject.security.api.User;
import org.opencastproject.security.api.UserDirectoryService;
import org.opencastproject.security.util.SecurityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* A Spring Security implementation of {@link SecurityService}.
*/
public class SecurityServiceSpringImpl implements SecurityService {
/** The logger */
private static final Logger logger = LoggerFactory.getLogger(SecurityServiceSpringImpl.class);
/** Holds delegates users for new threads that have been spawned from authenticated threads */
private static final ThreadLocal<User> delegatedUserHolder = new ThreadLocal<User>();
/** Holds the IP address for the delegated user for the current thread */
private static final ThreadLocal<String> delegatedUserIPHolder = new ThreadLocal<String>();
/** Holds organization responsible for the current thread */
private static final ThreadLocal<Organization> organization = new ThreadLocal<Organization>();
/** The user directory */
private UserDirectoryService userDirectory;
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.SecurityService#getOrganization()
*/
@Override
public Organization getOrganization() {
return SecurityServiceSpringImpl.organization.get();
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.SecurityService#setOrganization(Organization)
*/
@Override
public void setOrganization(Organization organization) {
SecurityServiceSpringImpl.organization.set(organization);
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.SecurityService#getUser()
*/
@Override
public User getUser() throws IllegalStateException {
Organization org = getOrganization();
if (org == null)
throw new IllegalStateException("No organization is set in security context");
User delegatedUser = delegatedUserHolder.get();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth instanceof AnonymousAuthenticationToken) {
return SecurityUtil.createAnonymousUser(org);
}
if (delegatedUser != null) {
return delegatedUser;
}
JaxbOrganization jaxbOrganization = JaxbOrganization.fromOrganization(org);
if (auth != null) {
Object principal = auth.getPrincipal();
if ((principal instanceof UserDetails)) {
UserDetails userDetails = (UserDetails) principal;
User user = null;
// If user exists, fetch it from the userDirectory
if (userDirectory != null) {
user = userDirectory.loadUser(userDetails.getUsername());
if (user == null) {
logger.debug("Authenticated user '{}' could not be found in any of the current UserProviders. "
+ "Continuing anyway...", userDetails.getUsername());
}
} else {
logger.debug("No UserDirectory was found when trying to search for user '{}'", userDetails.getUsername());
}
// Add the roles (authorities) in the security context
Set<JaxbRole> roles = new HashSet<>();
Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
if (authorities != null) {
for (GrantedAuthority ga : authorities) {
roles.add(new JaxbRole(ga.getAuthority(), jaxbOrganization));
}
}
if (user == null) {
// No user was found. Create one to hold the auth information from the security context
user = new JaxbUser(userDetails.getUsername(), null, jaxbOrganization, roles);
} else {
// Combine the existing user with the roles in the security context
user = JaxbUser.fromUser(user, roles);
}
// Save the user to retrieve it quicker the next time(s) this method is called (by this thread)
delegatedUserHolder.set(user);
return user;
}
}
// Return the anonymous user by default
return SecurityUtil.createAnonymousUser(jaxbOrganization);
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.SecurityService#setUser(User)
*/
@Override
public void setUser(User user) {
delegatedUserHolder.set(user);
}
@Override
public String getUserIP() {
return delegatedUserIPHolder.get();
}
@Override
public void setUserIP(String userIP) {
delegatedUserIPHolder.set(userIP);
}
/**
* OSGi callback for setting the user directory.
*
* @param userDirectory
* the user directory
*/
void setUserDirectory(UserDirectoryService userDirectory) {
this.userDirectory = userDirectory;
}
/**
* OSGi callback for removing the user directory.
*/
void removeUserDirectory() {
this.userDirectory = null;
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_4521_0 |
crossvul-java_data_bad_3052_0 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc.
*
* 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.diagnosis;
import hudson.model.AdministrativeMonitor;
import jenkins.model.Jenkins;
import hudson.model.AbstractModelObject;
import hudson.Extension;
import hudson.ExtensionPoint;
import hudson.ExtensionList;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import java.io.IOException;
import java.util.List;
/**
* Monitors the disk usage of <tt>JENKINS_HOME</tt>, and if it's almost filled up, warn the user.
*
* @author Kohsuke Kawaguchi
*/
@Extension
public final class HudsonHomeDiskUsageMonitor extends AdministrativeMonitor {
/**
* Value updated by {@link HudsonHomeDiskUsageChecker}.
*/
/*package*/ boolean activated;
public HudsonHomeDiskUsageMonitor() {
super("hudsonHomeIsFull");
}
public boolean isActivated() {
return activated;
}
@Override
public String getDisplayName() {
return Messages.HudsonHomeDiskUsageMonitor_DisplayName();
}
/**
* Depending on whether the user said "yes" or "no", send him to the right place.
*/
public HttpResponse doAct(@QueryParameter String no) throws IOException {
if(no!=null) {
disable(true);
return HttpResponses.redirectViaContextPath("/manage");
} else {
return HttpResponses.redirectToDot();
}
}
public List<Solution> getSolutions() {
return Solution.all();
}
/**
* Binds a solution to the URL.
*/
public Solution getSolution(String id) {
for( Solution s : Solution.all() )
if(s.id.equals(id))
return s;
return null;
}
/**
* Short cut for getting the singleton instance.
*/
public static HudsonHomeDiskUsageMonitor get() {
return all().get(HudsonHomeDiskUsageMonitor.class);
}
/**
* Extension point for suggesting solutions for full JENKINS_HOME.
*
* <h3>Views</h3>
* <dl>
* <dt>message.jelly</dt>
* <dd>
* This view is rendered inside an LI tag as a possible solution to the full JENKINS_HOME problem.
* </dd>
* </dl>
*/
public static abstract class Solution extends AbstractModelObject implements ExtensionPoint {
/**
* Human-readable ID of this monitor, which needs to be unique within the system.
*
* <p>
* This ID is used to remember persisted setting for this monitor,
* so the ID should remain consistent beyond the Hudson JVM lifespan.
*/
public final String id;
protected Solution(String id) {
this.id = id;
}
protected Solution() {
this.id = this.getClass().getName();
}
/**
* Returns the URL of this monitor, relative to the context path.
*/
public String getUrl() {
return HudsonHomeDiskUsageMonitor.get().getUrl()+"/solution/"+id;
}
/**
* All registered {@link Solution}s.
*/
public static ExtensionList<Solution> all() {
return ExtensionList.lookup(Solution.class);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/bad_3052_0 |
crossvul-java_data_bad_3052_2 | /*
* The MIT License
*
* Copyright (c) 2010, InfraDNA, Inc.
*
* 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.diagnosis;
import hudson.Extension;
import hudson.Util;
import hudson.model.AdministrativeMonitor;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.Stapler;
/**
* Looks out for a broken reverse proxy setup that doesn't rewrite the location header correctly.
*
* <p>
* Have the JavaScript make an AJAX call, to which we respond with 302 redirect. If the reverse proxy
* is done correctly, this will be handled by {@link #doFoo()}, but otherwise we'll report that as an error.
* Unfortunately, {@code XmlHttpRequest} doesn't expose properties that allow the client-side JavaScript
* to learn the details of the failure, so we have to make do with limited information.
*
* @author Kohsuke Kawaguchi
*/
@Extension
public class ReverseProxySetupMonitor extends AdministrativeMonitor {
private static final Logger LOGGER = Logger.getLogger(ReverseProxySetupMonitor.class.getName());
@Override
public boolean isActivated() {
// return true to always inject an HTML fragment to perform a test
return true;
}
public HttpResponse doTest() {
String referer = Stapler.getCurrentRequest().getReferer();
Jenkins j = Jenkins.getInstance();
assert j != null;
// May need to send an absolute URL, since handling of HttpRedirect with a relative URL does not currently honor X-Forwarded-Proto/Port at all.
String redirect = j.getRootUrl() + "administrativeMonitor/" + id + "/testForReverseProxySetup/" + (referer != null ? Util.rawEncode(referer) : "NO-REFERER") + "/";
LOGGER.log(Level.FINE, "coming from {0} and redirecting to {1}", new Object[] {referer, redirect});
return new HttpRedirect(redirect);
}
public void getTestForReverseProxySetup(String rest) {
Jenkins j = Jenkins.getInstance();
assert j != null;
String inferred = j.getRootUrlFromRequest() + "manage";
// TODO this could also verify that j.getRootUrl() has been properly configured, and send a different message if not
if (rest.startsWith(inferred)) { // not using equals due to JENKINS-24014
throw HttpResponses.ok();
} else {
LOGGER.log(Level.WARNING, "{0} vs. {1}", new Object[] {inferred, rest});
throw HttpResponses.errorWithoutStack(404, inferred + " vs. " + rest);
}
}
/**
* Depending on whether the user said "yes" or "no", send him to the right place.
*/
public HttpResponse doAct(@QueryParameter String no) throws IOException {
if(no!=null) { // dismiss
disable(true);
// of course the irony is that this redirect won't work
return HttpResponses.redirectViaContextPath("/manage");
} else {
return new HttpRedirect("https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+says+my+reverse+proxy+setup+is+broken");
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/bad_3052_2 |
crossvul-java_data_bad_2029_2 | package io.hawt.web.plugin.karaf.terminal;
import org.apache.felix.service.command.CommandProcessor;
import org.apache.felix.service.command.CommandSession;
import org.apache.felix.service.threadio.ThreadIO;
import org.apache.karaf.shell.console.jline.Console;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Constructor;
import java.util.zip.GZIPOutputStream;
/**
*
*/
public class TerminalServlet extends HttpServlet {
public static final int TERM_WIDTH = 120;
public static final int TERM_HEIGHT = 39;
private final static Logger LOG = LoggerFactory.getLogger(TerminalServlet.class);
/**
* Pseudo class version ID to keep the IDE quite.
*/
private static final long serialVersionUID = 1L;
public CommandProcessor getCommandProcessor() {
return CommandProcessorHolder.getCommandProcessor();
}
public ThreadIO getThreadIO() {
return ThreadIOHolder.getThreadIO();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String encoding = request.getHeader("Accept-Encoding");
boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1);
SessionTerminal st = (SessionTerminal) request.getSession(true).getAttribute("terminal");
if (st == null || st.isClosed()) {
st = new SessionTerminal(getCommandProcessor(), getThreadIO());
request.getSession().setAttribute("terminal", st);
}
String str = request.getParameter("k");
String f = request.getParameter("f");
String dump = st.handle(str, f != null && f.length() > 0);
if (dump != null) {
if (supportsGzip) {
response.setHeader("Content-Encoding", "gzip");
response.setHeader("Content-Type", "text/html");
try {
GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
gzos.write(dump.getBytes());
gzos.close();
} catch (IOException ie) {
LOG.info("Exception writing response: ", ie);
}
} else {
response.getOutputStream().write(dump.getBytes());
}
}
}
public class SessionTerminal implements Runnable {
private Terminal terminal;
private Console console;
private PipedOutputStream in;
private PipedInputStream out;
private boolean closed;
public SessionTerminal(CommandProcessor commandProcessor, ThreadIO threadIO) throws IOException {
try {
this.terminal = new Terminal(TERM_WIDTH, TERM_HEIGHT);
terminal.write("\u001b\u005B20\u0068"); // set newline mode on
in = new PipedOutputStream();
out = new PipedInputStream();
PrintStream pipedOut = new PrintStream(new PipedOutputStream(out), true);
Constructor ctr = Console.class.getConstructors()[0];
if (ctr.getParameterTypes().length <= 7) {
LOG.debug("Using old Karaf Console API");
// the old API does not have the threadIO parameter, so its only 7 parameters
console = (Console) ctr.newInstance(commandProcessor,
new PipedInputStream(in),
pipedOut,
pipedOut,
new WebTerminal(TERM_WIDTH, TERM_HEIGHT),
null,
null);
} else {
LOG.debug("Using new Karaf Console API");
// use the new api directly which we compile against
console = new Console(commandProcessor,
threadIO,
new PipedInputStream(in),
pipedOut,
pipedOut,
new WebTerminal(TERM_WIDTH, TERM_HEIGHT),
null,
null);
}
CommandSession session = console.getSession();
session.put("APPLICATION", System.getProperty("karaf.name", "root"));
session.put("USER", "karaf");
session.put("COLUMNS", Integer.toString(TERM_WIDTH));
session.put("LINES", Integer.toString(TERM_HEIGHT));
} catch (IOException e) {
LOG.info("Exception attaching to console", e);
throw e;
} catch (Exception e) {
LOG.info("Exception attaching to console", e);
throw (IOException) new IOException().initCause(e);
}
new Thread(console).start();
new Thread(this).start();
}
public boolean isClosed() {
return closed;
}
public String handle(String str, boolean forceDump) throws IOException {
try {
if (str != null && str.length() > 0) {
String d = terminal.pipe(str);
for (byte b : d.getBytes()) {
in.write(b);
}
in.flush();
}
} catch (IOException e) {
closed = true;
throw e;
}
try {
return terminal.dump(10, forceDump);
} catch (InterruptedException e) {
throw new InterruptedIOException(e.toString());
}
}
public void run() {
try {
for (; ; ) {
byte[] buf = new byte[8192];
int l = out.read(buf);
InputStreamReader r = new InputStreamReader(new ByteArrayInputStream(buf, 0, l));
StringBuilder sb = new StringBuilder();
for (; ; ) {
int c = r.read();
if (c == -1) {
break;
}
sb.append((char) c);
}
if (sb.length() > 0) {
terminal.write(sb.toString());
}
String s = terminal.read();
if (s != null && s.length() > 0) {
for (byte b : s.getBytes()) {
in.write(b);
}
}
}
} catch (IOException e) {
closed = true;
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/bad_2029_2 |
crossvul-java_data_good_3052_11 | package hudson.diagnosis;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import hudson.model.User;
import hudson.security.GlobalMatrixAuthorizationStrategy;
import hudson.security.HudsonPrivateSecurityRealm;
import hudson.security.Permission;
import jenkins.model.Jenkins;
import org.acegisecurity.context.SecurityContextHolder;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.xml.sax.SAXException;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import java.io.IOException;
import java.util.Collections;
/**
* @author Kohsuke Kawaguchi
*/
public class HudsonHomeDiskUsageMonitorTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Test
public void flow() throws Exception {
// manually activate this
HudsonHomeDiskUsageMonitor mon = HudsonHomeDiskUsageMonitor.get();
mon.activated = true;
// clicking yes should take us to somewhere
j.submit(getForm(mon), "yes");
assertTrue(mon.isEnabled());
// now dismiss
// submit(getForm(mon),"no"); TODO: figure out why this test is fragile
mon.doAct("no");
assertFalse(mon.isEnabled());
// and make sure it's gone
try {
fail(getForm(mon)+" shouldn't be there");
} catch (ElementNotFoundException e) {
// as expected
}
}
@Issue("SECURITY-371")
@Test
public void noAccessForNonAdmin() throws Exception {
JenkinsRule.WebClient wc = j.createWebClient();
// TODO: Use MockAuthorizationStrategy in later versions
JenkinsRule.DummySecurityRealm realm = j.createDummySecurityRealm();
realm.addGroups("administrator", "admins");
realm.addGroups("bob", "users");
j.jenkins.setSecurityRealm(realm);
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
auth.add(Jenkins.ADMINISTER, "admins");
auth.add(Jenkins.READ, "users");
j.jenkins.setAuthorizationStrategy(auth);
WebRequest request = new WebRequest(wc.createCrumbedUrl("administrativeMonitor/hudsonHomeIsFull/act"), HttpMethod.POST);
NameValuePair param = new NameValuePair("no", "true");
request.setRequestParameters(Collections.singletonList(param));
HudsonHomeDiskUsageMonitor mon = HudsonHomeDiskUsageMonitor.get();
try {
wc.login("bob");
wc.getPage(request);
} catch (FailingHttpStatusCodeException e) {
assertEquals(403, e.getStatusCode());
}
assertTrue(mon.isEnabled());
try {
WebRequest getIndex = new WebRequest(wc.createCrumbedUrl("administrativeMonitor/hudsonHomeIsFull"), HttpMethod.GET);
wc.getPage(getIndex);
} catch (FailingHttpStatusCodeException e) {
assertEquals(403, e.getStatusCode());
}
wc.login("administrator");
wc.getPage(request);
assertFalse(mon.isEnabled());
}
/**
* Gets the warning form.
*/
private HtmlForm getForm(HudsonHomeDiskUsageMonitor mon) throws IOException, SAXException {
HtmlPage p = j.createWebClient().goTo("manage");
return p.getFormByName(mon.id);
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_3052_11 |
crossvul-java_data_good_3052_5 | package jenkins.diagnostics;
import hudson.Extension;
import hudson.model.AdministrativeMonitor;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.interceptor.RequirePOST;
import java.io.IOException;
/**
* Unsecured Jenkins is, well, insecure.
*
* <p>
* Call attention to the fact that Jenkins is not secured, and encourage the administrator
* to take an action.
*
* @author Kohsuke Kawaguchi
*/
@Extension
public class SecurityIsOffMonitor extends AdministrativeMonitor {
@Override
public boolean isActivated() {
return !Jenkins.getInstance().isUseSecurity();
}
/**
* Depending on whether the user said "yes" or "no", send him to the right place.
*/
@RequirePOST
public void doAct(StaplerRequest req, StaplerResponse rsp) throws IOException {
if(req.hasParameter("no")) {
disable(true);
rsp.sendRedirect(req.getContextPath()+"/manage");
} else {
rsp.sendRedirect(req.getContextPath()+"/configureSecurity");
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_3052_5 |
crossvul-java_data_good_3052_3 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc.
*
* 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.diagnosis;
import hudson.model.AdministrativeMonitor;
import jenkins.model.Jenkins;
import hudson.Extension;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.interceptor.RequirePOST;
import java.io.IOException;
/**
* If Hudson is run with a lot of jobs but no views, suggest the user that they can create views.
*
* <p>
* I noticed at an user visit that some users didn't notice the '+' icon in the tab bar.
*
* @author Kohsuke Kawaguchi
*/
@Extension
public class TooManyJobsButNoView extends AdministrativeMonitor {
public boolean isActivated() {
Jenkins h = Jenkins.getInstance();
return h.getViews().size()==1 && h.getItemMap().size()> THRESHOLD;
}
/**
* Depending on whether the user said "yes" or "no", send him to the right place.
*/
@RequirePOST
public void doAct(StaplerRequest req, StaplerResponse rsp) throws IOException {
if(req.hasParameter("no")) {
disable(true);
rsp.sendRedirect(req.getContextPath()+"/manage");
} else {
rsp.sendRedirect(req.getContextPath()+"/newView");
}
}
public static final int THRESHOLD = 16;
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_3052_3 |
crossvul-java_data_good_3052_0 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc.
*
* 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.diagnosis;
import hudson.model.AdministrativeMonitor;
import hudson.model.AbstractModelObject;
import hudson.Extension;
import hudson.ExtensionPoint;
import hudson.ExtensionList;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.interceptor.RequirePOST;
import java.io.IOException;
import java.util.List;
/**
* Monitors the disk usage of <tt>JENKINS_HOME</tt>, and if it's almost filled up, warn the user.
*
* @author Kohsuke Kawaguchi
*/
@Extension
public final class HudsonHomeDiskUsageMonitor extends AdministrativeMonitor {
/**
* Value updated by {@link HudsonHomeDiskUsageChecker}.
*/
/*package*/ boolean activated;
public HudsonHomeDiskUsageMonitor() {
super("hudsonHomeIsFull");
}
public boolean isActivated() {
return activated;
}
@Override
public String getDisplayName() {
return Messages.HudsonHomeDiskUsageMonitor_DisplayName();
}
/**
* Depending on whether the user said "yes" or "no", send him to the right place.
*/
@RequirePOST
public HttpResponse doAct(@QueryParameter String no) throws IOException {
if(no!=null) {
disable(true);
return HttpResponses.redirectViaContextPath("/manage");
} else {
return HttpResponses.redirectToDot();
}
}
public List<Solution> getSolutions() {
return Solution.all();
}
/**
* Binds a solution to the URL.
*/
public Solution getSolution(String id) {
for( Solution s : Solution.all() )
if(s.id.equals(id))
return s;
return null;
}
/**
* Short cut for getting the singleton instance.
*/
public static HudsonHomeDiskUsageMonitor get() {
return all().get(HudsonHomeDiskUsageMonitor.class);
}
/**
* Extension point for suggesting solutions for full JENKINS_HOME.
*
* <h3>Views</h3>
* <dl>
* <dt>message.jelly</dt>
* <dd>
* This view is rendered inside an LI tag as a possible solution to the full JENKINS_HOME problem.
* </dd>
* </dl>
*/
public static abstract class Solution extends AbstractModelObject implements ExtensionPoint {
/**
* Human-readable ID of this monitor, which needs to be unique within the system.
*
* <p>
* This ID is used to remember persisted setting for this monitor,
* so the ID should remain consistent beyond the Hudson JVM lifespan.
*/
public final String id;
protected Solution(String id) {
this.id = id;
}
protected Solution() {
this.id = this.getClass().getName();
}
/**
* Returns the URL of this monitor, relative to the context path.
*/
public String getUrl() {
return HudsonHomeDiskUsageMonitor.get().getUrl()+"/solution/"+id;
}
/**
* All registered {@link Solution}s.
*/
public static ExtensionList<Solution> all() {
return ExtensionList.lookup(Solution.class);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/good_3052_0 |
crossvul-java_data_bad_3052_3 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc.
*
* 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.diagnosis;
import hudson.model.AdministrativeMonitor;
import jenkins.model.Jenkins;
import hudson.Extension;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import java.io.IOException;
/**
* If Hudson is run with a lot of jobs but no views, suggest the user that they can create views.
*
* <p>
* I noticed at an user visit that some users didn't notice the '+' icon in the tab bar.
*
* @author Kohsuke Kawaguchi
*/
@Extension
public class TooManyJobsButNoView extends AdministrativeMonitor {
public boolean isActivated() {
Jenkins h = Jenkins.getInstance();
return h.getViews().size()==1 && h.getItemMap().size()> THRESHOLD;
}
/**
* Depending on whether the user said "yes" or "no", send him to the right place.
*/
public void doAct(StaplerRequest req, StaplerResponse rsp) throws IOException {
if(req.hasParameter("no")) {
disable(true);
rsp.sendRedirect(req.getContextPath()+"/manage");
} else {
rsp.sendRedirect(req.getContextPath()+"/newView");
}
}
public static final int THRESHOLD = 16;
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/bad_3052_3 |
crossvul-java_data_bad_4521_0 | /**
* 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.kernel.security;
import org.opencastproject.security.api.JaxbOrganization;
import org.opencastproject.security.api.JaxbRole;
import org.opencastproject.security.api.JaxbUser;
import org.opencastproject.security.api.Organization;
import org.opencastproject.security.api.SecurityService;
import org.opencastproject.security.api.User;
import org.opencastproject.security.api.UserDirectoryService;
import org.opencastproject.security.util.SecurityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* A Spring Security implementation of {@link SecurityService}.
*/
public class SecurityServiceSpringImpl implements SecurityService {
/** The logger */
private static final Logger logger = LoggerFactory.getLogger(SecurityServiceSpringImpl.class);
/** Holds delegates users for new threads that have been spawned from authenticated threads */
private static final ThreadLocal<User> delegatedUserHolder = new ThreadLocal<User>();
/** Holds the IP address for the delegated user for the current thread */
private static final ThreadLocal<String> delegatedUserIPHolder = new ThreadLocal<String>();
/** Holds organization responsible for the current thread */
private static final ThreadLocal<Organization> organization = new ThreadLocal<Organization>();
/** The user directory */
private UserDirectoryService userDirectory;
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.SecurityService#getOrganization()
*/
@Override
public Organization getOrganization() {
return SecurityServiceSpringImpl.organization.get();
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.SecurityService#setOrganization(Organization)
*/
@Override
public void setOrganization(Organization organization) {
SecurityServiceSpringImpl.organization.set(organization);
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.SecurityService#getUser()
*/
@Override
public User getUser() throws IllegalStateException {
Organization org = getOrganization();
if (org == null)
throw new IllegalStateException("No organization is set in security context");
User delegatedUser = delegatedUserHolder.get();
if (delegatedUser != null) {
return delegatedUser;
}
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
JaxbOrganization jaxbOrganization = JaxbOrganization.fromOrganization(org);
if (auth != null) {
Object principal = auth.getPrincipal();
if ((principal != null) && (principal instanceof UserDetails)) {
UserDetails userDetails = (UserDetails) principal;
User user = null;
// If user exists, fetch it from the userDirectory
if (userDirectory != null) {
user = userDirectory.loadUser(userDetails.getUsername());
if (user == null) {
logger.debug(
"Authenticated user '{}' could not be found in any of the current UserProviders. Continuing anyway...",
userDetails.getUsername());
}
} else {
logger.debug("No UserDirectory was found when trying to search for user '{}'", userDetails.getUsername());
}
// Add the roles (authorities) in the security context
Set<JaxbRole> roles = new HashSet<JaxbRole>();
Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
if (authorities != null) {
for (GrantedAuthority ga : authorities) {
roles.add(new JaxbRole(ga.getAuthority(), jaxbOrganization));
}
}
if (user == null) {
// No user was found. Create one to hold the auth information from the security context
user = new JaxbUser(userDetails.getUsername(), null, jaxbOrganization, roles);
} else {
// Combine the existing user with the roles in the security context
user = JaxbUser.fromUser(user, roles);
}
// Save the user to retrieve it quicker the next time(s) this method is called (by this thread)
delegatedUserHolder.set(user);
return user;
}
}
// Return the anonymous user by default
return SecurityUtil.createAnonymousUser(jaxbOrganization);
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.SecurityService#setUser(User)
*/
@Override
public void setUser(User user) {
delegatedUserHolder.set(user);
}
@Override
public String getUserIP() {
return delegatedUserIPHolder.get();
}
@Override
public void setUserIP(String userIP) {
delegatedUserIPHolder.set(userIP);
}
/**
* OSGi callback for setting the user directory.
*
* @param userDirectory
* the user directory
*/
void setUserDirectory(UserDirectoryService userDirectory) {
this.userDirectory = userDirectory;
}
/**
* OSGi callback for removing the user directory.
*/
void removeUserDirectory() {
this.userDirectory = null;
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/bad_4521_0 |
crossvul-java_data_bad_3052_1 | /*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Alan Harder
*
* 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.diagnosis;
import com.google.common.base.Predicate;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import hudson.Extension;
import hudson.XmlFile;
import hudson.model.AdministrativeMonitor;
import hudson.model.Item;
import hudson.model.Job;
import hudson.model.ManagementLink;
import hudson.model.Run;
import hudson.model.Saveable;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.RunListener;
import hudson.model.listeners.SaveableListener;
import hudson.security.ACL;
import hudson.util.RobustReflectionConverter;
import hudson.util.VersionNumber;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import jenkins.model.Jenkins;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* Tracks whether any data structure changes were corrected when loading XML,
* that could be resaved to migrate that data to the new format.
*
* @author Alan.Harder@Sun.Com
*/
@Extension
public class OldDataMonitor extends AdministrativeMonitor {
private static final Logger LOGGER = Logger.getLogger(OldDataMonitor.class.getName());
private ConcurrentMap<SaveableReference,VersionRange> data = new ConcurrentHashMap<SaveableReference,VersionRange>();
static OldDataMonitor get(Jenkins j) {
return (OldDataMonitor) j.getAdministrativeMonitor("OldData");
}
public OldDataMonitor() {
super("OldData");
}
@Override
public String getDisplayName() {
return Messages.OldDataMonitor_DisplayName();
}
public boolean isActivated() {
return !data.isEmpty();
}
public Map<Saveable,VersionRange> getData() {
Map<Saveable,VersionRange> r = new HashMap<Saveable,VersionRange>();
for (Map.Entry<SaveableReference,VersionRange> entry : this.data.entrySet()) {
Saveable s = entry.getKey().get();
if (s != null) {
r.put(s, entry.getValue());
}
}
return r;
}
private static void remove(Saveable obj, boolean isDelete) {
Jenkins j = Jenkins.getInstance();
if (j != null) {
OldDataMonitor odm = get(j);
SecurityContext oldContext = ACL.impersonate(ACL.SYSTEM);
try {
odm.data.remove(referTo(obj));
if (isDelete && obj instanceof Job<?, ?>) {
for (Run r : ((Job<?, ?>) obj).getBuilds()) {
odm.data.remove(referTo(r));
}
}
} finally {
SecurityContextHolder.setContext(oldContext);
}
}
}
// Listeners to remove data here if resaved or deleted in regular Hudson usage
@Extension
public static final SaveableListener changeListener = new SaveableListener() {
@Override
public void onChange(Saveable obj, XmlFile file) {
remove(obj, false);
}
};
@Extension
public static final ItemListener itemDeleteListener = new ItemListener() {
@Override
public void onDeleted(Item item) {
remove(item, true);
}
};
@Extension
public static final RunListener<Run> runDeleteListener = new RunListener<Run>() {
@Override
public void onDeleted(Run run) {
remove(run, true);
}
};
/**
* Inform monitor that some data in a deprecated format has been loaded,
* and converted in-memory to a new structure.
* @param obj Saveable object; calling save() on this object will persist
* the data in its new format to disk.
* @param version Hudson release when the data structure changed.
*/
public static void report(Saveable obj, String version) {
OldDataMonitor odm = get(Jenkins.getInstance());
try {
SaveableReference ref = referTo(obj);
while (true) {
VersionRange vr = odm.data.get(ref);
if (vr != null && odm.data.replace(ref, vr, new VersionRange(vr, version, null))) {
break;
} else if (odm.data.putIfAbsent(ref, new VersionRange(null, version, null)) == null) {
break;
}
}
} catch (IllegalArgumentException ex) {
LOGGER.log(Level.WARNING, "Bad parameter given to OldDataMonitor", ex);
}
}
/**
* Inform monitor that some data in a deprecated format has been loaded, during
* XStream unmarshalling when the Saveable containing this object is not available.
* @param context XStream unmarshalling context
* @param version Hudson release when the data structure changed.
*/
public static void report(UnmarshallingContext context, String version) {
RobustReflectionConverter.addErrorInContext(context, new ReportException(version));
}
private static class ReportException extends Exception {
private String version;
private ReportException(String version) {
this.version = version;
}
}
/**
* Inform monitor that some unreadable data was found while loading.
* @param obj Saveable object; calling save() on this object will discard the unreadable data.
* @param errors Exception(s) thrown while loading, regarding the unreadable classes/fields.
*/
public static void report(Saveable obj, Collection<Throwable> errors) {
StringBuilder buf = new StringBuilder();
int i = 0;
for (Throwable e : errors) {
if (e instanceof ReportException) {
report(obj, ((ReportException)e).version);
} else {
if (++i > 1) buf.append(", ");
buf.append(e.getClass().getSimpleName()).append(": ").append(e.getMessage());
}
}
if (buf.length() == 0) return;
Jenkins j = Jenkins.getInstance();
if (j == null) {
// Startup failed, something is very broken, so report what we can.
for (Throwable t : errors) {
LOGGER.log(Level.WARNING, "could not read " + obj + " (and Jenkins did not start up)", t);
}
return;
}
OldDataMonitor odm = get(j);
SaveableReference ref = referTo(obj);
while (true) {
VersionRange vr = odm.data.get(ref);
if (vr != null && odm.data.replace(ref, vr, new VersionRange(vr, null, buf.toString()))) {
break;
} else if (odm.data.putIfAbsent(ref, new VersionRange(null, null, buf.toString())) == null) {
break;
}
}
}
public static class VersionRange {
private static VersionNumber currentVersion = Jenkins.getVersion();
final VersionNumber min;
final VersionNumber max;
final boolean single;
final public String extra;
public VersionRange(VersionRange previous, String version, String extra) {
if (previous == null) {
min = max = version != null ? new VersionNumber(version) : null;
this.single = true;
this.extra = extra;
} else if (version == null) {
min = previous.min;
max = previous.max;
single = previous.single;
this.extra = extra;
} else {
VersionNumber ver = new VersionNumber(version);
if (previous.min == null || ver.isOlderThan(previous.min)) {
this.min = ver;
} else {
this.min = previous.min;
}
if (previous.max == null || ver.isNewerThan(previous.max)) {
this.max = ver;
} else {
this.max = previous.max;
}
this.single = this.max.isNewerThan(this.min);
this.extra = extra;
}
}
@Override
public String toString() {
return min==null ? "" : min.toString() + (single ? "" : " - " + max.toString());
}
/**
* Does this version range contain a version more than the given number of releases ago?
* @param threshold Number of releases
* @return True if the major version# differs or the minor# differs by >= threshold
*/
public boolean isOld(int threshold) {
return currentVersion != null && min != null && (currentVersion.digit(0) > min.digit(0)
|| (currentVersion.digit(0) == min.digit(0)
&& currentVersion.digit(1) - min.digit(1) >= threshold));
}
}
/**
* Sorted list of unique max-versions in the data set. For select list in jelly.
*/
@Restricted(NoExternalUse.class)
public Iterator<VersionNumber> getVersionList() {
TreeSet<VersionNumber> set = new TreeSet<VersionNumber>();
for (VersionRange vr : data.values()) {
if (vr.max != null) {
set.add(vr.max);
}
}
return set.iterator();
}
/**
* Depending on whether the user said "yes" or "no", send him to the right place.
*/
@RequirePOST
public HttpResponse doAct(StaplerRequest req, StaplerResponse rsp) throws IOException {
if (req.hasParameter("no")) {
disable(true);
return HttpResponses.redirectViaContextPath("/manage");
} else {
return new HttpRedirect("manage");
}
}
/**
* Save all or some of the files to persist data in the new forms.
* Remove those items from the data map.
*/
@RequirePOST
public HttpResponse doUpgrade(StaplerRequest req, StaplerResponse rsp) {
final String thruVerParam = req.getParameter("thruVer");
final VersionNumber thruVer = thruVerParam.equals("all") ? null : new VersionNumber(thruVerParam);
saveAndRemoveEntries(new Predicate<Map.Entry<SaveableReference, VersionRange>>() {
@Override
public boolean apply(Map.Entry<SaveableReference, VersionRange> entry) {
VersionNumber version = entry.getValue().max;
return version != null && (thruVer == null || !version.isNewerThan(thruVer));
}
});
return HttpResponses.forwardToPreviousPage();
}
/**
* Save all files containing only unreadable data (no data upgrades), which discards this data.
* Remove those items from the data map.
*/
@RequirePOST
public HttpResponse doDiscard(StaplerRequest req, StaplerResponse rsp) {
saveAndRemoveEntries( new Predicate<Map.Entry<SaveableReference,VersionRange>>() {
@Override
public boolean apply(Map.Entry<SaveableReference, VersionRange> entry) {
return entry.getValue().max == null;
}
});
return HttpResponses.forwardToPreviousPage();
}
private void saveAndRemoveEntries(Predicate<Map.Entry<SaveableReference, VersionRange>> matchingPredicate) {
/*
* Note that there a race condition here: we acquire the lock and get localCopy which includes some
* project (say); then we go through our loop and save that project; then someone POSTs a new
* config.xml for the project with some old data, causing remove to be called and the project to be
* added to data (in the new version); then we hit the end of this method and the project is removed
* from data again, even though it again has old data.
*
* In practice this condition is extremely unlikely, and not a major problem even if it
* does occur: just means the user will be prompted to discard less than they should have been (and
* would see the warning again after next restart).
*/
List<SaveableReference> removed = new ArrayList<SaveableReference>();
for (Map.Entry<SaveableReference,VersionRange> entry : data.entrySet()) {
if (matchingPredicate.apply(entry)) {
Saveable s = entry.getKey().get();
if (s != null) {
try {
s.save();
} catch (Exception x) {
LOGGER.log(Level.WARNING, "failed to save " + s, x);
}
}
removed.add(entry.getKey());
}
}
data.keySet().removeAll(removed);
}
public HttpResponse doIndex(StaplerResponse rsp) throws IOException {
return new HttpRedirect("manage");
}
/** Reference to a saveable object that need not actually hold it in heap. */
private interface SaveableReference {
@CheckForNull Saveable get();
// must also define equals, hashCode
}
private static SaveableReference referTo(Saveable s) {
if (s instanceof Run) {
Job parent = ((Run) s).getParent();
if (Jenkins.getInstance().getItemByFullName(parent.getFullName()) == parent) {
return new RunSaveableReference((Run) s);
}
}
return new SimpleSaveableReference(s);
}
private static final class SimpleSaveableReference implements SaveableReference {
private final Saveable instance;
SimpleSaveableReference(Saveable instance) {
this.instance = instance;
}
@Override public Saveable get() {
return instance;
}
@Override public int hashCode() {
return instance.hashCode();
}
@Override public boolean equals(Object obj) {
return obj instanceof SimpleSaveableReference && instance.equals(((SimpleSaveableReference) obj).instance);
}
}
// could easily make an ItemSaveableReference, but Jenkins holds all these strongly, so why bother
private static final class RunSaveableReference implements SaveableReference {
private final String id;
RunSaveableReference(Run<?,?> r) {
id = r.getExternalizableId();
}
@Override public Saveable get() {
try {
return Run.fromExternalizableId(id);
} catch (IllegalArgumentException x) {
// Typically meaning the job or build was since deleted.
LOGGER.log(Level.FINE, null, x);
return null;
}
}
@Override public int hashCode() {
return id.hashCode();
}
@Override public boolean equals(Object obj) {
return obj instanceof RunSaveableReference && id.equals(((RunSaveableReference) obj).id);
}
}
@Extension
public static class ManagementLinkImpl extends ManagementLink {
@Override
public String getIconFileName() {
return "document.png";
}
@Override
public String getUrlName() {
return "administrativeMonitor/OldData/";
}
@Override
public String getDescription() {
return Messages.OldDataMonitor_Description();
}
public String getDisplayName() {
return Messages.OldDataMonitor_DisplayName();
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/bad_3052_1 |
crossvul-java_data_bad_3052_7 | package jenkins.security.s2m;
import hudson.Extension;
import hudson.FilePath;
import hudson.model.AdministrativeMonitor;
import hudson.remoting.Callable;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import javax.inject.Inject;
import java.io.IOException;
/**
* Report any rejected {@link Callable}s and {@link FilePath} executions and allow
* admins to whitelist them.
*
* @since 1.THU
* @author Kohsuke Kawaguchi
*/
@Extension
public class AdminCallableMonitor extends AdministrativeMonitor {
@Inject
Jenkins jenkins;
@Inject
AdminWhitelistRule rule;
public AdminCallableMonitor() {
super("slaveToMasterAccessControl");
}
@Override
public boolean isActivated() {
return !rule.rejected.describe().isEmpty();
}
@Override
public String getDisplayName() {
return "Slave \u2192 Master Access Control";
}
// bind this to URL
public AdminWhitelistRule getRule() {
return rule;
}
/**
* Depending on whether the user said "examin" or "dismiss", send him to the right place.
*/
public HttpResponse doAct(@QueryParameter String dismiss) throws IOException {
if(dismiss!=null) {
disable(true);
return HttpResponses.redirectViaContextPath("/manage");
} else {
return HttpResponses.redirectTo("rule/");
}
}
public HttpResponse doIndex() {
return HttpResponses.redirectTo("rule/");
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/bad_3052_7 |
crossvul-java_data_bad_2029_6 | package io.hawt.web;
import java.io.IOException;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import javax.security.auth.Subject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import io.hawt.system.Authenticator;
import io.hawt.system.ConfigManager;
import io.hawt.system.Helpers;
import io.hawt.system.PrivilegedCallback;
import io.hawt.web.tomcat.TomcatAuthenticationContainerDiscovery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Filter for authentication. If the filter is enabled, then the login screen is shown.
*/
public class AuthenticationFilter implements Filter {
private static final transient Logger LOG = LoggerFactory.getLogger(AuthenticationFilter.class);
// JVM system properties
public static final String HAWTIO_AUTHENTICATION_ENABLED = "hawtio.authenticationEnabled";
public static final String HAWTIO_REALM = "hawtio.realm";
public static final String HAWTIO_ROLE = "hawtio.role";
public static final String HAWTIO_ROLE_PRINCIPAL_CLASSES = "hawtio.rolePrincipalClasses";
private final AuthenticationConfiguration configuration = new AuthenticationConfiguration();
// add known SPI authentication container discovery
private final AuthenticationContainerDiscovery[] discoveries = new AuthenticationContainerDiscovery[]{
new TomcatAuthenticationContainerDiscovery()
};
@Override
public void init(FilterConfig filterConfig) throws ServletException {
ConfigManager config = (ConfigManager) filterConfig.getServletContext().getAttribute("ConfigManager");
if (config != null) {
configuration.setRealm(config.get("realm", "karaf"));
configuration.setRole(config.get("role", "admin"));
configuration.setRolePrincipalClasses(config.get("rolePrincipalClasses", ""));
configuration.setEnabled(Boolean.parseBoolean(config.get("authenticationEnabled", "true")));
}
// JVM system properties can override always
if (System.getProperty(HAWTIO_AUTHENTICATION_ENABLED) != null) {
configuration.setEnabled(Boolean.getBoolean(HAWTIO_AUTHENTICATION_ENABLED));
}
if (System.getProperty(HAWTIO_REALM) != null) {
configuration.setRealm(System.getProperty(HAWTIO_REALM));
}
if (System.getProperty(HAWTIO_ROLE) != null) {
configuration.setRole(System.getProperty(HAWTIO_ROLE));
}
if (System.getProperty(HAWTIO_ROLE_PRINCIPAL_CLASSES) != null) {
configuration.setRolePrincipalClasses(System.getProperty(HAWTIO_ROLE_PRINCIPAL_CLASSES));
}
if (configuration.isEnabled()) {
for (AuthenticationContainerDiscovery discovery : discoveries) {
if (discovery.canAuthenticate(configuration)) {
LOG.info("Discovered container {} to use with hawtio authentication filter", discovery.getContainerName());
break;
}
}
}
if (configuration.isEnabled()) {
LOG.info("Starting hawtio authentication filter, JAAS realm: \"{}\" authorized role: \"{}\" role principal classes: \"{}\"",
new Object[]{configuration.getRealm(), configuration.getRole(), configuration.getRolePrincipalClasses()});
} else {
LOG.info("Starting hawtio authentication filter, JAAS authentication disabled");
}
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String path = httpRequest.getServletPath();
LOG.debug("Handling request for path {}", path);
if (configuration.getRealm() == null || configuration.getRealm().equals("") || !configuration.isEnabled()) {
LOG.debug("No authentication needed for path {}", path);
chain.doFilter(request, response);
return;
}
HttpSession session = httpRequest.getSession(false);
if (session != null) {
Subject subject = (Subject) session.getAttribute("subject");
if (subject != null) {
LOG.debug("Session subject {}", subject);
executeAs(request, response, chain, subject);
return;
}
}
boolean doAuthenticate = path.startsWith("/auth") ||
path.startsWith("/jolokia") ||
path.startsWith("/upload");
if (doAuthenticate) {
LOG.debug("Doing authentication and authorization for path {}", path);
switch (Authenticator.authenticate(configuration.getRealm(), configuration.getRole(), configuration.getRolePrincipalClasses(),
configuration.getConfiguration(), httpRequest, new PrivilegedCallback() {
public void execute(Subject subject) throws Exception {
executeAs(request, response, chain, subject);
}
})) {
case AUTHORIZED:
// request was executed using the authenticated subject, nothing more to do
break;
case NOT_AUTHORIZED:
Helpers.doForbidden((HttpServletResponse) response);
break;
case NO_CREDENTIALS:
//doAuthPrompt((HttpServletResponse)response);
Helpers.doForbidden((HttpServletResponse) response);
break;
}
} else {
LOG.debug("No authentication needed for path {}", path);
chain.doFilter(request, response);
}
}
private static void executeAs(final ServletRequest request, final ServletResponse response, final FilterChain chain, Subject subject) {
try {
Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
chain.doFilter(request, response);
return null;
}
});
} catch (PrivilegedActionException e) {
LOG.info("Failed to invoke action " + ((HttpServletRequest) request).getPathInfo() + " due to:", e);
}
}
@Override
public void destroy() {
LOG.info("Destroying hawtio authentication filter");
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/java/bad_2029_6 |
crossvul-java_data_bad_4532_6 | /**
* 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.userdirectory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.opencastproject.util.data.Collections.set;
import static org.opencastproject.util.persistence.PersistenceUtil.newTestEntityManagerFactory;
import org.opencastproject.security.api.Role;
import org.opencastproject.security.api.SecurityConstants;
import org.opencastproject.security.api.SecurityService;
import org.opencastproject.security.api.UnauthorizedException;
import org.opencastproject.security.api.User;
import org.opencastproject.security.impl.jpa.JpaOrganization;
import org.opencastproject.security.impl.jpa.JpaRole;
import org.opencastproject.security.impl.jpa.JpaUser;
import org.opencastproject.util.NotFoundException;
import org.opencastproject.util.PasswordEncoder;
import org.opencastproject.util.data.Collections;
import org.apache.commons.collections4.IteratorUtils;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class JpaUserProviderTest {
private JpaUserAndRoleProvider provider = null;
private JpaOrganization org1 = null;
private JpaOrganization org2 = null;
@Before
public void setUp() throws Exception {
org1 = new JpaOrganization("org1", "org1", "localhost", 80, "admin", "anon", null);
org2 = new JpaOrganization("org2", "org2", "127.0.0.1", 80, "admin", "anon", null);
SecurityService securityService = mockSecurityServiceWithUser(
createUserWithRoles(org1, "admin", SecurityConstants.GLOBAL_SYSTEM_ROLES));
JpaGroupRoleProvider groupRoleProvider = EasyMock.createNiceMock(JpaGroupRoleProvider.class);
provider = new JpaUserAndRoleProvider();
provider.setSecurityService(securityService);
provider.setEntityManagerFactory(newTestEntityManagerFactory(JpaUserAndRoleProvider.PERSISTENCE_UNIT));
provider.setGroupRoleProvider(groupRoleProvider);
provider.activate(null);
}
@Test
public void testAddAndGetUser() throws Exception {
JpaUser user = createUserWithRoles(org1, "user1", "ROLE_ASTRO_101_SPRING_2011_STUDENT");
provider.addUser(user);
User loadUser = provider.loadUser("user1");
assertNotNull(loadUser);
assertEquals(user.getUsername(), loadUser.getUsername());
assertEquals(PasswordEncoder.encode(user.getPassword(), user.getUsername()), loadUser.getPassword());
assertEquals(user.getOrganization(), loadUser.getOrganization());
assertEquals(user.getRoles(), loadUser.getRoles());
assertNull("Loading 'does not exist' should return null", provider.loadUser("does not exist"));
assertNull("Loading 'does not exist' should return null", provider.loadUser("user1", org2.getId()));
loadUser = provider.loadUser("user1", org1.getId());
assertNotNull(loadUser);
assertEquals(user.getUsername(), loadUser.getUsername());
assertEquals(PasswordEncoder.encode(user.getPassword(), user.getUsername()), loadUser.getPassword());
assertEquals(user.getOrganization(), loadUser.getOrganization());
assertEquals(user.getRoles(), loadUser.getRoles());
}
@Test
public void testAddUserWithGlobalAdminRole() throws Exception {
JpaUser adminUser = createUserWithRoles(org1, "admin1", SecurityConstants.GLOBAL_ADMIN_ROLE);
provider.addUser(adminUser);
User loadedUser = provider.loadUser(adminUser.getUsername());
assertNotNull("The currently added user isn't loaded as expected", loadedUser);
assertEquals(adminUser.getUsername(), loadedUser.getUsername());
assertEquals(adminUser.getRoles(), loadedUser.getRoles());
}
@Test
public void testAddUserWithOrgAdminRoleAsGlobalAdmin() throws Exception {
JpaUser newUser = createUserWithRoles(org1, "org_admin2", org1.getAdminRole());
provider.addUser(newUser);
User loadedUser = provider.loadUser(newUser.getUsername());
assertNotNull("The currently added user isn't loaded as expected", loadedUser);
assertEquals(newUser.getUsername(), loadedUser.getUsername());
assertEquals(newUser.getRoles(), loadedUser.getRoles());
}
@Test
public void testAddUserWithOrgAdminRoleAsOrgAdmin() throws Exception {
provider.setSecurityService(mockSecurityServiceWithUser(
createUserWithRoles(org1, "org_admin", org1.getAdminRole())));
JpaUser newUser = createUserWithRoles(org1, "org_admin2", org1.getAdminRole());
provider.addUser(newUser);
User loadedUser = provider.loadUser(newUser.getUsername());
assertNotNull("The currently added user isn't loaded as expected", loadedUser);
assertEquals(newUser.getUsername(), loadedUser.getUsername());
assertEquals(newUser.getRoles(), loadedUser.getRoles());
}
@Test(expected = UnauthorizedException.class)
public void testAddUserWithGlobalAdminRoleNotAllowedAsNonAdminUser() throws Exception {
provider.setSecurityService(mockSecurityServiceWithUser(
createUserWithRoles(org1, "user1", "ROLE_USER")));
JpaUser newUser = createUserWithRoles(org1, "admin2", SecurityConstants.GLOBAL_ADMIN_ROLE);
provider.addUser(newUser);
fail("The current user shouldn't able to create an global admin user.");
}
@Test(expected = UnauthorizedException.class)
public void testAddUserWithGlobalAdminRoleNotAllowedAsOrgAdmin() throws Exception {
provider.setSecurityService(mockSecurityServiceWithUser(
createUserWithRoles(org1, "org1_admin", org1.getAdminRole())));
JpaUser newUser = createUserWithRoles(org1, "admin2", SecurityConstants.GLOBAL_ADMIN_ROLE);
provider.addUser(newUser);
fail("The current user shouldn't able to create an global admin user.");
}
@Test(expected = UnauthorizedException.class)
public void testAddUserWithOrgAdminRoleNotAllowedAsNonAdminUser() throws Exception {
provider.setSecurityService(mockSecurityServiceWithUser(
createUserWithRoles(org1, "user1", "ROLE_USER")));
JpaUser newUser = createUserWithRoles(org1, "org_admin2", org1.getAdminRole());
provider.addUser(newUser);
fail("The current user shouldn't able to create an global admin user.");
}
@Test
public void testDeleteUser() throws Exception {
JpaUser user1 = createUserWithRoles(org1, "user1", "ROLE_ASTRO_101_SPRING_2011_STUDENT");
JpaUser user2 = createUserWithRoles(org1, "user2", "ROLE_ASTRO_101_SPRING_2011_STUDENT");
JpaUser user3 = createUserWithRoles(org1, "user3", "ROLE_ASTRO_101_SPRING_2011_STUDENT");
JpaUser user4 = createUserWithRoles(org1, "user4", "ROLE_ASTRO_101_SPRING_2011_STUDENT");
provider.addUser(user1);
provider.addUser(user2);
provider.addUser(user3);
provider.addUser(user4);
User loadUser = provider.loadUser("user1");
assertNotNull(loadUser);
provider.deleteUser("user1", user1.getOrganization().getId());
provider.deleteUser("user2", user1.getOrganization().getId());
provider.deleteUser("user3", user1.getOrganization().getId());
assertNull(provider.loadUser("user1", org1.getId()));
assertNull(provider.loadUser("user2", org1.getId()));
assertNull(provider.loadUser("user3", org1.getId()));
assertNotNull(provider.loadUser("user4", org1.getId()));
try {
provider.deleteUser("user1", user1.getOrganization().getId());
fail("Should throw a NotFoundException");
} catch (NotFoundException e) {
assertTrue("User not found.", true);
}
}
@Test(expected = UnauthorizedException.class)
public void testDeleteUserNotAllowedAsNonAdmin() throws UnauthorizedException, Exception {
JpaUser adminUser = createUserWithRoles(org1, "admin", "ROLE_ADMIN");
JpaUser nonAdminUser = createUserWithRoles(org1, "user1", "ROLE_USER");
try {
provider.addUser(adminUser);
provider.addUser(nonAdminUser);
} catch (UnauthorizedException ex) {
fail("The user shuld be created");
}
provider.setSecurityService(mockSecurityServiceWithUser(nonAdminUser));
provider.deleteUser(adminUser.getUsername(), org1.getId());
fail("An non admin user may not delete an admin user");
}
@Test
public void testUpdateUser() throws Exception {
Set<JpaRole> authorities = new HashSet<JpaRole>();
authorities.add(new JpaRole("ROLE_ASTRO_101_SPRING_2011_STUDENT", org1));
JpaUser user = new JpaUser("user1", "pass1", org1, provider.getName(), true, authorities);
provider.addUser(user);
User loadUser = provider.loadUser("user1");
assertNotNull(loadUser);
authorities.add(new JpaRole("ROLE_ASTRO_101_SPRING_2013_STUDENT", org1));
String newPassword = "newPassword";
JpaUser updateUser = new JpaUser(user.getUsername(), newPassword, org1, provider.getName(), true, authorities);
User loadUpdatedUser = provider.updateUser(updateUser);
// User loadUpdatedUser = provider.loadUser(user.getUsername());
assertNotNull(loadUpdatedUser);
assertEquals(user.getUsername(), loadUpdatedUser.getUsername());
assertEquals(PasswordEncoder.encode(newPassword, user.getUsername()), loadUpdatedUser.getPassword());
assertEquals(authorities.size(), loadUpdatedUser.getRoles().size());
updateUser = new JpaUser("unknown", newPassword, org1, provider.getName(), true, authorities);
try {
provider.updateUser(updateUser);
fail("Should throw a NotFoundException");
} catch (NotFoundException e) {
assertTrue("User not found.", true);
}
}
@Test
public void testUpdateUserForbiddenForNonAdminUsers() throws Exception {
JpaUser adminUser = createUserWithRoles(org1, "admin", SecurityConstants.GLOBAL_ADMIN_ROLE);
JpaUser user = createUserWithRoles(org1, "user", "ROLE_USER");
provider.addUser(adminUser);
provider.addUser(user);
provider.setSecurityService(mockSecurityServiceWithUser(user));
// try to add ROLE_USER
Set<JpaRole> updatedRoles = Collections.set(
new JpaRole("ROLE_USER", org1),
new JpaRole(SecurityConstants.GLOBAL_ADMIN_ROLE, org1));
try {
provider.updateUser(new JpaUser(adminUser.getUsername(), adminUser.getPassword(), org1,
adminUser.getName(), true, updatedRoles));
fail("The current user may not edit an admin user");
} catch (UnauthorizedException e) {
// pass
}
// try to remove ROLE_ADMIN
updatedRoles = Collections.set(new JpaRole("ROLE_USER", org1));
try {
provider.updateUser(new JpaUser(adminUser.getUsername(), adminUser.getPassword(), org1,
adminUser.getName(), true, updatedRoles));
fail("The current user may not remove the admin role on other user");
} catch (UnauthorizedException e) {
// pass
}
}
@Test
public void testRoles() throws Exception {
JpaUser userOne = createUserWithRoles(org1, "user1", "ROLE_ONE");
provider.addUser(userOne);
Set<JpaRole> authoritiesTwo = new HashSet<JpaRole>();
authoritiesTwo.add(new JpaRole("ROLE_ONE", org1));
authoritiesTwo.add(new JpaRole("ROLE_TWO", org1));
JpaUser userTwo = createUserWithRoles(org1, "user2", "ROLE_ONE", "ROLE_TWO");
provider.addUser(userTwo);
// The provider is not authoritative for these roles
assertEquals("There should be no roles", 0, IteratorUtils.toList(provider.findRoles("%", Role.Target.ALL, 0, 0)).size());
}
@Test
public void testUsers() throws Exception {
Set<JpaRole> authorities = new HashSet<JpaRole>();
authorities.add(new JpaRole("ROLE_COOL_ONE", org1));
JpaUser userOne = createUserWithRoles(org1, "user_test_1", "ROLE_COOL_ONE");
JpaUser userTwo = createUserWithRoles(org1, "user2", "ROLE_CCOL_ONE");
JpaUser userThree = createUserWithRoles(org1, "user3", "ROLE_COOL_ONE");
JpaUser userFour = createUserWithRoles(org1, "user_test_4", "ROLE_COOL_ONE");
provider.addUser(userOne);
provider.addUser(userTwo);
provider.addUser(userThree);
provider.addUser(userFour);
assertEquals("There should be two roles", 4, IteratorUtils.toList(provider.getUsers()).size());
}
@Test
public void testDuplicateUser() {
Set<JpaRole> authorities1 = set(new JpaRole("ROLE_COOL_ONE", org1));
Set<JpaRole> authorities2 = set(new JpaRole("ROLE_COOL_ONE", org2));
try {
provider.addUser(createUserWithRoles(org1, "user1", "ROLE_COOL_ONE"));
provider.addUser(createUserWithRoles(org1, "user2", "ROLE_COOL_ONE"));
provider.addUser(createUserWithRoles(org2, "user1", "ROLE_COOL_ONE"));
} catch (UnauthorizedException e) {
fail("User should be created");
}
try {
provider.addUser(createUserWithRoles(org1, "user1", "ROLE_COOL_ONE"));
fail("Duplicate user");
} catch (Exception ignore) {
}
}
@Test
public void testRolesForUser() {
JpaRole astroRole = new JpaRole("ROLE_ASTRO_105_SPRING_2013_STUDENT", org1, "Astro role");
provider.addRole(astroRole);
JpaUser userOne = createUserWithRoles(org1, "user1", "ROLE_ONE", "ROLE_TWO");
try {
provider.addUser(userOne);
} catch (UnauthorizedException e) {
fail("User should be created");
}
// Provider not authoritative for these roles
assertEquals("There should be zero roles", 0, IteratorUtils.toList(provider.findRoles("%", Role.Target.ALL, 0, 0)).size());
List<String> rolesForUser = provider.getRolesForUser("user1").stream()
.map(Role::getName)
.sorted()
.collect(Collectors.toList());
assertEquals("There should be two roles", 2, rolesForUser.size());
assertEquals("ROLE_ONE", rolesForUser.get(0));
assertEquals("ROLE_TWO", rolesForUser.get(1));
}
@Test
public void testFindUsers() throws UnauthorizedException {
JpaUser userOne = createUserWithRoles(org1, "user_test_1", "ROLE_COOL_ONE");
JpaUser userTwo = createUserWithRoles(org1, "user2", "ROLE_COOL_ONE");
JpaUser userThree = createUserWithRoles(org1, "user3", "ROLE_COOL_ONE");
JpaUser userFour = createUserWithRoles(org1, "user_test_4", "ROLE_COOL_ONE");
provider.addUser(userOne);
provider.addUser(userTwo);
provider.addUser(userThree);
provider.addUser(userFour);
assertEquals(2, IteratorUtils.toList(provider.findUsers("%tEsT%", 0, 0)).size());
assertEquals(1, IteratorUtils.toList(provider.findUsers("%tEsT%", 0, 1)).size());
User user = provider.findUsers("%tEsT%", 1, 1).next();
assertEquals(userFour, user);
}
@Test
public void testFindRoles() throws UnauthorizedException {
JpaRole astroRole = new JpaRole("ROLE_ASTRO_105_SPRING_2013_STUDENT", org1, "Astro role");
provider.addRole(astroRole);
JpaUser userOne = createUserWithRoles(org1, "user1", "ROLE_COOL_ONE", "ROLE_COOL_TWO");
provider.addUser(userOne);
// We expect findRoles() for this provider to return an empty set,
// as it is not authoritative for roles that it persists.
assertEquals(0, IteratorUtils.toList(provider.findRoles("%coOL%", Role.Target.ALL, 0, 0)).size());
assertEquals(0, IteratorUtils.toList(provider.findRoles("%cOoL%", Role.Target.ALL, 0, 1)).size());
assertEquals(0, IteratorUtils.toList(provider.findRoles("%oLe%", Role.Target.ALL, 0, 0)).size());
assertEquals(0, IteratorUtils.toList(provider.findRoles("%olE%", Role.Target.ALL, 1, 2)).size());
}
private static SecurityService mockSecurityServiceWithUser(User currentUser) {
// Set the security sevice
SecurityService securityService = EasyMock.createNiceMock(SecurityService.class);
EasyMock.expect(securityService.getOrganization()).andReturn(currentUser.getOrganization()).anyTimes();
EasyMock.expect(securityService.getUser()).andReturn(currentUser).anyTimes();
EasyMock.replay(securityService);
return securityService;
}
private static JpaUser createUserWithRoles(JpaOrganization org, String username, String... roles) {
Set<JpaRole> userRoles = new HashSet<>();
for (String adminRole : roles) {
userRoles.add(new JpaRole(adminRole, org));
}
return new JpaUser(username, "pass1", org, "opencast", true, userRoles);
}
}
| ./CrossVul/dataset_final_sorted/CWE-327/java/bad_4532_6 |
crossvul-java_data_good_28_0 | package org.bouncycastle.crypto.generators;
import java.math.BigInteger;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator;
import org.bouncycastle.crypto.KeyGenerationParameters;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import org.bouncycastle.math.Primes;
import org.bouncycastle.math.ec.WNafUtil;
/**
* an RSA key pair generator.
*/
public class RSAKeyPairGenerator
implements AsymmetricCipherKeyPairGenerator
{
private static final BigInteger ONE = BigInteger.valueOf(1);
private RSAKeyGenerationParameters param;
public void init(KeyGenerationParameters param)
{
this.param = (RSAKeyGenerationParameters)param;
}
public AsymmetricCipherKeyPair generateKeyPair()
{
AsymmetricCipherKeyPair result = null;
boolean done = false;
//
// p and q values should have a length of half the strength in bits
//
int strength = param.getStrength();
int pbitlength = (strength + 1) / 2;
int qbitlength = strength - pbitlength;
int mindiffbits = (strength / 2) - 100;
if (mindiffbits < strength / 3)
{
mindiffbits = strength / 3;
}
int minWeight = strength >> 2;
// d lower bound is 2^(strength / 2)
BigInteger dLowerBound = BigInteger.valueOf(2).pow(strength / 2);
// squared bound (sqrt(2)*2^(nlen/2-1))^2
BigInteger squaredBound = ONE.shiftLeft(strength - 1);
// 2^(nlen/2 - 100)
BigInteger minDiff = ONE.shiftLeft(mindiffbits);
while (!done)
{
BigInteger p, q, n, d, e, pSub1, qSub1, gcd, lcm;
e = param.getPublicExponent();
p = chooseRandomPrime(pbitlength, e, squaredBound);
//
// generate a modulus of the required length
//
for (; ; )
{
q = chooseRandomPrime(qbitlength, e, squaredBound);
// p and q should not be too close together (or equal!)
BigInteger diff = q.subtract(p).abs();
if (diff.bitLength() < mindiffbits || diff.compareTo(minDiff) <= 0)
{
continue;
}
//
// calculate the modulus
//
n = p.multiply(q);
if (n.bitLength() != strength)
{
//
// if we get here our primes aren't big enough, make the largest
// of the two p and try again
//
p = p.max(q);
continue;
}
/*
* Require a minimum weight of the NAF representation, since low-weight composites may
* be weak against a version of the number-field-sieve for factoring.
*
* See "The number field sieve for integers of low weight", Oliver Schirokauer.
*/
if (WNafUtil.getNafWeight(n) < minWeight)
{
p = chooseRandomPrime(pbitlength, e, squaredBound);
continue;
}
break;
}
if (p.compareTo(q) < 0)
{
gcd = p;
p = q;
q = gcd;
}
pSub1 = p.subtract(ONE);
qSub1 = q.subtract(ONE);
gcd = pSub1.gcd(qSub1);
lcm = pSub1.divide(gcd).multiply(qSub1);
//
// calculate the private exponent
//
d = e.modInverse(lcm);
if (d.compareTo(dLowerBound) <= 0)
{
continue;
}
else
{
done = true;
}
//
// calculate the CRT factors
//
BigInteger dP, dQ, qInv;
dP = d.remainder(pSub1);
dQ = d.remainder(qSub1);
qInv = q.modInverse(p);
result = new AsymmetricCipherKeyPair(
new RSAKeyParameters(false, n, e),
new RSAPrivateCrtKeyParameters(n, e, d, p, q, dP, dQ, qInv));
}
return result;
}
/**
* Choose a random prime value for use with RSA
*
* @param bitlength the bit-length of the returned prime
* @param e the RSA public exponent
* @return A prime p, with (p-1) relatively prime to e
*/
protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger sqrdBound)
{
for (int i = 0; i != 5 * bitlength; i++)
{
BigInteger p = new BigInteger(bitlength, 1, param.getRandom());
if (p.mod(e).equals(ONE))
{
continue;
}
if (p.multiply(p).compareTo(sqrdBound) < 0)
{
continue;
}
if (!isProbablePrime(p))
{
continue;
}
if (!e.gcd(p.subtract(ONE)).equals(ONE))
{
continue;
}
return p;
}
throw new IllegalStateException("unable to generate prime number for RSA key");
}
protected boolean isProbablePrime(BigInteger x)
{
int iterations = getNumberOfIterations(x.bitLength(), param.getCertainty());
/*
* Primes class for FIPS 186-4 C.3 primality checking
*/
return !Primes.hasAnySmallFactors(x) && Primes.isMRProbablePrime(x, param.getRandom(), iterations);
}
private static int getNumberOfIterations(int bits, int certainty)
{
/*
* NOTE: We enforce a minimum 'certainty' of 100 for bits >= 1024 (else 80). Where the
* certainty is higher than the FIPS 186-4 tables (C.2/C.3) cater to, extra iterations
* are added at the "worst case rate" for the excess.
*/
if (bits >= 1536)
{
return certainty <= 100 ? 3
: certainty <= 128 ? 4
: 4 + (certainty - 128 + 1) / 2;
}
else if (bits >= 1024)
{
return certainty <= 100 ? 4
: certainty <= 112 ? 5
: 5 + (certainty - 112 + 1) / 2;
}
else if (bits >= 512)
{
return certainty <= 80 ? 5
: certainty <= 100 ? 7
: 7 + (certainty - 100 + 1) / 2;
}
else
{
return certainty <= 80 ? 40
: 40 + (certainty - 80 + 1) / 2;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-327/java/good_28_0 |
crossvul-java_data_bad_4532_5 | /**
* 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.userdirectory.endpoint;
import static org.apache.http.HttpStatus.SC_BAD_REQUEST;
import static org.apache.http.HttpStatus.SC_CONFLICT;
import static org.apache.http.HttpStatus.SC_CREATED;
import static org.apache.http.HttpStatus.SC_FORBIDDEN;
import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR;
import static org.apache.http.HttpStatus.SC_NOT_FOUND;
import static org.apache.http.HttpStatus.SC_OK;
import static org.opencastproject.util.RestUtil.getEndpointUrl;
import static org.opencastproject.util.UrlSupport.uri;
import static org.opencastproject.util.doc.rest.RestParameter.Type.STRING;
import org.opencastproject.security.api.JaxbUser;
import org.opencastproject.security.api.JaxbUserList;
import org.opencastproject.security.api.SecurityService;
import org.opencastproject.security.api.UnauthorizedException;
import org.opencastproject.security.api.User;
import org.opencastproject.security.impl.jpa.JpaOrganization;
import org.opencastproject.security.impl.jpa.JpaRole;
import org.opencastproject.security.impl.jpa.JpaUser;
import org.opencastproject.userdirectory.JpaUserAndRoleProvider;
import org.opencastproject.util.NotFoundException;
import org.opencastproject.util.UrlSupport;
import org.opencastproject.util.data.Tuple;
import org.opencastproject.util.doc.rest.RestParameter;
import org.opencastproject.util.doc.rest.RestQuery;
import org.opencastproject.util.doc.rest.RestResponse;
import org.opencastproject.util.doc.rest.RestService;
import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* Provides a sorted set of known users
*/
@Path("/")
@RestService(
name = "UsersUtils",
title = "User utils",
notes = "This service offers the default CRUD Operations for the internal Opencast users.",
abstractText = "Provides operations for internal Opencast users")
public class UserEndpoint {
/** The logger */
private static final Logger logger = LoggerFactory.getLogger(UserEndpoint.class);
private JpaUserAndRoleProvider jpaUserAndRoleProvider;
private SecurityService securityService;
private String endpointBaseUrl;
/** OSGi callback. */
public void activate(ComponentContext cc) {
logger.info("Start users endpoint");
final Tuple<String, String> endpointUrl = getEndpointUrl(cc);
endpointBaseUrl = UrlSupport.concat(endpointUrl.getA(), endpointUrl.getB());
}
/**
* @param securityService
* the securityService to set
*/
public void setSecurityService(SecurityService securityService) {
this.securityService = securityService;
}
/**
* @param jpaUserAndRoleProvider
* the persistenceProperties to set
*/
public void setJpaUserAndRoleProvider(JpaUserAndRoleProvider jpaUserAndRoleProvider) {
this.jpaUserAndRoleProvider = jpaUserAndRoleProvider;
}
@GET
@Path("users.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(
name = "allusersasjson",
description = "Returns a list of users",
returnDescription = "Returns a JSON representation of the list of user accounts",
restParameters = {
@RestParameter(
name = "limit",
defaultValue = "100",
description = "The maximum number of items to return per page.",
isRequired = false,
type = RestParameter.Type.STRING),
@RestParameter(
name = "offset",
defaultValue = "0",
description = "The page number.",
isRequired = false,
type = RestParameter.Type.STRING)
}, reponses = {
@RestResponse(
responseCode = SC_OK,
description = "The user accounts.")
})
public JaxbUserList getUsersAsJson(@QueryParam("limit") int limit, @QueryParam("offset") int offset)
throws IOException {
// Set the maximum number of items to return to 100 if this limit parameter is not given
if (limit < 1) {
limit = 100;
}
JaxbUserList userList = new JaxbUserList();
for (Iterator<User> i = jpaUserAndRoleProvider.findUsers("%", offset, limit); i.hasNext();) {
userList.add(i.next());
}
return userList;
}
@GET
@Path("{username}.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(
name = "user",
description = "Returns a user",
returnDescription = "Returns a JSON representation of a user",
pathParameters = {
@RestParameter(
name = "username",
description = "The username.",
isRequired = true,
type = STRING)
}, reponses = {
@RestResponse(
responseCode = SC_OK,
description = "The user account."),
@RestResponse(
responseCode = SC_NOT_FOUND,
description = "User not found")
})
public Response getUserAsJson(@PathParam("username") String username) throws NotFoundException {
User user = jpaUserAndRoleProvider.loadUser(username);
if (user == null) {
logger.debug("Requested user not found: {}", username);
return Response.status(SC_NOT_FOUND).build();
}
return Response.ok(JaxbUser.fromUser(user)).build();
}
@POST
@Path("/")
@RestQuery(
name = "createUser",
description = "Create a new user",
returnDescription = "Location of the new ressource",
restParameters = {
@RestParameter(
name = "username",
description = "The username.",
isRequired = true,
type = STRING),
@RestParameter(
name = "password",
description = "The password.",
isRequired = true,
type = STRING),
@RestParameter(
name = "name",
description = "The name.",
isRequired = false,
type = STRING),
@RestParameter(
name = "email",
description = "The email.",
isRequired = false,
type = STRING),
@RestParameter(
name = "roles",
description = "The user roles as a json array, for example: [\"ROLE_USER\", \"ROLE_ADMIN\"]",
isRequired = false,
type = STRING)
}, reponses = {
@RestResponse(
responseCode = SC_BAD_REQUEST,
description = "Malformed request syntax."),
@RestResponse(
responseCode = SC_CREATED,
description = "User has been created."),
@RestResponse(
responseCode = SC_CONFLICT,
description = "An user with this username already exist."),
@RestResponse(
responseCode = SC_FORBIDDEN,
description = "Not enough permissions to create a user with the admin role.")
})
public Response createUser(@FormParam("username") String username, @FormParam("password") String password,
@FormParam("name") String name, @FormParam("email") String email, @FormParam("roles") String roles) {
if (jpaUserAndRoleProvider.loadUser(username) != null) {
return Response.status(SC_CONFLICT).build();
}
try {
Set<JpaRole> rolesSet = parseRoles(roles);
/* Add new user */
logger.debug("Updating user {}", username);
JpaOrganization organization = (JpaOrganization) securityService.getOrganization();
JpaUser user = new JpaUser(username, password, organization, name, email, jpaUserAndRoleProvider.getName(), true,
rolesSet);
try {
jpaUserAndRoleProvider.addUser(user);
return Response.created(uri(endpointBaseUrl, user.getUsername() + ".json")).build();
} catch (UnauthorizedException ex) {
logger.debug("Create user failed", ex);
return Response.status(Response.Status.FORBIDDEN).build();
}
} catch (IllegalArgumentException e) {
logger.debug("Request with malformed ROLE data: {}", roles);
return Response.status(SC_BAD_REQUEST).build();
}
}
@PUT
@Path("{username}.json")
@RestQuery(
name = "updateUser",
description = "Update an user",
returnDescription = "Status ok",
restParameters = {
@RestParameter(
name = "password",
description = "The password.",
isRequired = true,
type = STRING),
@RestParameter(
name = "name",
description = "The name.",
isRequired = false,
type = STRING),
@RestParameter(
name = "email",
description = "The email.",
isRequired = false,
type = STRING),
@RestParameter(
name = "roles",
description = "The user roles as a json array, for example: [\"ROLE_USER\", \"ROLE_ADMIN\"]",
isRequired = false,
type = STRING)
}, pathParameters = @RestParameter(
name = "username",
description = "The username",
isRequired = true,
type = STRING),
reponses = {
@RestResponse(
responseCode = SC_BAD_REQUEST,
description = "Malformed request syntax."),
@RestResponse(
responseCode = SC_FORBIDDEN,
description = "Not enough permissions to update a user with the admin role."),
@RestResponse(
responseCode = SC_OK,
description = "User has been updated.") })
public Response setUser(@PathParam("username") String username, @FormParam("password") String password,
@FormParam("name") String name, @FormParam("email") String email, @FormParam("roles") String roles) {
try {
User user = jpaUserAndRoleProvider.loadUser(username);
if (user == null) {
return createUser(username, password, name, email, roles);
}
Set<JpaRole> rolesSet = parseRoles(roles);
logger.debug("Updating user {}", username);
JpaOrganization organization = (JpaOrganization) securityService.getOrganization();
jpaUserAndRoleProvider.updateUser(new JpaUser(username, password, organization, name, email,
jpaUserAndRoleProvider.getName(), true, rolesSet));
return Response.status(SC_OK).build();
} catch (NotFoundException e) {
logger.debug("User {} not found.", username);
return Response.status(SC_NOT_FOUND).build();
} catch (UnauthorizedException e) {
logger.debug("Update user failed", e);
return Response.status(Response.Status.FORBIDDEN).build();
} catch (IllegalArgumentException e) {
logger.debug("Request with malformed ROLE data: {}", roles);
return Response.status(SC_BAD_REQUEST).build();
}
}
@DELETE
@Path("{username}.json")
@RestQuery(
name = "deleteUser",
description = "Delete a new user",
returnDescription = "Status ok",
pathParameters = @RestParameter(
name = "username",
type = STRING,
isRequired = true,
description = "The username"),
reponses = {
@RestResponse(
responseCode = SC_OK,
description = "User has been deleted."),
@RestResponse(
responseCode = SC_FORBIDDEN,
description = "Not enough permissions to delete a user with the admin role."),
@RestResponse(
responseCode = SC_NOT_FOUND,
description = "User not found.")
})
public Response deleteUser(@PathParam("username") String username) {
try {
jpaUserAndRoleProvider.deleteUser(username, securityService.getOrganization().getId());
} catch (NotFoundException e) {
logger.debug("User {} not found.", username);
return Response.status(SC_NOT_FOUND).build();
} catch (UnauthorizedException e) {
logger.debug("Error during deletion of user {}: {}", username, e);
return Response.status(SC_FORBIDDEN).build();
} catch (Exception e) {
logger.error("Error during deletion of user {}: {}", username, e);
return Response.status(SC_INTERNAL_SERVER_ERROR).build();
}
logger.debug("User {} removed.", username);
return Response.status(SC_OK).build();
}
/**
* Parse JSON roles array.
*
* @param roles
* String representation of JSON array containing roles
*/
private Set<JpaRole> parseRoles(String roles) throws IllegalArgumentException {
JSONArray rolesArray = null;
/* Try parsing JSON. Return Bad Request if malformed. */
try {
rolesArray = (JSONArray) JSONValue.parseWithException(StringUtils.isEmpty(roles) ? "[]" : roles);
} catch (Exception e) {
throw new IllegalArgumentException("Error parsing JSON array", e);
}
Set<JpaRole> rolesSet = new HashSet<JpaRole>();
/* Add given roles */
for (Object role : rolesArray) {
try {
rolesSet.add(new JpaRole((String) role, (JpaOrganization) securityService.getOrganization()));
} catch (ClassCastException e) {
throw new IllegalArgumentException("Error parsing array vales as String", e);
}
}
return rolesSet;
}
}
| ./CrossVul/dataset_final_sorted/CWE-327/java/bad_4532_5 |
crossvul-java_data_bad_4532_3 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-327/java/bad_4532_3 |
crossvul-java_data_good_4532_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.security.impl.jpa;
import org.opencastproject.security.api.Organization;
import org.opencastproject.security.api.Role;
import org.opencastproject.security.api.User;
import org.opencastproject.util.EqualsUtil;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
/**
* JPA-annotated user object.
*/
@Entity
@Access(AccessType.FIELD)
@Table(name = "oc_user", uniqueConstraints = { @UniqueConstraint(columnNames = { "username", "organization" }) })
@NamedQueries({
@NamedQuery(name = "User.findByQuery", query = "select u from JpaUser u where UPPER(u.username) like :query and u.organization.id = :org"),
@NamedQuery(name = "User.findByIdAndOrg", query = "select u from JpaUser u where u.id=:id and u.organization.id = :org"),
@NamedQuery(name = "User.findByUsername", query = "select u from JpaUser u where u.username=:u and u.organization.id = :org"),
@NamedQuery(name = "User.findAll", query = "select u from JpaUser u where u.organization.id = :org"),
@NamedQuery(name = "User.findInsecureHash",
query = "select u from JpaUser u where length(u.password) = 32 and u.organization.id = :org"),
@NamedQuery(name = "User.findAllByUserNames", query = "select u from JpaUser u where u.organization.id = :org AND u.username IN :names"),
@NamedQuery(name = "User.countAll", query = "select COUNT(u) from JpaUser u where u.organization.id = :org") })
public class JpaUser implements User {
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@Column(name = "username", length = 128)
private String username;
@Column(name = "name")
private String name;
@Column(name = "email")
private String email;
@Column(name = "manageable")
private boolean manageable = true;
@Transient
private String provider;
@Lob
@Column(name = "password", length = 65535)
private String password;
@OneToOne()
@JoinColumn(name = "organization")
private JpaOrganization organization;
@ManyToMany(cascade = { CascadeType.MERGE }, fetch = FetchType.LAZY)
@JoinTable(name = "oc_user_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") }, uniqueConstraints = { @UniqueConstraint(columnNames = {
"user_id", "role_id" }) })
private Set<JpaRole> roles;
/**
* No-arg constructor needed by JPA
*/
public JpaUser() {
}
/**
* Constructs a user with the specified username, password, name, email and provider.
*
* @param username
* the username
* @param password
* the password
* @param organization
* the organization
* @param name
* the name
* @param email
* the email
* @param provider
* the provider
* @param manageable
* whether the user is manageable
*/
public JpaUser(String username, String password, JpaOrganization organization, String name, String email,
String provider, boolean manageable) {
super();
this.username = username;
this.password = password;
this.organization = organization;
this.name = name;
this.email = email;
this.provider = provider;
this.manageable = manageable;
this.roles = new HashSet<JpaRole>();
}
/**
* Constructs a user with the specified username, password, provider and roles.
*
* @param username
* the username
* @param password
* the password
* @param organization
* the organization
* @param provider
* the provider
* @param manageable
* whether the user is manageable
* @param roles
* the roles
*/
public JpaUser(String username, String password, JpaOrganization organization, String provider, boolean manageable,
Set<JpaRole> roles) {
this(username, password, organization, null, null, provider, manageable);
for (Role role : roles) {
if (!Objects.equals(organization.getId(), role.getOrganizationId())) {
throw new IllegalArgumentException("Role " + role + " is not from the same organization!");
}
}
this.roles = roles;
}
/**
* Constructs a user with the specified username, password, name, email, provider and roles.
*
* @param username
* the username
* @param password
* the password
* @param organization
* the organization
* @param name
* the name
* @param email
* the email
* @param provider
* the provider
* @param manageable
* whether the user is manageable
* @param roles
* the roles
*/
public JpaUser(String username, String password, JpaOrganization organization, String name, String email,
String provider, boolean manageable, Set<JpaRole> roles) {
this(username, password, organization, name, email, provider, manageable);
for (Role role : roles) {
if (!Objects.equals(organization.getId(), role.getOrganizationId())) {
throw new IllegalArgumentException("Role " + role + " is not from the same organization ("
+ organization.getId() + ")");
}
}
this.roles = roles;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* Gets this user's clear text password.
*
* @return the user account's password
*/
@Override
public String getPassword() {
return password;
}
/**
* @see org.opencastproject.security.api.User#getUsername()
*/
@Override
public String getUsername() {
return username;
}
/**
* @see org.opencastproject.security.api.User#hasRole(String)
*/
@Override
public boolean hasRole(String roleName) {
for (Role role : roles) {
if (role.getName().equals(roleName))
return true;
}
return false;
}
/**
* @see org.opencastproject.security.api.User#getOrganization()
*/
@Override
public Organization getOrganization() {
return organization;
}
/**
* @see org.opencastproject.security.api.User#getRoles()
*/
@Override
public Set<Role> getRoles() {
return new HashSet<Role>(roles);
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof User))
return false;
User other = (User) obj;
return username.equals(other.getUsername()) && organization.equals(other.getOrganization())
&& EqualsUtil.eq(provider, other.getProvider());
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return Objects.hash(username, organization, provider);
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return new StringBuilder(username).append(":").append(organization).append(":").append(provider).toString();
}
@Override
public String getName() {
return name;
}
@Override
public String getEmail() {
return email;
}
@Override
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
@Override
public boolean isManageable() {
return manageable;
}
public void setManageable(boolean isManageable) {
this.manageable = isManageable;
}
}
| ./CrossVul/dataset_final_sorted/CWE-327/java/good_4532_1 |
crossvul-java_data_bad_4532_4 | /**
* 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.userdirectory;
import org.opencastproject.security.api.Group;
import org.opencastproject.security.api.Role;
import org.opencastproject.security.api.RoleProvider;
import org.opencastproject.security.api.SecurityService;
import org.opencastproject.security.api.UnauthorizedException;
import org.opencastproject.security.api.User;
import org.opencastproject.security.api.UserProvider;
import org.opencastproject.security.impl.jpa.JpaOrganization;
import org.opencastproject.security.impl.jpa.JpaRole;
import org.opencastproject.security.impl.jpa.JpaUser;
import org.opencastproject.userdirectory.utils.UserDirectoryUtils;
import org.opencastproject.util.NotFoundException;
import org.opencastproject.util.PasswordEncoder;
import org.opencastproject.util.data.Monadics;
import org.opencastproject.util.data.Option;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.apache.commons.lang3.StringUtils;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
/**
* Manages and locates users using JPA.
*/
public class JpaUserAndRoleProvider implements UserProvider, RoleProvider {
/** The logger */
private static final Logger logger = LoggerFactory.getLogger(JpaUserAndRoleProvider.class);
public static final String PERSISTENCE_UNIT = "org.opencastproject.common";
/** The user provider name */
public static final String PROVIDER_NAME = "opencast";
/** Username constant used in JSON formatted users */
public static final String USERNAME = "username";
/** Role constant used in JSON formatted users */
public static final String ROLES = "roles";
/** Encoding expected from all inputs */
public static final String ENCODING = "UTF-8";
/** The delimiter for the User cache */
private static final String DELIMITER = ";==;";
/** The security service */
protected SecurityService securityService = null;
/** Group provider */
protected JpaGroupRoleProvider groupRoleProvider;
/** A cache of users, which lightens the load on the SQL server */
private LoadingCache<String, Object> cache = null;
/** A token to store in the miss cache */
protected Object nullToken = new Object();
/** OSGi DI */
void setEntityManagerFactory(EntityManagerFactory emf) {
this.emf = emf;
}
/**
* @param securityService
* the securityService to set
*/
public void setSecurityService(SecurityService securityService) {
this.securityService = securityService;
}
/**
* @param groupRoleProvider
* the groupRoleProvider to set
*/
void setGroupRoleProvider(JpaGroupRoleProvider groupRoleProvider) {
this.groupRoleProvider = groupRoleProvider;
}
/** The factory used to generate the entity manager */
protected EntityManagerFactory emf = null;
/**
* Callback for activation of this component.
*
* @param cc
* the component context
*/
public void activate(ComponentContext cc) {
logger.debug("activate");
// Setup the caches
cache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).build(new CacheLoader<String, Object>() {
@Override
public Object load(String id) {
String[] key = id.split(DELIMITER);
logger.trace("Loading user '{}':'{}' from database", key[0], key[1]);
User user = loadUser(key[0], key[1]);
return user == null ? nullToken : user;
}
});
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.RoleProvider#getRolesForUser(String)
*/
@Override
public List<Role> getRolesForUser(String userName) {
ArrayList<Role> roles = new ArrayList<Role>();
User user = loadUser(userName);
if (user == null)
return roles;
roles.addAll(user.getRoles());
return roles;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.UserProvider#findUsers(String, int, int)
*/
@Override
public Iterator<User> findUsers(String query, int offset, int limit) {
if (query == null)
throw new IllegalArgumentException("Query must be set");
String orgId = securityService.getOrganization().getId();
List<JpaUser> users = UserDirectoryPersistenceUtil.findUsersByQuery(orgId, query, limit, offset, emf);
return Monadics.mlist(users).map(addProviderName).iterator();
}
@Override
public Iterator<User> findUsers(Collection<String> userNames) {
String orgId = securityService.getOrganization().getId();
List<JpaUser> users = UserDirectoryPersistenceUtil.findUsersByUserName(userNames, orgId, emf);
return Monadics.mlist(users).map(addProviderName).iterator();
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.RoleProvider#findRoles(String, Role.Target, int, int)
*/
@Override
public Iterator<Role> findRoles(String query, Role.Target target, int offset, int limit) {
if (query == null)
throw new IllegalArgumentException("Query must be set");
// This provider persists roles but is not authoritative for any roles, so return an empty set
return new ArrayList<Role>().iterator();
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.UserProvider#loadUser(java.lang.String)
*/
@Override
public User loadUser(String userName) {
String orgId = securityService.getOrganization().getId();
Object user = cache.getUnchecked(userName.concat(DELIMITER).concat(orgId));
if (user == nullToken) {
return null;
} else {
return (User) user;
}
}
@Override
public Iterator<User> getUsers() {
String orgId = securityService.getOrganization().getId();
List<JpaUser> users = UserDirectoryPersistenceUtil.findUsers(orgId, 0, 0, emf);
return Monadics.mlist(users).map(addProviderName).iterator();
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.UserProvider#getOrganization()
*/
@Override
public String getOrganization() {
return ALL_ORGANIZATIONS;
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getClass().getName();
}
/**
* Loads a user from persistence
*
* @param userName
* the user name
* @param organization
* the organization id
* @return the loaded user or <code>null</code> if not found
*/
public User loadUser(String userName, String organization) {
JpaUser user = UserDirectoryPersistenceUtil.findUser(userName, organization, emf);
return Option.option(user).map(addProviderName).getOrElseNull();
}
/**
* Loads a user from persistence
*
* @param userId
* the user's id
* @param organization
* the organization id
* @return the loaded user or <code>null</code> if not found
*/
public User loadUser(long userId, String organization) {
JpaUser user = UserDirectoryPersistenceUtil.findUser(userId, organization, emf);
return Option.option(user).map(addProviderName).getOrElseNull();
}
/**
* Adds a user to the persistence
*
* @param user
* the user to add
*
* @throws org.opencastproject.security.api.UnauthorizedException
* if the user is not allowed to create other user with the given roles
*/
public void addUser(JpaUser user) throws UnauthorizedException {
if (!UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, user.getRoles()))
throw new UnauthorizedException("The user is not allowed to set the admin role on other users");
// Create a JPA user with an encoded password.
String 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 newUser = new JpaUser(user.getUsername(), encodedPassword, organization, user.getName(), user.getEmail(),
user.getProvider(), user.isManageable(), roles);
// Then save the user
EntityManager em = null;
EntityTransaction tx = null;
try {
em = emf.createEntityManager();
tx = em.getTransaction();
tx.begin();
em.persist(newUser);
tx.commit();
cache.put(user.getUsername() + DELIMITER + user.getOrganization().getId(), newUser);
} finally {
if (tx.isActive()) {
tx.rollback();
}
if (em != null)
em.close();
}
updateGroupMembership(user);
}
/**
* Updates a user to the persistence
*
* @param user
* the user to save
* @throws NotFoundException
* @throws org.opencastproject.security.api.UnauthorizedException
* if the current user is not allowed to update user with the given roles
*/
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;
}
/**
* Select only internal roles
*
* @param userRoles
* the user's full set of roles
*/
private Set<JpaRole> filterRoles(Set<Role> userRoles) {
Set<JpaRole> roles = new HashSet<JpaRole>();
for (Role role : userRoles) {
if (Role.Type.INTERNAL.equals(role.getType()) && !role.getName().startsWith(Group.ROLE_PREFIX)) {
JpaRole jpaRole = (JpaRole) role;
roles.add(jpaRole);
}
}
return roles;
}
/**
* Updates a user's groups based on assigned roles
*
* @param user
* the user for whom groups should be updated
* @throws NotFoundException
*/
private void updateGroupMembership(JpaUser user) {
logger.debug("updateGroupMembership({}, roles={})", user.getUsername(), user.getRoles().size());
List<String> internalGroupRoles = new ArrayList<String>();
for (Role role : user.getRoles()) {
if (Role.Type.GROUP.equals(role.getType())
|| (Role.Type.INTERNAL.equals(role.getType()) && role.getName().startsWith(Group.ROLE_PREFIX))) {
internalGroupRoles.add(role.getName());
}
}
groupRoleProvider.updateGroupMembershipFromRoles(user.getUsername(), user.getOrganization().getId(), internalGroupRoles);
}
/**
* Delete the given user
*
* @param username
* the name of the user to delete
* @param orgId
* the organization id
* @throws NotFoundException
* if the requested user is not exist
* @throws org.opencastproject.security.api.UnauthorizedException
* if you havn't permissions to delete an admin user (only admins may do that)
* @throws Exception
*/
public void deleteUser(String username, String orgId) throws NotFoundException, UnauthorizedException, Exception {
User user = loadUser(username, orgId);
if (user != null && !UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, user.getRoles()))
throw new UnauthorizedException("The user is not allowed to delete an admin user");
// Remove the user's group membership
groupRoleProvider.updateGroupMembershipFromRoles(username, orgId, new ArrayList<String>());
// Remove the user
UserDirectoryPersistenceUtil.deleteUser(username, orgId, emf);
cache.invalidate(username + DELIMITER + orgId);
}
/**
* Adds a role to the persistence
*
* @param jpaRole
* the role
*/
public void addRole(JpaRole jpaRole) {
HashSet<JpaRole> roles = new HashSet<JpaRole>();
roles.add(jpaRole);
UserDirectoryPersistenceUtil.saveRoles(roles, emf);
}
@Override
public String getName() {
return PROVIDER_NAME;
}
private static org.opencastproject.util.data.Function<JpaUser, User> addProviderName = new org.opencastproject.util.data.Function<JpaUser, User>() {
@Override
public User apply(JpaUser a) {
a.setProvider(PROVIDER_NAME);
return a;
}
};
@Override
public long countUsers() {
String orgId = securityService.getOrganization().getId();
return UserDirectoryPersistenceUtil.countUsers(orgId, emf);
}
@Override
public void invalidate(String userName) {
String orgId = securityService.getOrganization().getId();
cache.invalidate(userName + DELIMITER + orgId);
}
}
| ./CrossVul/dataset_final_sorted/CWE-327/java/bad_4532_4 |
crossvul-java_data_bad_29_0 | package org.bouncycastle.crypto.generators;
import java.math.BigInteger;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator;
import org.bouncycastle.crypto.KeyGenerationParameters;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import org.bouncycastle.math.Primes;
import org.bouncycastle.math.ec.WNafUtil;
/**
* an RSA key pair generator.
*/
public class RSAKeyPairGenerator
implements AsymmetricCipherKeyPairGenerator
{
private static final BigInteger ONE = BigInteger.valueOf(1);
private RSAKeyGenerationParameters param;
private int iterations;
public void init(KeyGenerationParameters param)
{
this.param = (RSAKeyGenerationParameters)param;
this.iterations = getNumberOfIterations(this.param.getStrength(), this.param.getCertainty());
}
public AsymmetricCipherKeyPair generateKeyPair()
{
AsymmetricCipherKeyPair result = null;
boolean done = false;
//
// p and q values should have a length of half the strength in bits
//
int strength = param.getStrength();
int pbitlength = (strength + 1) / 2;
int qbitlength = strength - pbitlength;
int mindiffbits = (strength / 2) - 100;
if (mindiffbits < strength / 3)
{
mindiffbits = strength / 3;
}
int minWeight = strength >> 2;
// d lower bound is 2^(strength / 2)
BigInteger dLowerBound = BigInteger.valueOf(2).pow(strength / 2);
// squared bound (sqrt(2)*2^(nlen/2-1))^2
BigInteger squaredBound = ONE.shiftLeft(strength - 1);
// 2^(nlen/2 - 100)
BigInteger minDiff = ONE.shiftLeft(mindiffbits);
while (!done)
{
BigInteger p, q, n, d, e, pSub1, qSub1, gcd, lcm;
e = param.getPublicExponent();
p = chooseRandomPrime(pbitlength, e, squaredBound);
//
// generate a modulus of the required length
//
for (; ; )
{
q = chooseRandomPrime(qbitlength, e, squaredBound);
// p and q should not be too close together (or equal!)
BigInteger diff = q.subtract(p).abs();
if (diff.bitLength() < mindiffbits || diff.compareTo(minDiff) <= 0)
{
continue;
}
//
// calculate the modulus
//
n = p.multiply(q);
if (n.bitLength() != strength)
{
//
// if we get here our primes aren't big enough, make the largest
// of the two p and try again
//
p = p.max(q);
continue;
}
/*
* Require a minimum weight of the NAF representation, since low-weight composites may
* be weak against a version of the number-field-sieve for factoring.
*
* See "The number field sieve for integers of low weight", Oliver Schirokauer.
*/
if (WNafUtil.getNafWeight(n) < minWeight)
{
p = chooseRandomPrime(pbitlength, e, squaredBound);
continue;
}
break;
}
if (p.compareTo(q) < 0)
{
gcd = p;
p = q;
q = gcd;
}
pSub1 = p.subtract(ONE);
qSub1 = q.subtract(ONE);
gcd = pSub1.gcd(qSub1);
lcm = pSub1.divide(gcd).multiply(qSub1);
//
// calculate the private exponent
//
d = e.modInverse(lcm);
if (d.compareTo(dLowerBound) <= 0)
{
continue;
}
else
{
done = true;
}
//
// calculate the CRT factors
//
BigInteger dP, dQ, qInv;
dP = d.remainder(pSub1);
dQ = d.remainder(qSub1);
qInv = q.modInverse(p);
result = new AsymmetricCipherKeyPair(
new RSAKeyParameters(false, n, e),
new RSAPrivateCrtKeyParameters(n, e, d, p, q, dP, dQ, qInv));
}
return result;
}
/**
* Choose a random prime value for use with RSA
*
* @param bitlength the bit-length of the returned prime
* @param e the RSA public exponent
* @return A prime p, with (p-1) relatively prime to e
*/
protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger sqrdBound)
{
for (int i = 0; i != 5 * bitlength; i++)
{
BigInteger p = new BigInteger(bitlength, 1, param.getRandom());
if (p.mod(e).equals(ONE))
{
continue;
}
if (p.multiply(p).compareTo(sqrdBound) < 0)
{
continue;
}
if (!isProbablePrime(p))
{
continue;
}
if (!e.gcd(p.subtract(ONE)).equals(ONE))
{
continue;
}
return p;
}
throw new IllegalStateException("unable to generate prime number for RSA key");
}
protected boolean isProbablePrime(BigInteger x)
{
/*
* Primes class for FIPS 186-4 C.3 primality checking
*/
return !Primes.hasAnySmallFactors(x) && Primes.isMRProbablePrime(x, param.getRandom(), iterations);
}
private static int getNumberOfIterations(int bits, int certainty)
{
/*
* NOTE: We enforce a minimum 'certainty' of 100 for bits >= 1024 (else 80). Where the
* certainty is higher than the FIPS 186-4 tables (C.2/C.3) cater to, extra iterations
* are added at the "worst case rate" for the excess.
*/
if (bits >= 1536)
{
return certainty <= 100 ? 3
: certainty <= 128 ? 4
: 4 + (certainty - 128 + 1) / 2;
}
else if (bits >= 1024)
{
return certainty <= 100 ? 4
: certainty <= 112 ? 5
: 5 + (certainty - 112 + 1) / 2;
}
else if (bits >= 512)
{
return certainty <= 80 ? 5
: certainty <= 100 ? 7
: 7 + (certainty - 100 + 1) / 2;
}
else
{
return certainty <= 80 ? 40
: 40 + (certainty - 80 + 1) / 2;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-327/java/bad_29_0 |
crossvul-java_data_bad_4532_2 | /**
* 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.util;
import org.apache.commons.codec.digest.DigestUtils;
/**
* A password encoder that md5 hashes a password with a salt.
*/
public final class PasswordEncoder {
/**
* Private constructor to disallow construction of this utility class.
*/
private PasswordEncoder() {
}
/**
* Encode a clear text password.
*
* @param clearText
* the password
* @param salt
* the salt. See http://en.wikipedia.org/wiki/Salt_%28cryptography%29
* @return the encoded password
* @throws IllegalArgumentException
* if clearText or salt are null
*/
public static String encode(String clearText, Object salt) throws IllegalArgumentException {
if (clearText == null || salt == null)
throw new IllegalArgumentException("clearText and salt must not be null");
return DigestUtils.md5Hex(clearText + "{" + salt.toString() + "}");
}
}
| ./CrossVul/dataset_final_sorted/CWE-327/java/bad_4532_2 |
crossvul-java_data_bad_4532_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.security.impl.jpa;
import org.opencastproject.security.api.Organization;
import org.opencastproject.security.api.Role;
import org.opencastproject.security.api.User;
import org.opencastproject.util.EqualsUtil;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
/**
* JPA-annotated user object.
*/
@Entity
@Access(AccessType.FIELD)
@Table(name = "oc_user", uniqueConstraints = { @UniqueConstraint(columnNames = { "username", "organization" }) })
@NamedQueries({
@NamedQuery(name = "User.findByQuery", query = "select u from JpaUser u where UPPER(u.username) like :query and u.organization.id = :org"),
@NamedQuery(name = "User.findByIdAndOrg", query = "select u from JpaUser u where u.id=:id and u.organization.id = :org"),
@NamedQuery(name = "User.findByUsername", query = "select u from JpaUser u where u.username=:u and u.organization.id = :org"),
@NamedQuery(name = "User.findAll", query = "select u from JpaUser u where u.organization.id = :org"),
@NamedQuery(name = "User.findAllByUserNames", query = "select u from JpaUser u where u.organization.id = :org AND u.username IN :names"),
@NamedQuery(name = "User.countAll", query = "select COUNT(u) from JpaUser u where u.organization.id = :org") })
public class JpaUser implements User {
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@Column(name = "username", length = 128)
private String username;
@Column(name = "name")
private String name;
@Column(name = "email")
private String email;
@Column(name = "manageable")
private boolean manageable = true;
@Transient
private String provider;
@Lob
@Column(name = "password", length = 65535)
private String password;
@OneToOne()
@JoinColumn(name = "organization")
private JpaOrganization organization;
@ManyToMany(cascade = { CascadeType.MERGE }, fetch = FetchType.LAZY)
@JoinTable(name = "oc_user_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") }, uniqueConstraints = { @UniqueConstraint(columnNames = {
"user_id", "role_id" }) })
private Set<JpaRole> roles;
/**
* No-arg constructor needed by JPA
*/
public JpaUser() {
}
/**
* Constructs a user with the specified username, password, name, email and provider.
*
* @param username
* the username
* @param password
* the password
* @param organization
* the organization
* @param name
* the name
* @param email
* the email
* @param provider
* the provider
* @param manageable
* whether the user is manageable
*/
public JpaUser(String username, String password, JpaOrganization organization, String name, String email,
String provider, boolean manageable) {
super();
this.username = username;
this.password = password;
this.organization = organization;
this.name = name;
this.email = email;
this.provider = provider;
this.manageable = manageable;
this.roles = new HashSet<JpaRole>();
}
/**
* Constructs a user with the specified username, password, provider and roles.
*
* @param username
* the username
* @param password
* the password
* @param organization
* the organization
* @param provider
* the provider
* @param manageable
* whether the user is manageable
* @param roles
* the roles
*/
public JpaUser(String username, String password, JpaOrganization organization, String provider, boolean manageable,
Set<JpaRole> roles) {
this(username, password, organization, null, null, provider, manageable);
for (Role role : roles) {
if (!Objects.equals(organization.getId(), role.getOrganizationId())) {
throw new IllegalArgumentException("Role " + role + " is not from the same organization!");
}
}
this.roles = roles;
}
/**
* Constructs a user with the specified username, password, name, email, provider and roles.
*
* @param username
* the username
* @param password
* the password
* @param organization
* the organization
* @param name
* the name
* @param email
* the email
* @param provider
* the provider
* @param manageable
* whether the user is manageable
* @param roles
* the roles
*/
public JpaUser(String username, String password, JpaOrganization organization, String name, String email,
String provider, boolean manageable, Set<JpaRole> roles) {
this(username, password, organization, name, email, provider, manageable);
for (Role role : roles) {
if (!Objects.equals(organization.getId(), role.getOrganizationId())) {
throw new IllegalArgumentException("Role " + role + " is not from the same organization ("
+ organization.getId() + ")");
}
}
this.roles = roles;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* Gets this user's clear text password.
*
* @return the user account's password
*/
@Override
public String getPassword() {
return password;
}
/**
* @see org.opencastproject.security.api.User#getUsername()
*/
@Override
public String getUsername() {
return username;
}
/**
* @see org.opencastproject.security.api.User#hasRole(String)
*/
@Override
public boolean hasRole(String roleName) {
for (Role role : roles) {
if (role.getName().equals(roleName))
return true;
}
return false;
}
/**
* @see org.opencastproject.security.api.User#getOrganization()
*/
@Override
public Organization getOrganization() {
return organization;
}
/**
* @see org.opencastproject.security.api.User#getRoles()
*/
@Override
public Set<Role> getRoles() {
return new HashSet<Role>(roles);
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof User))
return false;
User other = (User) obj;
return username.equals(other.getUsername()) && organization.equals(other.getOrganization())
&& EqualsUtil.eq(provider, other.getProvider());
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return Objects.hash(username, organization, provider);
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return new StringBuilder(username).append(":").append(organization).append(":").append(provider).toString();
}
@Override
public String getName() {
return name;
}
@Override
public String getEmail() {
return email;
}
@Override
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
@Override
public boolean isManageable() {
return manageable;
}
public void setManageable(boolean isManageable) {
this.manageable = isManageable;
}
}
| ./CrossVul/dataset_final_sorted/CWE-327/java/bad_4532_1 |
crossvul-java_data_good_4532_6 | /**
* 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.userdirectory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.opencastproject.util.data.Collections.set;
import static org.opencastproject.util.persistence.PersistenceUtil.newTestEntityManagerFactory;
import org.opencastproject.kernel.security.CustomPasswordEncoder;
import org.opencastproject.security.api.Role;
import org.opencastproject.security.api.SecurityConstants;
import org.opencastproject.security.api.SecurityService;
import org.opencastproject.security.api.UnauthorizedException;
import org.opencastproject.security.api.User;
import org.opencastproject.security.impl.jpa.JpaOrganization;
import org.opencastproject.security.impl.jpa.JpaRole;
import org.opencastproject.security.impl.jpa.JpaUser;
import org.opencastproject.util.NotFoundException;
import org.opencastproject.util.data.Collections;
import org.apache.commons.collections4.IteratorUtils;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class JpaUserProviderTest {
private JpaUserAndRoleProvider provider = null;
private JpaOrganization org1 = null;
private JpaOrganization org2 = null;
private CustomPasswordEncoder passwordEncoder = new CustomPasswordEncoder();
@Before
public void setUp() throws Exception {
org1 = new JpaOrganization("org1", "org1", "localhost", 80, "admin", "anon", null);
org2 = new JpaOrganization("org2", "org2", "127.0.0.1", 80, "admin", "anon", null);
SecurityService securityService = mockSecurityServiceWithUser(
createUserWithRoles(org1, "admin", SecurityConstants.GLOBAL_SYSTEM_ROLES));
JpaGroupRoleProvider groupRoleProvider = EasyMock.createNiceMock(JpaGroupRoleProvider.class);
provider = new JpaUserAndRoleProvider();
provider.setSecurityService(securityService);
provider.setEntityManagerFactory(newTestEntityManagerFactory(JpaUserAndRoleProvider.PERSISTENCE_UNIT));
provider.setGroupRoleProvider(groupRoleProvider);
provider.activate(null);
}
@Test
public void testAddAndGetUser() throws Exception {
JpaUser user = createUserWithRoles(org1, "user1", "ROLE_ASTRO_101_SPRING_2011_STUDENT");
provider.addUser(user);
User loadUser = provider.loadUser("user1");
assertNotNull(loadUser);
assertEquals(user.getUsername(), loadUser.getUsername());
assertTrue(passwordEncoder.isPasswordValid(loadUser.getPassword(), user.getPassword(), null));
assertEquals(user.getOrganization(), loadUser.getOrganization());
assertEquals(user.getRoles(), loadUser.getRoles());
assertNull("Loading 'does not exist' should return null", provider.loadUser("does not exist"));
assertNull("Loading 'does not exist' should return null", provider.loadUser("user1", org2.getId()));
loadUser = provider.loadUser("user1", org1.getId());
assertNotNull(loadUser);
assertEquals(user.getUsername(), loadUser.getUsername());
assertTrue(passwordEncoder.isPasswordValid(loadUser.getPassword(), user.getPassword(), null));
assertEquals(user.getOrganization(), loadUser.getOrganization());
assertEquals(user.getRoles(), loadUser.getRoles());
}
@Test
public void testAddUserWithGlobalAdminRole() throws Exception {
JpaUser adminUser = createUserWithRoles(org1, "admin1", SecurityConstants.GLOBAL_ADMIN_ROLE);
provider.addUser(adminUser);
User loadedUser = provider.loadUser(adminUser.getUsername());
assertNotNull("The currently added user isn't loaded as expected", loadedUser);
assertEquals(adminUser.getUsername(), loadedUser.getUsername());
assertEquals(adminUser.getRoles(), loadedUser.getRoles());
}
@Test
public void testAddUserWithOrgAdminRoleAsGlobalAdmin() throws Exception {
JpaUser newUser = createUserWithRoles(org1, "org_admin2", org1.getAdminRole());
provider.addUser(newUser);
User loadedUser = provider.loadUser(newUser.getUsername());
assertNotNull("The currently added user isn't loaded as expected", loadedUser);
assertEquals(newUser.getUsername(), loadedUser.getUsername());
assertEquals(newUser.getRoles(), loadedUser.getRoles());
}
@Test
public void testAddUserWithOrgAdminRoleAsOrgAdmin() throws Exception {
provider.setSecurityService(mockSecurityServiceWithUser(
createUserWithRoles(org1, "org_admin", org1.getAdminRole())));
JpaUser newUser = createUserWithRoles(org1, "org_admin2", org1.getAdminRole());
provider.addUser(newUser);
User loadedUser = provider.loadUser(newUser.getUsername());
assertNotNull("The currently added user isn't loaded as expected", loadedUser);
assertEquals(newUser.getUsername(), loadedUser.getUsername());
assertEquals(newUser.getRoles(), loadedUser.getRoles());
}
@Test(expected = UnauthorizedException.class)
public void testAddUserWithGlobalAdminRoleNotAllowedAsNonAdminUser() throws Exception {
provider.setSecurityService(mockSecurityServiceWithUser(
createUserWithRoles(org1, "user1", "ROLE_USER")));
JpaUser newUser = createUserWithRoles(org1, "admin2", SecurityConstants.GLOBAL_ADMIN_ROLE);
provider.addUser(newUser);
fail("The current user shouldn't able to create an global admin user.");
}
@Test(expected = UnauthorizedException.class)
public void testAddUserWithGlobalAdminRoleNotAllowedAsOrgAdmin() throws Exception {
provider.setSecurityService(mockSecurityServiceWithUser(
createUserWithRoles(org1, "org1_admin", org1.getAdminRole())));
JpaUser newUser = createUserWithRoles(org1, "admin2", SecurityConstants.GLOBAL_ADMIN_ROLE);
provider.addUser(newUser);
fail("The current user shouldn't able to create an global admin user.");
}
@Test(expected = UnauthorizedException.class)
public void testAddUserWithOrgAdminRoleNotAllowedAsNonAdminUser() throws Exception {
provider.setSecurityService(mockSecurityServiceWithUser(
createUserWithRoles(org1, "user1", "ROLE_USER")));
JpaUser newUser = createUserWithRoles(org1, "org_admin2", org1.getAdminRole());
provider.addUser(newUser);
fail("The current user shouldn't able to create an global admin user.");
}
@Test
public void testDeleteUser() throws Exception {
JpaUser user1 = createUserWithRoles(org1, "user1", "ROLE_ASTRO_101_SPRING_2011_STUDENT");
JpaUser user2 = createUserWithRoles(org1, "user2", "ROLE_ASTRO_101_SPRING_2011_STUDENT");
JpaUser user3 = createUserWithRoles(org1, "user3", "ROLE_ASTRO_101_SPRING_2011_STUDENT");
JpaUser user4 = createUserWithRoles(org1, "user4", "ROLE_ASTRO_101_SPRING_2011_STUDENT");
provider.addUser(user1);
provider.addUser(user2);
provider.addUser(user3);
provider.addUser(user4);
User loadUser = provider.loadUser("user1");
assertNotNull(loadUser);
provider.deleteUser("user1", user1.getOrganization().getId());
provider.deleteUser("user2", user1.getOrganization().getId());
provider.deleteUser("user3", user1.getOrganization().getId());
assertNull(provider.loadUser("user1", org1.getId()));
assertNull(provider.loadUser("user2", org1.getId()));
assertNull(provider.loadUser("user3", org1.getId()));
assertNotNull(provider.loadUser("user4", org1.getId()));
try {
provider.deleteUser("user1", user1.getOrganization().getId());
fail("Should throw a NotFoundException");
} catch (NotFoundException e) {
assertTrue("User not found.", true);
}
}
@Test(expected = UnauthorizedException.class)
public void testDeleteUserNotAllowedAsNonAdmin() throws UnauthorizedException, Exception {
JpaUser adminUser = createUserWithRoles(org1, "admin", "ROLE_ADMIN");
JpaUser nonAdminUser = createUserWithRoles(org1, "user1", "ROLE_USER");
try {
provider.addUser(adminUser);
provider.addUser(nonAdminUser);
} catch (UnauthorizedException ex) {
fail("The user shuld be created");
}
provider.setSecurityService(mockSecurityServiceWithUser(nonAdminUser));
provider.deleteUser(adminUser.getUsername(), org1.getId());
fail("An non admin user may not delete an admin user");
}
@Test
public void testUpdateUser() throws Exception {
Set<JpaRole> authorities = new HashSet<JpaRole>();
authorities.add(new JpaRole("ROLE_ASTRO_101_SPRING_2011_STUDENT", org1));
JpaUser user = new JpaUser("user1", "pass1", org1, provider.getName(), true, authorities);
provider.addUser(user);
User loadUser = provider.loadUser("user1");
assertNotNull(loadUser);
authorities.add(new JpaRole("ROLE_ASTRO_101_SPRING_2013_STUDENT", org1));
String newPassword = "newPassword";
JpaUser updateUser = new JpaUser(user.getUsername(), newPassword, org1, provider.getName(), true, authorities);
User loadUpdatedUser = provider.updateUser(updateUser);
// User loadUpdatedUser = provider.loadUser(user.getUsername());
assertNotNull(loadUpdatedUser);
assertEquals(user.getUsername(), loadUpdatedUser.getUsername());
assertTrue(passwordEncoder.isPasswordValid(loadUpdatedUser.getPassword(), newPassword, null));
assertEquals(authorities.size(), loadUpdatedUser.getRoles().size());
updateUser = new JpaUser("unknown", newPassword, org1, provider.getName(), true, authorities);
try {
provider.updateUser(updateUser);
fail("Should throw a NotFoundException");
} catch (NotFoundException e) {
assertTrue("User not found.", true);
}
}
@Test
public void testUpdateUserForbiddenForNonAdminUsers() throws Exception {
JpaUser adminUser = createUserWithRoles(org1, "admin", SecurityConstants.GLOBAL_ADMIN_ROLE);
JpaUser user = createUserWithRoles(org1, "user", "ROLE_USER");
provider.addUser(adminUser);
provider.addUser(user);
provider.setSecurityService(mockSecurityServiceWithUser(user));
// try to add ROLE_USER
Set<JpaRole> updatedRoles = Collections.set(
new JpaRole("ROLE_USER", org1),
new JpaRole(SecurityConstants.GLOBAL_ADMIN_ROLE, org1));
try {
provider.updateUser(new JpaUser(adminUser.getUsername(), adminUser.getPassword(), org1,
adminUser.getName(), true, updatedRoles));
fail("The current user may not edit an admin user");
} catch (UnauthorizedException e) {
// pass
}
// try to remove ROLE_ADMIN
updatedRoles = Collections.set(new JpaRole("ROLE_USER", org1));
try {
provider.updateUser(new JpaUser(adminUser.getUsername(), adminUser.getPassword(), org1,
adminUser.getName(), true, updatedRoles));
fail("The current user may not remove the admin role on other user");
} catch (UnauthorizedException e) {
// pass
}
}
@Test
public void testRoles() throws Exception {
JpaUser userOne = createUserWithRoles(org1, "user1", "ROLE_ONE");
provider.addUser(userOne);
Set<JpaRole> authoritiesTwo = new HashSet<JpaRole>();
authoritiesTwo.add(new JpaRole("ROLE_ONE", org1));
authoritiesTwo.add(new JpaRole("ROLE_TWO", org1));
JpaUser userTwo = createUserWithRoles(org1, "user2", "ROLE_ONE", "ROLE_TWO");
provider.addUser(userTwo);
// The provider is not authoritative for these roles
assertEquals("There should be no roles", 0, IteratorUtils.toList(provider.findRoles("%", Role.Target.ALL, 0, 0)).size());
}
@Test
public void testUsers() throws Exception {
Set<JpaRole> authorities = new HashSet<JpaRole>();
authorities.add(new JpaRole("ROLE_COOL_ONE", org1));
JpaUser userOne = createUserWithRoles(org1, "user_test_1", "ROLE_COOL_ONE");
JpaUser userTwo = createUserWithRoles(org1, "user2", "ROLE_CCOL_ONE");
JpaUser userThree = createUserWithRoles(org1, "user3", "ROLE_COOL_ONE");
JpaUser userFour = createUserWithRoles(org1, "user_test_4", "ROLE_COOL_ONE");
provider.addUser(userOne);
provider.addUser(userTwo);
provider.addUser(userThree);
provider.addUser(userFour);
assertEquals("There should be two roles", 4, IteratorUtils.toList(provider.getUsers()).size());
}
@Test
public void testDuplicateUser() {
Set<JpaRole> authorities1 = set(new JpaRole("ROLE_COOL_ONE", org1));
Set<JpaRole> authorities2 = set(new JpaRole("ROLE_COOL_ONE", org2));
try {
provider.addUser(createUserWithRoles(org1, "user1", "ROLE_COOL_ONE"));
provider.addUser(createUserWithRoles(org1, "user2", "ROLE_COOL_ONE"));
provider.addUser(createUserWithRoles(org2, "user1", "ROLE_COOL_ONE"));
} catch (UnauthorizedException e) {
fail("User should be created");
}
try {
provider.addUser(createUserWithRoles(org1, "user1", "ROLE_COOL_ONE"));
fail("Duplicate user");
} catch (Exception ignore) {
}
}
@Test
public void testRolesForUser() {
JpaRole astroRole = new JpaRole("ROLE_ASTRO_105_SPRING_2013_STUDENT", org1, "Astro role");
provider.addRole(astroRole);
JpaUser userOne = createUserWithRoles(org1, "user1", "ROLE_ONE", "ROLE_TWO");
try {
provider.addUser(userOne);
} catch (UnauthorizedException e) {
fail("User should be created");
}
// Provider not authoritative for these roles
assertEquals("There should be zero roles", 0, IteratorUtils.toList(provider.findRoles("%", Role.Target.ALL, 0, 0)).size());
List<String> rolesForUser = provider.getRolesForUser("user1").stream()
.map(Role::getName)
.sorted()
.collect(Collectors.toList());
assertEquals("There should be two roles", 2, rolesForUser.size());
assertEquals("ROLE_ONE", rolesForUser.get(0));
assertEquals("ROLE_TWO", rolesForUser.get(1));
}
@Test
public void testFindUsers() throws UnauthorizedException {
JpaUser userOne = createUserWithRoles(org1, "user_test_1", "ROLE_COOL_ONE");
JpaUser userTwo = createUserWithRoles(org1, "user2", "ROLE_COOL_ONE");
JpaUser userThree = createUserWithRoles(org1, "user3", "ROLE_COOL_ONE");
JpaUser userFour = createUserWithRoles(org1, "user_test_4", "ROLE_COOL_ONE");
provider.addUser(userOne);
provider.addUser(userTwo);
provider.addUser(userThree);
provider.addUser(userFour);
assertEquals(2, IteratorUtils.toList(provider.findUsers("%tEsT%", 0, 0)).size());
assertEquals(1, IteratorUtils.toList(provider.findUsers("%tEsT%", 0, 1)).size());
User user = provider.findUsers("%tEsT%", 1, 1).next();
assertEquals(userFour, user);
}
@Test
public void testFindRoles() throws UnauthorizedException {
JpaRole astroRole = new JpaRole("ROLE_ASTRO_105_SPRING_2013_STUDENT", org1, "Astro role");
provider.addRole(astroRole);
JpaUser userOne = createUserWithRoles(org1, "user1", "ROLE_COOL_ONE", "ROLE_COOL_TWO");
provider.addUser(userOne);
// We expect findRoles() for this provider to return an empty set,
// as it is not authoritative for roles that it persists.
assertEquals(0, IteratorUtils.toList(provider.findRoles("%coOL%", Role.Target.ALL, 0, 0)).size());
assertEquals(0, IteratorUtils.toList(provider.findRoles("%cOoL%", Role.Target.ALL, 0, 1)).size());
assertEquals(0, IteratorUtils.toList(provider.findRoles("%oLe%", Role.Target.ALL, 0, 0)).size());
assertEquals(0, IteratorUtils.toList(provider.findRoles("%olE%", Role.Target.ALL, 1, 2)).size());
}
private static SecurityService mockSecurityServiceWithUser(User currentUser) {
// Set the security sevice
SecurityService securityService = EasyMock.createNiceMock(SecurityService.class);
EasyMock.expect(securityService.getOrganization()).andReturn(currentUser.getOrganization()).anyTimes();
EasyMock.expect(securityService.getUser()).andReturn(currentUser).anyTimes();
EasyMock.replay(securityService);
return securityService;
}
private static JpaUser createUserWithRoles(JpaOrganization org, String username, String... roles) {
Set<JpaRole> userRoles = new HashSet<>();
for (String adminRole : roles) {
userRoles.add(new JpaRole(adminRole, org));
}
return new JpaUser(username, "pass1", org, "opencast", true, userRoles);
}
}
| ./CrossVul/dataset_final_sorted/CWE-327/java/good_4532_6 |
crossvul-java_data_good_4532_5 | /**
* 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.userdirectory.endpoint;
import static org.apache.http.HttpStatus.SC_BAD_REQUEST;
import static org.apache.http.HttpStatus.SC_CONFLICT;
import static org.apache.http.HttpStatus.SC_CREATED;
import static org.apache.http.HttpStatus.SC_FORBIDDEN;
import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR;
import static org.apache.http.HttpStatus.SC_NOT_FOUND;
import static org.apache.http.HttpStatus.SC_OK;
import static org.opencastproject.util.RestUtil.getEndpointUrl;
import static org.opencastproject.util.UrlSupport.uri;
import static org.opencastproject.util.doc.rest.RestParameter.Type.STRING;
import org.opencastproject.security.api.JaxbUser;
import org.opencastproject.security.api.JaxbUserList;
import org.opencastproject.security.api.SecurityService;
import org.opencastproject.security.api.UnauthorizedException;
import org.opencastproject.security.api.User;
import org.opencastproject.security.impl.jpa.JpaOrganization;
import org.opencastproject.security.impl.jpa.JpaRole;
import org.opencastproject.security.impl.jpa.JpaUser;
import org.opencastproject.userdirectory.JpaUserAndRoleProvider;
import org.opencastproject.util.NotFoundException;
import org.opencastproject.util.UrlSupport;
import org.opencastproject.util.data.Tuple;
import org.opencastproject.util.doc.rest.RestParameter;
import org.opencastproject.util.doc.rest.RestQuery;
import org.opencastproject.util.doc.rest.RestResponse;
import org.opencastproject.util.doc.rest.RestService;
import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* Provides a sorted set of known users
*/
@Path("/")
@RestService(
name = "UsersUtils",
title = "User utils",
notes = "This service offers the default CRUD Operations for the internal Opencast users.",
abstractText = "Provides operations for internal Opencast users")
public class UserEndpoint {
/** The logger */
private static final Logger logger = LoggerFactory.getLogger(UserEndpoint.class);
private JpaUserAndRoleProvider jpaUserAndRoleProvider;
private SecurityService securityService;
private String endpointBaseUrl;
/** OSGi callback. */
public void activate(ComponentContext cc) {
logger.info("Start users endpoint");
final Tuple<String, String> endpointUrl = getEndpointUrl(cc);
endpointBaseUrl = UrlSupport.concat(endpointUrl.getA(), endpointUrl.getB());
}
/**
* @param securityService
* the securityService to set
*/
public void setSecurityService(SecurityService securityService) {
this.securityService = securityService;
}
/**
* @param jpaUserAndRoleProvider
* the persistenceProperties to set
*/
public void setJpaUserAndRoleProvider(JpaUserAndRoleProvider jpaUserAndRoleProvider) {
this.jpaUserAndRoleProvider = jpaUserAndRoleProvider;
}
@GET
@Path("users.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(
name = "allusersasjson",
description = "Returns a list of users",
returnDescription = "Returns a JSON representation of the list of user accounts",
restParameters = {
@RestParameter(
name = "limit",
defaultValue = "100",
description = "The maximum number of items to return per page.",
isRequired = false,
type = RestParameter.Type.STRING),
@RestParameter(
name = "offset",
defaultValue = "0",
description = "The page number.",
isRequired = false,
type = RestParameter.Type.STRING)
}, reponses = {
@RestResponse(
responseCode = SC_OK,
description = "The user accounts.")
})
public JaxbUserList getUsersAsJson(@QueryParam("limit") int limit, @QueryParam("offset") int offset)
throws IOException {
// Set the maximum number of items to return to 100 if this limit parameter is not given
if (limit < 1) {
limit = 100;
}
JaxbUserList userList = new JaxbUserList();
for (Iterator<User> i = jpaUserAndRoleProvider.findUsers("%", offset, limit); i.hasNext();) {
userList.add(i.next());
}
return userList;
}
@GET
@Path("{username}.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(
name = "user",
description = "Returns a user",
returnDescription = "Returns a JSON representation of a user",
pathParameters = {
@RestParameter(
name = "username",
description = "The username.",
isRequired = true,
type = STRING)
}, reponses = {
@RestResponse(
responseCode = SC_OK,
description = "The user account."),
@RestResponse(
responseCode = SC_NOT_FOUND,
description = "User not found")
})
public Response getUserAsJson(@PathParam("username") String username) throws NotFoundException {
User user = jpaUserAndRoleProvider.loadUser(username);
if (user == null) {
logger.debug("Requested user not found: {}", username);
return Response.status(SC_NOT_FOUND).build();
}
return Response.ok(JaxbUser.fromUser(user)).build();
}
@GET
@Path("users/md5.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(
name = "users-with-insecure-hashing",
description = "Returns a list of users which passwords are stored using MD5 hashes",
returnDescription = "Returns a JSON representation of the list of matching user accounts",
reponses = {
@RestResponse(
responseCode = SC_OK,
description = "The user accounts.")
})
public JaxbUserList getUserWithInsecurePasswordHashingAsJson() {
JaxbUserList userList = new JaxbUserList();
for (User user: jpaUserAndRoleProvider.findInsecurePasswordHashes()) {
userList.add(user);
}
return userList;
}
@POST
@Path("/")
@RestQuery(
name = "createUser",
description = "Create a new user",
returnDescription = "Location of the new ressource",
restParameters = {
@RestParameter(
name = "username",
description = "The username.",
isRequired = true,
type = STRING),
@RestParameter(
name = "password",
description = "The password.",
isRequired = true,
type = STRING),
@RestParameter(
name = "name",
description = "The name.",
isRequired = false,
type = STRING),
@RestParameter(
name = "email",
description = "The email.",
isRequired = false,
type = STRING),
@RestParameter(
name = "roles",
description = "The user roles as a json array, for example: [\"ROLE_USER\", \"ROLE_ADMIN\"]",
isRequired = false,
type = STRING)
}, reponses = {
@RestResponse(
responseCode = SC_BAD_REQUEST,
description = "Malformed request syntax."),
@RestResponse(
responseCode = SC_CREATED,
description = "User has been created."),
@RestResponse(
responseCode = SC_CONFLICT,
description = "An user with this username already exist."),
@RestResponse(
responseCode = SC_FORBIDDEN,
description = "Not enough permissions to create a user with the admin role.")
})
public Response createUser(@FormParam("username") String username, @FormParam("password") String password,
@FormParam("name") String name, @FormParam("email") String email, @FormParam("roles") String roles) {
if (jpaUserAndRoleProvider.loadUser(username) != null) {
return Response.status(SC_CONFLICT).build();
}
try {
Set<JpaRole> rolesSet = parseRoles(roles);
/* Add new user */
logger.debug("Updating user {}", username);
JpaOrganization organization = (JpaOrganization) securityService.getOrganization();
JpaUser user = new JpaUser(username, password, organization, name, email, jpaUserAndRoleProvider.getName(), true,
rolesSet);
try {
jpaUserAndRoleProvider.addUser(user);
return Response.created(uri(endpointBaseUrl, user.getUsername() + ".json")).build();
} catch (UnauthorizedException ex) {
logger.debug("Create user failed", ex);
return Response.status(Response.Status.FORBIDDEN).build();
}
} catch (IllegalArgumentException e) {
logger.debug("Request with malformed ROLE data: {}", roles);
return Response.status(SC_BAD_REQUEST).build();
}
}
@PUT
@Path("{username}.json")
@RestQuery(
name = "updateUser",
description = "Update an user",
returnDescription = "Status ok",
restParameters = {
@RestParameter(
name = "password",
description = "The password.",
isRequired = true,
type = STRING),
@RestParameter(
name = "name",
description = "The name.",
isRequired = false,
type = STRING),
@RestParameter(
name = "email",
description = "The email.",
isRequired = false,
type = STRING),
@RestParameter(
name = "roles",
description = "The user roles as a json array, for example: [\"ROLE_USER\", \"ROLE_ADMIN\"]",
isRequired = false,
type = STRING)
}, pathParameters = @RestParameter(
name = "username",
description = "The username",
isRequired = true,
type = STRING),
reponses = {
@RestResponse(
responseCode = SC_BAD_REQUEST,
description = "Malformed request syntax."),
@RestResponse(
responseCode = SC_FORBIDDEN,
description = "Not enough permissions to update a user with the admin role."),
@RestResponse(
responseCode = SC_OK,
description = "User has been updated.") })
public Response setUser(@PathParam("username") String username, @FormParam("password") String password,
@FormParam("name") String name, @FormParam("email") String email, @FormParam("roles") String roles) {
try {
User user = jpaUserAndRoleProvider.loadUser(username);
if (user == null) {
return createUser(username, password, name, email, roles);
}
Set<JpaRole> rolesSet = parseRoles(roles);
logger.debug("Updating user {}", username);
JpaOrganization organization = (JpaOrganization) securityService.getOrganization();
jpaUserAndRoleProvider.updateUser(new JpaUser(username, password, organization, name, email,
jpaUserAndRoleProvider.getName(), true, rolesSet));
return Response.status(SC_OK).build();
} catch (NotFoundException e) {
logger.debug("User {} not found.", username);
return Response.status(SC_NOT_FOUND).build();
} catch (UnauthorizedException e) {
logger.debug("Update user failed", e);
return Response.status(Response.Status.FORBIDDEN).build();
} catch (IllegalArgumentException e) {
logger.debug("Request with malformed ROLE data: {}", roles);
return Response.status(SC_BAD_REQUEST).build();
}
}
@DELETE
@Path("{username}.json")
@RestQuery(
name = "deleteUser",
description = "Delete a new user",
returnDescription = "Status ok",
pathParameters = @RestParameter(
name = "username",
type = STRING,
isRequired = true,
description = "The username"),
reponses = {
@RestResponse(
responseCode = SC_OK,
description = "User has been deleted."),
@RestResponse(
responseCode = SC_FORBIDDEN,
description = "Not enough permissions to delete a user with the admin role."),
@RestResponse(
responseCode = SC_NOT_FOUND,
description = "User not found.")
})
public Response deleteUser(@PathParam("username") String username) {
try {
jpaUserAndRoleProvider.deleteUser(username, securityService.getOrganization().getId());
} catch (NotFoundException e) {
logger.debug("User {} not found.", username);
return Response.status(SC_NOT_FOUND).build();
} catch (UnauthorizedException e) {
logger.debug("Error during deletion of user {}: {}", username, e);
return Response.status(SC_FORBIDDEN).build();
} catch (Exception e) {
logger.error("Error during deletion of user {}: {}", username, e);
return Response.status(SC_INTERNAL_SERVER_ERROR).build();
}
logger.debug("User {} removed.", username);
return Response.status(SC_OK).build();
}
/**
* Parse JSON roles array.
*
* @param roles
* String representation of JSON array containing roles
*/
private Set<JpaRole> parseRoles(String roles) throws IllegalArgumentException {
JSONArray rolesArray = null;
/* Try parsing JSON. Return Bad Request if malformed. */
try {
rolesArray = (JSONArray) JSONValue.parseWithException(StringUtils.isEmpty(roles) ? "[]" : roles);
} catch (Exception e) {
throw new IllegalArgumentException("Error parsing JSON array", e);
}
Set<JpaRole> rolesSet = new HashSet<JpaRole>();
/* Add given roles */
for (Object role : rolesArray) {
try {
rolesSet.add(new JpaRole((String) role, (JpaOrganization) securityService.getOrganization()));
} catch (ClassCastException e) {
throw new IllegalArgumentException("Error parsing array vales as String", e);
}
}
return rolesSet;
}
}
| ./CrossVul/dataset_final_sorted/CWE-327/java/good_4532_5 |
crossvul-java_data_good_4532_3 | /**
* 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.kernel.security;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCrypt;
/**
*
*/
public class CustomPasswordEncoder implements PasswordEncoder {
private Logger logger = LoggerFactory.getLogger(CustomPasswordEncoder.class);
/**
* Encode the raw password for storage using BCrypt.
* @param rawPassword raw password to encrypt/hash
* @return hashed password
*/
public String encodePassword(final String rawPassword) {
return encodePassword(rawPassword, null);
}
/**
* Encode the raw password for storage using BCrypt.
* @param rawPassword raw password to encrypt/hash
* @param ignored This parameter will not be used. A random salt is generated by BCrypt.
* @return hashed password
*/
@Override
public String encodePassword(final String rawPassword, final Object ignored) {
return BCrypt.hashpw(rawPassword, BCrypt.gensalt());
}
/**
* Verify the encoded password obtained from storage matches the submitted raw
* password after it too is encoded. Returns true if the passwords match, false if
* they do not. The stored password itself is never decoded.
*
* @param rawPassword the raw password to encode and match
* @param encodedPassword the encoded password from storage to compare with
* @return true if the raw password, after encoding, matches the encoded password from storage
*/
@Override
public boolean isPasswordValid(String encodedPassword, String rawPassword, Object salt) {
// Test MD5 encoded hash
if (encodedPassword.length() == 32) {
final String hash = md5Encode(rawPassword, salt);
logger.debug("Checking md5 hashed password '{}' against encoded password '{}'", hash, encodedPassword);
return hash.equals(encodedPassword);
}
// Test BCrypt encoded hash
logger.debug("Verifying BCrypt hash {}", encodedPassword);
return BCrypt.checkpw(rawPassword, encodedPassword);
}
/**
* Encode a clear text password using Opencast's legacy MD5 based hashing with salt.
* The username was used as salt for this.
*
* @param clearText
* the password
* @param salt
* the salt
* @return the hashed password
* @throws IllegalArgumentException
* if clearText or salt are null
*/
public static String md5Encode(String clearText, Object salt) throws IllegalArgumentException {
if (clearText == null || salt == null)
throw new IllegalArgumentException("clearText and salt must not be null");
return DigestUtils.md5Hex(clearText + "{" + salt.toString() + "}");
}
}
| ./CrossVul/dataset_final_sorted/CWE-327/java/good_4532_3 |
crossvul-java_data_bad_28_0 | package org.bouncycastle.crypto.generators;
import java.math.BigInteger;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator;
import org.bouncycastle.crypto.KeyGenerationParameters;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import org.bouncycastle.math.Primes;
import org.bouncycastle.math.ec.WNafUtil;
/**
* an RSA key pair generator.
*/
public class RSAKeyPairGenerator
implements AsymmetricCipherKeyPairGenerator
{
private static final BigInteger ONE = BigInteger.valueOf(1);
private RSAKeyGenerationParameters param;
public void init(KeyGenerationParameters param)
{
this.param = (RSAKeyGenerationParameters)param;
}
public AsymmetricCipherKeyPair generateKeyPair()
{
AsymmetricCipherKeyPair result = null;
boolean done = false;
//
// p and q values should have a length of half the strength in bits
//
int strength = param.getStrength();
int pbitlength = (strength + 1) / 2;
int qbitlength = strength - pbitlength;
int mindiffbits = (strength / 2) - 100;
if (mindiffbits < strength / 3)
{
mindiffbits = strength / 3;
}
int minWeight = strength >> 2;
// d lower bound is 2^(strength / 2)
BigInteger dLowerBound = BigInteger.valueOf(2).pow(strength / 2);
// squared bound (sqrt(2)*2^(nlen/2-1))^2
BigInteger squaredBound = ONE.shiftLeft(strength - 1);
// 2^(nlen/2 - 100)
BigInteger minDiff = ONE.shiftLeft(mindiffbits);
while (!done)
{
BigInteger p, q, n, d, e, pSub1, qSub1, gcd, lcm;
e = param.getPublicExponent();
p = chooseRandomPrime(pbitlength, e, squaredBound);
//
// generate a modulus of the required length
//
for (; ; )
{
q = chooseRandomPrime(qbitlength, e, squaredBound);
// p and q should not be too close together (or equal!)
BigInteger diff = q.subtract(p).abs();
if (diff.bitLength() < mindiffbits || diff.compareTo(minDiff) <= 0)
{
continue;
}
//
// calculate the modulus
//
n = p.multiply(q);
if (n.bitLength() != strength)
{
//
// if we get here our primes aren't big enough, make the largest
// of the two p and try again
//
p = p.max(q);
continue;
}
/*
* Require a minimum weight of the NAF representation, since low-weight composites may
* be weak against a version of the number-field-sieve for factoring.
*
* See "The number field sieve for integers of low weight", Oliver Schirokauer.
*/
if (WNafUtil.getNafWeight(n) < minWeight)
{
p = chooseRandomPrime(pbitlength, e, squaredBound);
continue;
}
break;
}
if (p.compareTo(q) < 0)
{
gcd = p;
p = q;
q = gcd;
}
pSub1 = p.subtract(ONE);
qSub1 = q.subtract(ONE);
gcd = pSub1.gcd(qSub1);
lcm = pSub1.divide(gcd).multiply(qSub1);
//
// calculate the private exponent
//
d = e.modInverse(lcm);
if (d.compareTo(dLowerBound) <= 0)
{
continue;
}
else
{
done = true;
}
//
// calculate the CRT factors
//
BigInteger dP, dQ, qInv;
dP = d.remainder(pSub1);
dQ = d.remainder(qSub1);
qInv = q.modInverse(p);
result = new AsymmetricCipherKeyPair(
new RSAKeyParameters(false, n, e),
new RSAPrivateCrtKeyParameters(n, e, d, p, q, dP, dQ, qInv));
}
return result;
}
/**
* Choose a random prime value for use with RSA
*
* @param bitlength the bit-length of the returned prime
* @param e the RSA public exponent
* @return A prime p, with (p-1) relatively prime to e
*/
protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger sqrdBound)
{
int iterations = getNumberOfIterations(bitlength, param.getCertainty());
for (int i = 0; i != 5 * bitlength; i++)
{
BigInteger p = new BigInteger(bitlength, 1, param.getRandom());
if (p.mod(e).equals(ONE))
{
continue;
}
if (p.multiply(p).compareTo(sqrdBound) < 0)
{
continue;
}
if (!isProbablePrime(p, iterations))
{
continue;
}
if (!e.gcd(p.subtract(ONE)).equals(ONE))
{
continue;
}
return p;
}
throw new IllegalStateException("unable to generate prime number for RSA key");
}
protected boolean isProbablePrime(BigInteger x, int iterations)
{
/*
* Primes class for FIPS 186-4 C.3 primality checking
*/
return !Primes.hasAnySmallFactors(x) && Primes.isMRProbablePrime(x, param.getRandom(), iterations);
}
private static int getNumberOfIterations(int bits, int certainty)
{
/*
* NOTE: We enforce a minimum 'certainty' of 100 for bits >= 1024 (else 80). Where the
* certainty is higher than the FIPS 186-4 tables (C.2/C.3) cater to, extra iterations
* are added at the "worst case rate" for the excess.
*/
if (bits >= 1536)
{
return certainty <= 100 ? 3
: certainty <= 128 ? 4
: 4 + (certainty - 128 + 1) / 2;
}
else if (bits >= 1024)
{
return certainty <= 100 ? 4
: certainty <= 112 ? 5
: 5 + (certainty - 112 + 1) / 2;
}
else if (bits >= 512)
{
return certainty <= 80 ? 5
: certainty <= 100 ? 7
: 7 + (certainty - 100 + 1) / 2;
}
else
{
return certainty <= 80 ? 40
: 40 + (certainty - 80 + 1) / 2;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-327/java/bad_28_0 |
crossvul-java_data_good_4532_4 | /**
* 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.userdirectory;
import org.opencastproject.kernel.security.CustomPasswordEncoder;
import org.opencastproject.security.api.Group;
import org.opencastproject.security.api.Role;
import org.opencastproject.security.api.RoleProvider;
import org.opencastproject.security.api.SecurityService;
import org.opencastproject.security.api.UnauthorizedException;
import org.opencastproject.security.api.User;
import org.opencastproject.security.api.UserProvider;
import org.opencastproject.security.impl.jpa.JpaOrganization;
import org.opencastproject.security.impl.jpa.JpaRole;
import org.opencastproject.security.impl.jpa.JpaUser;
import org.opencastproject.userdirectory.utils.UserDirectoryUtils;
import org.opencastproject.util.NotFoundException;
import org.opencastproject.util.data.Monadics;
import org.opencastproject.util.data.Option;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.apache.commons.lang3.StringUtils;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
/**
* Manages and locates users using JPA.
*/
public class JpaUserAndRoleProvider implements UserProvider, RoleProvider {
/** The logger */
private static final Logger logger = LoggerFactory.getLogger(JpaUserAndRoleProvider.class);
public static final String PERSISTENCE_UNIT = "org.opencastproject.common";
/** The user provider name */
public static final String PROVIDER_NAME = "opencast";
/** Username constant used in JSON formatted users */
public static final String USERNAME = "username";
/** Role constant used in JSON formatted users */
public static final String ROLES = "roles";
/** Encoding expected from all inputs */
public static final String ENCODING = "UTF-8";
/** The delimiter for the User cache */
private static final String DELIMITER = ";==;";
/** The security service */
protected SecurityService securityService = null;
/** Group provider */
protected JpaGroupRoleProvider groupRoleProvider;
/** A cache of users, which lightens the load on the SQL server */
private LoadingCache<String, Object> cache = null;
/** A token to store in the miss cache */
protected Object nullToken = new Object();
/** Password encoder for storing user passwords */
private CustomPasswordEncoder passwordEncoder = new CustomPasswordEncoder();
/** OSGi DI */
void setEntityManagerFactory(EntityManagerFactory emf) {
this.emf = emf;
}
/**
* @param securityService
* the securityService to set
*/
public void setSecurityService(SecurityService securityService) {
this.securityService = securityService;
}
/**
* @param groupRoleProvider
* the groupRoleProvider to set
*/
void setGroupRoleProvider(JpaGroupRoleProvider groupRoleProvider) {
this.groupRoleProvider = groupRoleProvider;
}
/** The factory used to generate the entity manager */
protected EntityManagerFactory emf = null;
/**
* Callback for activation of this component.
*
* @param cc
* the component context
*/
public void activate(ComponentContext cc) {
logger.debug("activate");
// Setup the caches
cache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).build(new CacheLoader<String, Object>() {
@Override
public Object load(String id) {
String[] key = id.split(DELIMITER);
logger.trace("Loading user '{}':'{}' from database", key[0], key[1]);
User user = loadUser(key[0], key[1]);
return user == null ? nullToken : user;
}
});
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.RoleProvider#getRolesForUser(String)
*/
@Override
public List<Role> getRolesForUser(String userName) {
ArrayList<Role> roles = new ArrayList<Role>();
User user = loadUser(userName);
if (user == null)
return roles;
roles.addAll(user.getRoles());
return roles;
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.UserProvider#findUsers(String, int, int)
*/
@Override
public Iterator<User> findUsers(String query, int offset, int limit) {
if (query == null)
throw new IllegalArgumentException("Query must be set");
String orgId = securityService.getOrganization().getId();
List<JpaUser> users = UserDirectoryPersistenceUtil.findUsersByQuery(orgId, query, limit, offset, emf);
return Monadics.mlist(users).map(addProviderName).iterator();
}
@Override
public Iterator<User> findUsers(Collection<String> userNames) {
String orgId = securityService.getOrganization().getId();
List<JpaUser> users = UserDirectoryPersistenceUtil.findUsersByUserName(userNames, orgId, emf);
return Monadics.mlist(users).map(addProviderName).iterator();
}
/**
* List all users with insecure password hashes
*/
public List<User> findInsecurePasswordHashes() {
final String orgId = securityService.getOrganization().getId();
EntityManager em = null;
try {
em = emf.createEntityManager();
TypedQuery<User> q = em.createNamedQuery("User.findInsecureHash", User.class);
q.setParameter("org", orgId);
return q.getResultList();
} finally {
if (em != null)
em.close();
}
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.RoleProvider#findRoles(String, Role.Target, int, int)
*/
@Override
public Iterator<Role> findRoles(String query, Role.Target target, int offset, int limit) {
if (query == null)
throw new IllegalArgumentException("Query must be set");
// This provider persists roles but is not authoritative for any roles, so return an empty set
return new ArrayList<Role>().iterator();
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.UserProvider#loadUser(java.lang.String)
*/
@Override
public User loadUser(String userName) {
String orgId = securityService.getOrganization().getId();
Object user = cache.getUnchecked(userName.concat(DELIMITER).concat(orgId));
if (user == nullToken) {
return null;
} else {
return (User) user;
}
}
@Override
public Iterator<User> getUsers() {
String orgId = securityService.getOrganization().getId();
List<JpaUser> users = UserDirectoryPersistenceUtil.findUsers(orgId, 0, 0, emf);
return Monadics.mlist(users).map(addProviderName).iterator();
}
/**
* {@inheritDoc}
*
* @see org.opencastproject.security.api.UserProvider#getOrganization()
*/
@Override
public String getOrganization() {
return ALL_ORGANIZATIONS;
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getClass().getName();
}
/**
* Loads a user from persistence
*
* @param userName
* the user name
* @param organization
* the organization id
* @return the loaded user or <code>null</code> if not found
*/
public User loadUser(String userName, String organization) {
JpaUser user = UserDirectoryPersistenceUtil.findUser(userName, organization, emf);
return Option.option(user).map(addProviderName).getOrElseNull();
}
/**
* Loads a user from persistence
*
* @param userId
* the user's id
* @param organization
* the organization id
* @return the loaded user or <code>null</code> if not found
*/
public User loadUser(long userId, String organization) {
JpaUser user = UserDirectoryPersistenceUtil.findUser(userId, organization, emf);
return Option.option(user).map(addProviderName).getOrElseNull();
}
/**
* Adds a user to the persistence
*
* @param user
* the user to add
*
* @throws org.opencastproject.security.api.UnauthorizedException
* if the user is not allowed to create other user with the given roles
*/
public void addUser(JpaUser user) throws UnauthorizedException {
addUser(user, false);
}
/**
* Adds a user to the persistence
*
* @param user
* the user to add
* @param passwordEncoded
* if the password is already encoded or should be encoded
*
* @throws org.opencastproject.security.api.UnauthorizedException
* if the user is not allowed to create other user with the given roles
*/
public void addUser(JpaUser user, final boolean passwordEncoded) throws UnauthorizedException {
if (!UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, user.getRoles()))
throw new UnauthorizedException("The user is not allowed to set the admin role on other users");
// Create a JPA user with an encoded password.
String encodedPassword = passwordEncoded ? user.getPassword() : passwordEncoder.encodePassword(user.getPassword());
// Only save internal roles
Set<JpaRole> roles = UserDirectoryPersistenceUtil.saveRoles(filterRoles(user.getRoles()), emf);
JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization(
(JpaOrganization) user.getOrganization(), emf);
JpaUser newUser = new JpaUser(user.getUsername(), encodedPassword, organization, user.getName(), user.getEmail(),
user.getProvider(), user.isManageable(), roles);
// Then save the user
EntityManager em = null;
EntityTransaction tx = null;
try {
em = emf.createEntityManager();
tx = em.getTransaction();
tx.begin();
em.persist(newUser);
tx.commit();
cache.put(user.getUsername() + DELIMITER + user.getOrganization().getId(), newUser);
} finally {
if (tx.isActive()) {
tx.rollback();
}
if (em != null)
em.close();
}
updateGroupMembership(user);
}
/**
* Updates a user to the persistence
*
* @param user
* the user to save
* @throws NotFoundException
* @throws org.opencastproject.security.api.UnauthorizedException
* if the current user is not allowed to update user with the given roles
*/
public User updateUser(JpaUser user) throws NotFoundException, UnauthorizedException {
return updateUser(user, false);
}
/**
* Updates a user to the persistence
*
* @param user
* the user to save
* @param passwordEncoded
* if the password is already encoded or should be encoded
* @throws NotFoundException
* @throws org.opencastproject.security.api.UnauthorizedException
* if the current user is not allowed to update user with the given roles
*/
public User updateUser(JpaUser user, final boolean passwordEncoded) 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.
if (passwordEncoded) {
encodedPassword = user.getPassword();
} else {
encodedPassword = passwordEncoder.encodePassword(user.getPassword());
}
}
// 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;
}
/**
* Select only internal roles
*
* @param userRoles
* the user's full set of roles
*/
private Set<JpaRole> filterRoles(Set<Role> userRoles) {
Set<JpaRole> roles = new HashSet<JpaRole>();
for (Role role : userRoles) {
if (Role.Type.INTERNAL.equals(role.getType()) && !role.getName().startsWith(Group.ROLE_PREFIX)) {
JpaRole jpaRole = (JpaRole) role;
roles.add(jpaRole);
}
}
return roles;
}
/**
* Updates a user's groups based on assigned roles
*
* @param user
* the user for whom groups should be updated
* @throws NotFoundException
*/
private void updateGroupMembership(JpaUser user) {
logger.debug("updateGroupMembership({}, roles={})", user.getUsername(), user.getRoles().size());
List<String> internalGroupRoles = new ArrayList<String>();
for (Role role : user.getRoles()) {
if (Role.Type.GROUP.equals(role.getType())
|| (Role.Type.INTERNAL.equals(role.getType()) && role.getName().startsWith(Group.ROLE_PREFIX))) {
internalGroupRoles.add(role.getName());
}
}
groupRoleProvider.updateGroupMembershipFromRoles(user.getUsername(), user.getOrganization().getId(), internalGroupRoles);
}
/**
* Delete the given user
*
* @param username
* the name of the user to delete
* @param orgId
* the organization id
* @throws NotFoundException
* if the requested user is not exist
* @throws org.opencastproject.security.api.UnauthorizedException
* if you havn't permissions to delete an admin user (only admins may do that)
* @throws Exception
*/
public void deleteUser(String username, String orgId) throws NotFoundException, UnauthorizedException, Exception {
User user = loadUser(username, orgId);
if (user != null && !UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, user.getRoles()))
throw new UnauthorizedException("The user is not allowed to delete an admin user");
// Remove the user's group membership
groupRoleProvider.updateGroupMembershipFromRoles(username, orgId, new ArrayList<String>());
// Remove the user
UserDirectoryPersistenceUtil.deleteUser(username, orgId, emf);
cache.invalidate(username + DELIMITER + orgId);
}
/**
* Adds a role to the persistence
*
* @param jpaRole
* the role
*/
public void addRole(JpaRole jpaRole) {
HashSet<JpaRole> roles = new HashSet<JpaRole>();
roles.add(jpaRole);
UserDirectoryPersistenceUtil.saveRoles(roles, emf);
}
@Override
public String getName() {
return PROVIDER_NAME;
}
private static org.opencastproject.util.data.Function<JpaUser, User> addProviderName = new org.opencastproject.util.data.Function<JpaUser, User>() {
@Override
public User apply(JpaUser a) {
a.setProvider(PROVIDER_NAME);
return a;
}
};
@Override
public long countUsers() {
String orgId = securityService.getOrganization().getId();
return UserDirectoryPersistenceUtil.countUsers(orgId, emf);
}
@Override
public void invalidate(String userName) {
String orgId = securityService.getOrganization().getId();
cache.invalidate(userName + DELIMITER + orgId);
}
}
| ./CrossVul/dataset_final_sorted/CWE-327/java/good_4532_4 |
crossvul-java_data_good_29_0 | package org.bouncycastle.crypto.generators;
import java.math.BigInteger;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator;
import org.bouncycastle.crypto.KeyGenerationParameters;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import org.bouncycastle.math.Primes;
import org.bouncycastle.math.ec.WNafUtil;
/**
* an RSA key pair generator.
*/
public class RSAKeyPairGenerator
implements AsymmetricCipherKeyPairGenerator
{
private static final BigInteger ONE = BigInteger.valueOf(1);
private RSAKeyGenerationParameters param;
public void init(KeyGenerationParameters param)
{
this.param = (RSAKeyGenerationParameters)param;
}
public AsymmetricCipherKeyPair generateKeyPair()
{
AsymmetricCipherKeyPair result = null;
boolean done = false;
//
// p and q values should have a length of half the strength in bits
//
int strength = param.getStrength();
int pbitlength = (strength + 1) / 2;
int qbitlength = strength - pbitlength;
int mindiffbits = (strength / 2) - 100;
if (mindiffbits < strength / 3)
{
mindiffbits = strength / 3;
}
int minWeight = strength >> 2;
// d lower bound is 2^(strength / 2)
BigInteger dLowerBound = BigInteger.valueOf(2).pow(strength / 2);
// squared bound (sqrt(2)*2^(nlen/2-1))^2
BigInteger squaredBound = ONE.shiftLeft(strength - 1);
// 2^(nlen/2 - 100)
BigInteger minDiff = ONE.shiftLeft(mindiffbits);
while (!done)
{
BigInteger p, q, n, d, e, pSub1, qSub1, gcd, lcm;
e = param.getPublicExponent();
p = chooseRandomPrime(pbitlength, e, squaredBound);
//
// generate a modulus of the required length
//
for (; ; )
{
q = chooseRandomPrime(qbitlength, e, squaredBound);
// p and q should not be too close together (or equal!)
BigInteger diff = q.subtract(p).abs();
if (diff.bitLength() < mindiffbits || diff.compareTo(minDiff) <= 0)
{
continue;
}
//
// calculate the modulus
//
n = p.multiply(q);
if (n.bitLength() != strength)
{
//
// if we get here our primes aren't big enough, make the largest
// of the two p and try again
//
p = p.max(q);
continue;
}
/*
* Require a minimum weight of the NAF representation, since low-weight composites may
* be weak against a version of the number-field-sieve for factoring.
*
* See "The number field sieve for integers of low weight", Oliver Schirokauer.
*/
if (WNafUtil.getNafWeight(n) < minWeight)
{
p = chooseRandomPrime(pbitlength, e, squaredBound);
continue;
}
break;
}
if (p.compareTo(q) < 0)
{
gcd = p;
p = q;
q = gcd;
}
pSub1 = p.subtract(ONE);
qSub1 = q.subtract(ONE);
gcd = pSub1.gcd(qSub1);
lcm = pSub1.divide(gcd).multiply(qSub1);
//
// calculate the private exponent
//
d = e.modInverse(lcm);
if (d.compareTo(dLowerBound) <= 0)
{
continue;
}
else
{
done = true;
}
//
// calculate the CRT factors
//
BigInteger dP, dQ, qInv;
dP = d.remainder(pSub1);
dQ = d.remainder(qSub1);
qInv = q.modInverse(p);
result = new AsymmetricCipherKeyPair(
new RSAKeyParameters(false, n, e),
new RSAPrivateCrtKeyParameters(n, e, d, p, q, dP, dQ, qInv));
}
return result;
}
/**
* Choose a random prime value for use with RSA
*
* @param bitlength the bit-length of the returned prime
* @param e the RSA public exponent
* @return A prime p, with (p-1) relatively prime to e
*/
protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger sqrdBound)
{
int iterations = getNumberOfIterations(bitlength, param.getCertainty());
for (int i = 0; i != 5 * bitlength; i++)
{
BigInteger p = new BigInteger(bitlength, 1, param.getRandom());
if (p.mod(e).equals(ONE))
{
continue;
}
if (p.multiply(p).compareTo(sqrdBound) < 0)
{
continue;
}
if (!isProbablePrime(p, iterations))
{
continue;
}
if (!e.gcd(p.subtract(ONE)).equals(ONE))
{
continue;
}
return p;
}
throw new IllegalStateException("unable to generate prime number for RSA key");
}
protected boolean isProbablePrime(BigInteger x, int iterations)
{
/*
* Primes class for FIPS 186-4 C.3 primality checking
*/
return !Primes.hasAnySmallFactors(x) && Primes.isMRProbablePrime(x, param.getRandom(), iterations);
}
private static int getNumberOfIterations(int bits, int certainty)
{
/*
* NOTE: We enforce a minimum 'certainty' of 100 for bits >= 1024 (else 80). Where the
* certainty is higher than the FIPS 186-4 tables (C.2/C.3) cater to, extra iterations
* are added at the "worst case rate" for the excess.
*/
if (bits >= 1536)
{
return certainty <= 100 ? 3
: certainty <= 128 ? 4
: 4 + (certainty - 128 + 1) / 2;
}
else if (bits >= 1024)
{
return certainty <= 100 ? 4
: certainty <= 112 ? 5
: 5 + (certainty - 112 + 1) / 2;
}
else if (bits >= 512)
{
return certainty <= 80 ? 5
: certainty <= 100 ? 7
: 7 + (certainty - 100 + 1) / 2;
}
else
{
return certainty <= 80 ? 40
: 40 + (certainty - 80 + 1) / 2;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-327/java/good_29_0 |
crossvul-java_data_good_4532_2 | /**
* 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.util;
import org.apache.commons.codec.digest.DigestUtils;
/**
* A password encoder that md5 hashes a password with a salt.
*/
public final class PasswordEncoder {
/**
* Private constructor to disallow construction of this utility class.
*/
private PasswordEncoder() {
}
/**
* Encode a clear text password.
*
* @param clearText
* the password
* @param salt
* the salt. See http://en.wikipedia.org/wiki/Salt_%28cryptography%29
* @return the encoded password
* @throws IllegalArgumentException
* if clearText or salt are null
*/
public static String encode(String clearText, Object salt) throws IllegalArgumentException {
if (clearText == null || salt == null)
throw new IllegalArgumentException("clearText and salt must not be null");
return DigestUtils.md5Hex(clearText + "{" + salt.toString() + "}");
}
}
| ./CrossVul/dataset_final_sorted/CWE-327/java/good_4532_2 |
crossvul-java_data_good_2398_1 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Jean-Baptiste Quenot, Tom Huybrechts
*
* 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;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
import com.thoughtworks.xstream.core.JVM;
import com.trilead.ssh2.util.IOUtils;
import hudson.model.Hudson;
import hudson.util.BootFailure;
import jenkins.model.Jenkins;
import hudson.util.HudsonIsLoading;
import hudson.util.IncompatibleServletVersionDetected;
import hudson.util.IncompatibleVMDetected;
import hudson.util.InsufficientPermissionDetected;
import hudson.util.NoHomeDir;
import hudson.util.RingBufferLogHandler;
import hudson.util.NoTempDir;
import hudson.util.IncompatibleAntVersionDetected;
import hudson.util.HudsonFailedToLoad;
import hudson.util.ChartUtil;
import hudson.util.AWTProblem;
import org.jvnet.localizer.LocaleProvider;
import org.kohsuke.stapler.jelly.JellyFacet;
import org.apache.tools.ant.types.FileSet;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletResponse;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.security.Security;
import java.util.logging.LogRecord;
import static java.util.logging.Level.*;
/**
* Entry point when Hudson is used as a webapp.
*
* @author Kohsuke Kawaguchi
*/
public class WebAppMain implements ServletContextListener {
private final RingBufferLogHandler handler = new RingBufferLogHandler() {
@Override public synchronized void publish(LogRecord record) {
if (record.getLevel().intValue() >= Level.INFO.intValue()) {
super.publish(record);
}
}
};
private static final String APP = "app";
private boolean terminated;
private Thread initThread;
/**
* Creates the sole instance of {@link jenkins.model.Jenkins} and register it to the {@link ServletContext}.
*/
public void contextInitialized(ServletContextEvent event) {
final ServletContext context = event.getServletContext();
File home=null;
try {
// use the current request to determine the language
LocaleProvider.setProvider(new LocaleProvider() {
public Locale get() {
return Functions.getCurrentLocale();
}
});
// quick check to see if we (seem to) have enough permissions to run. (see #719)
JVM jvm;
try {
jvm = new JVM();
new URLClassLoader(new URL[0],getClass().getClassLoader());
} catch(SecurityException e) {
throw new InsufficientPermissionDetected(e);
}
try {// remove Sun PKCS11 provider if present. See http://wiki.jenkins-ci.org/display/JENKINS/Solaris+Issue+6276483
Security.removeProvider("SunPKCS11-Solaris");
} catch (SecurityException e) {
// ignore this error.
}
installLogger();
markCookieAsHttpOnly(context);
final FileAndDescription describedHomeDir = getHomeDir(event);
home = describedHomeDir.file.getAbsoluteFile();
home.mkdirs();
System.out.println("Jenkins home directory: "+home+" found at: "+describedHomeDir.description);
// check that home exists (as mkdirs could have failed silently), otherwise throw a meaningful error
if (!home.exists())
throw new NoHomeDir(home);
recordBootAttempt(home);
// make sure that we are using XStream in the "enhanced" (JVM-specific) mode
if(jvm.bestReflectionProvider().getClass()==PureJavaReflectionProvider.class) {
throw new IncompatibleVMDetected(); // nope
}
// JNA is no longer a hard requirement. It's just nice to have. See HUDSON-4820 for more context.
// // make sure JNA works. this can fail if
// // - platform is unsupported
// // - JNA is already loaded in another classloader
// // see http://wiki.jenkins-ci.org/display/JENKINS/JNA+is+already+loaded
// // TODO: or shall we instead modify Hudson to work gracefully without JNA?
// try {
// /*
// java.lang.UnsatisfiedLinkError: Native Library /builds/apps/glassfish/domains/hudson-domain/generated/jsp/j2ee-modules/hudson-1.309/loader/com/sun/jna/sunos-sparc/libjnidispatch.so already loaded in another classloader
// at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1743)
// at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1674)
// at java.lang.Runtime.load0(Runtime.java:770)
// at java.lang.System.load(System.java:1005)
// at com.sun.jna.Native.loadNativeLibraryFromJar(Native.java:746)
// at com.sun.jna.Native.loadNativeLibrary(Native.java:680)
// at com.sun.jna.Native.<clinit>(Native.java:108)
// at hudson.util.jna.GNUCLibrary.<clinit>(GNUCLibrary.java:86)
// at hudson.Util.createSymlink(Util.java:970)
// at hudson.model.Run.run(Run.java:1174)
// at hudson.matrix.MatrixBuild.run(MatrixBuild.java:149)
// at hudson.model.ResourceController.execute(ResourceController.java:88)
// at hudson.model.Executor.run(Executor.java:123)
// */
// String.valueOf(Native.POINTER_SIZE); // this meaningless operation forces the classloading and initialization
// } catch (LinkageError e) {
// if (e.getMessage().contains("another classloader"))
// context.setAttribute(APP,new JNADoublyLoaded(e));
// else
// context.setAttribute(APP,new HudsonFailedToLoad(e));
// }
// make sure this is servlet 2.4 container or above
try {
ServletResponse.class.getMethod("setCharacterEncoding",String.class);
} catch (NoSuchMethodException e) {
throw new IncompatibleServletVersionDetected(ServletResponse.class);
}
// make sure that we see Ant 1.7
try {
FileSet.class.getMethod("getDirectoryScanner");
} catch (NoSuchMethodException e) {
throw new IncompatibleAntVersionDetected(FileSet.class);
}
// make sure AWT is functioning, or else JFreeChart won't even load.
if(ChartUtil.awtProblemCause!=null) {
throw new AWTProblem(ChartUtil.awtProblemCause);
}
// some containers (in particular Tomcat) doesn't abort a launch
// even if the temp directory doesn't exist.
// check that and report an error
try {
File f = File.createTempFile("test", "test");
f.delete();
} catch (IOException e) {
throw new NoTempDir(e);
}
// Tomcat breaks XSLT with JDK 5.0 and onward. Check if that's the case, and if so,
// try to correct it
try {
TransformerFactory.newInstance();
// if this works we are all happy
} catch (TransformerFactoryConfigurationError x) {
// no it didn't.
LOGGER.log(WARNING, "XSLT not configured correctly. Hudson will try to fix this. See http://issues.apache.org/bugzilla/show_bug.cgi?id=40895 for more details",x);
System.setProperty(TransformerFactory.class.getName(),"com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
try {
TransformerFactory.newInstance();
LOGGER.info("XSLT is set to the JAXP RI in JRE");
} catch(TransformerFactoryConfigurationError y) {
LOGGER.log(SEVERE, "Failed to correct the problem.");
}
}
installExpressionFactory(event);
context.setAttribute(APP,new HudsonIsLoading());
final File _home = home;
initThread = new Thread("Jenkins initialization thread") {
@Override
public void run() {
boolean success = false;
try {
Jenkins instance = new Hudson(_home, context);
context.setAttribute(APP, instance);
BootFailure.getBootFailureFile(_home).delete();
// at this point we are open for business and serving requests normally
LOGGER.info("Jenkins is fully up and running");
success = true;
} catch (Error e) {
new HudsonFailedToLoad(e).publish(context,_home);
throw e;
} catch (Exception e) {
new HudsonFailedToLoad(e).publish(context,_home);
} finally {
Jenkins instance = Jenkins.getInstance();
if(!success && instance!=null)
instance.cleanUp();
}
}
};
initThread.start();
} catch (BootFailure e) {
e.publish(context,home);
} catch (Error e) {
LOGGER.log(SEVERE, "Failed to initialize Jenkins",e);
throw e;
} catch (RuntimeException e) {
LOGGER.log(SEVERE, "Failed to initialize Jenkins",e);
throw e;
}
}
/**
* Set the session cookie as HTTP only.
*
* @see <a href="https://www.owasp.org/index.php/HttpOnly">discussion of this topic in OWASP</a>
*/
private void markCookieAsHttpOnly(ServletContext context) {
try {
Method m;
try {
m = context.getClass().getMethod("getSessionCookieConfig");
} catch (NoSuchMethodException x) { // 3.0+
LOGGER.log(Level.FINE, "Failed to set secure cookie flag", x);
return;
}
Object sessionCookieConfig = m.invoke(context);
// not exposing session cookie to JavaScript to mitigate damage caused by XSS
Class scc = Class.forName("javax.servlet.SessionCookieConfig");
Method setHttpOnly = scc.getMethod("setHttpOnly",boolean.class);
setHttpOnly.invoke(sessionCookieConfig,true);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to set HTTP-only cookie flag", e);
}
}
public void joinInit() throws InterruptedException {
initThread.join();
}
/**
* To assist boot failure script, record the number of boot attempts.
* This file gets deleted in case of successful boot.
*
* @see BootFailure
*/
private void recordBootAttempt(File home) {
FileOutputStream o=null;
try {
o = new FileOutputStream(BootFailure.getBootFailureFile(home), true);
o.write((new Date().toString() + System.getProperty("line.separator", "\n")).toString().getBytes());
} catch (IOException e) {
LOGGER.log(WARNING, "Failed to record boot attempts",e);
} finally {
IOUtils.closeQuietly(o);
}
}
public static void installExpressionFactory(ServletContextEvent event) {
JellyFacet.setExpressionFactory(event, new ExpressionFactory2());
}
/**
* Installs log handler to monitor all Hudson logs.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE")
private void installLogger() {
Jenkins.logRecords = handler.getView();
Logger.getLogger("").addHandler(handler);
}
/** Add some metadata to a File, allowing to trace setup issues */
public static class FileAndDescription {
public final File file;
public final String description;
public FileAndDescription(File file,String description) {
this.file = file;
this.description = description;
}
}
/**
* Determines the home directory for Jenkins.
*
* <p>
* We look for a setting that affects the smallest scope first, then bigger ones later.
*
* <p>
* People makes configuration mistakes, so we are trying to be nice
* with those by doing {@link String#trim()}.
*
* <p>
* @return the File alongside with some description to help the user troubleshoot issues
*/
public FileAndDescription getHomeDir(ServletContextEvent event) {
// check JNDI for the home directory first
for (String name : HOME_NAMES) {
try {
InitialContext iniCtxt = new InitialContext();
Context env = (Context) iniCtxt.lookup("java:comp/env");
String value = (String) env.lookup(name);
if(value!=null && value.trim().length()>0)
return new FileAndDescription(new File(value.trim()),"JNDI/java:comp/env/"+name);
// look at one more place. See issue #1314
value = (String) iniCtxt.lookup(name);
if(value!=null && value.trim().length()>0)
return new FileAndDescription(new File(value.trim()),"JNDI/"+name);
} catch (NamingException e) {
// ignore
}
}
// next the system property
for (String name : HOME_NAMES) {
String sysProp = System.getProperty(name);
if(sysProp!=null)
return new FileAndDescription(new File(sysProp.trim()),"System.getProperty(\""+name+"\")");
}
// look at the env var next
for (String name : HOME_NAMES) {
String env = EnvVars.masterEnvVars.get(name);
if(env!=null)
return new FileAndDescription(new File(env.trim()).getAbsoluteFile(),"EnvVars.masterEnvVars.get(\""+name+"\")");
}
// otherwise pick a place by ourselves
String root = event.getServletContext().getRealPath("/WEB-INF/workspace");
if(root!=null) {
File ws = new File(root.trim());
if(ws.exists())
// Hudson <1.42 used to prefer this before ~/.hudson, so
// check the existence and if it's there, use it.
// otherwise if this is a new installation, prefer ~/.hudson
return new FileAndDescription(ws,"getServletContext().getRealPath(\"/WEB-INF/workspace\")");
}
File legacyHome = new File(new File(System.getProperty("user.home")),".hudson");
if (legacyHome.exists()) {
return new FileAndDescription(legacyHome,"$user.home/.hudson"); // before rename, this is where it was stored
}
File newHome = new File(new File(System.getProperty("user.home")),".jenkins");
return new FileAndDescription(newHome,"$user.home/.jenkins");
}
public void contextDestroyed(ServletContextEvent event) {
terminated = true;
Jenkins instance = Jenkins.getInstance();
if(instance!=null)
instance.cleanUp();
Thread t = initThread;
if (t!=null)
t.interrupt();
// Logger is in the system classloader, so if we don't do this
// the whole web app will never be undepoyed.
Logger.getLogger("").removeHandler(handler);
}
private static final Logger LOGGER = Logger.getLogger(WebAppMain.class.getName());
private static final String[] HOME_NAMES = {"JENKINS_HOME","HUDSON_HOME"};
}
| ./CrossVul/dataset_final_sorted/CWE-254/java/good_2398_1 |
crossvul-java_data_bad_2398_2 | package jenkins.model;
import hudson.Extension;
import hudson.Util;
import hudson.XmlFile;
import hudson.util.FormValidation;
import hudson.util.XStream2;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import static hudson.Util.fixNull;
/**
* Stores the location of Jenkins (e-mail address and the HTTP URL.)
*
* @author Kohsuke Kawaguchi
* @since 1.494
*/
@Extension
public class JenkinsLocationConfiguration extends GlobalConfiguration {
/**
* @deprecated
*/
private transient String hudsonUrl;
private String adminAddress;
private String jenkinsUrl;
// just to suppress warnings
private transient String charset,useSsl;
public static JenkinsLocationConfiguration get() {
return GlobalConfiguration.all().get(JenkinsLocationConfiguration.class);
}
public JenkinsLocationConfiguration() {
load();
}
@Override
public synchronized void load() {
// for backward compatibility, if we don't have our own data yet, then
// load from Mailer.
XmlFile file = getConfigFile();
if(!file.exists()) {
XStream2 xs = new XStream2();
xs.addCompatibilityAlias("hudson.tasks.Mailer$DescriptorImpl",JenkinsLocationConfiguration.class);
file = new XmlFile(xs,new File(Jenkins.getInstance().getRootDir(),"hudson.tasks.Mailer.xml"));
if (file.exists()) {
try {
file.unmarshal(this);
if (jenkinsUrl==null)
jenkinsUrl = hudsonUrl;
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to load "+file, e);
}
}
} else {
super.load();
}
updateSecureSessionFlag();
}
public String getAdminAddress() {
String v = adminAddress;
if(v==null) v = Messages.Mailer_Address_Not_Configured();
return v;
}
public void setAdminAddress(String adminAddress) {
if(adminAddress.startsWith("\"") && adminAddress.endsWith("\"")) {
// some users apparently quote the whole thing. Don't konw why
// anyone does this, but it's a machine's job to forgive human mistake
adminAddress = adminAddress.substring(1,adminAddress.length()-1);
}
this.adminAddress = adminAddress;
save();
}
public String getUrl() {
return jenkinsUrl;
}
public void setUrl(String hudsonUrl) {
String url = Util.nullify(hudsonUrl);
if(url!=null && !url.endsWith("/"))
url += '/';
this.jenkinsUrl = url;
save();
updateSecureSessionFlag();
}
/**
* If the Jenkins URL starts from "https", force the secure session flag
*
* @see <a href="https://www.owasp.org/index.php/SecureFlag">discussion of this topic in OWASP</a>
*/
private void updateSecureSessionFlag() {
try {
ServletContext context = Jenkins.getInstance().servletContext;
Method m;
try {
m = context.getClass().getMethod("getSessionCookieConfig");
} catch (NoSuchMethodException x) { // 3.0+
LOGGER.log(Level.FINE, "Failed to set secure cookie flag", x);
return;
}
Object sessionCookieConfig = m.invoke(context);
// not exposing session cookie to JavaScript to mitigate damage caused by XSS
Class scc = Class.forName("javax.servlet.SessionCookieConfig");
Method setHttpOnly = scc.getMethod("setHttpOnly",boolean.class);
setHttpOnly.invoke(sessionCookieConfig,true);
Method setSecure = scc.getMethod("setSecure",boolean.class);
boolean v = fixNull(jenkinsUrl).startsWith("https");
setSecure.invoke(sessionCookieConfig,v);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to set secure cookie flag", e);
}
}
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
req.bindJSON(this,json);
return true;
}
/**
* Checks the URL in <tt>global.jelly</tt>
*/
public FormValidation doCheckUrl(@QueryParameter String value) {
if(value.startsWith("http://localhost"))
return FormValidation.warning(Messages.Mailer_Localhost_Error());
return FormValidation.ok();
}
public FormValidation doCheckAdminAddress(@QueryParameter String value) {
try {
new InternetAddress(value);
return FormValidation.ok();
} catch (AddressException e) {
return FormValidation.error(e.getMessage());
}
}
private static final Logger LOGGER = Logger.getLogger(JenkinsLocationConfiguration.class.getName());
}
| ./CrossVul/dataset_final_sorted/CWE-254/java/bad_2398_2 |
crossvul-java_data_good_2398_2 | package jenkins.model;
import hudson.Extension;
import hudson.Util;
import hudson.XmlFile;
import hudson.util.FormValidation;
import hudson.util.XStream2;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import static hudson.Util.fixNull;
/**
* Stores the location of Jenkins (e-mail address and the HTTP URL.)
*
* @author Kohsuke Kawaguchi
* @since 1.494
*/
@Extension
public class JenkinsLocationConfiguration extends GlobalConfiguration {
/**
* @deprecated
*/
private transient String hudsonUrl;
private String adminAddress;
private String jenkinsUrl;
// just to suppress warnings
private transient String charset,useSsl;
public static JenkinsLocationConfiguration get() {
return GlobalConfiguration.all().get(JenkinsLocationConfiguration.class);
}
public JenkinsLocationConfiguration() {
load();
}
@Override
public synchronized void load() {
// for backward compatibility, if we don't have our own data yet, then
// load from Mailer.
XmlFile file = getConfigFile();
if(!file.exists()) {
XStream2 xs = new XStream2();
xs.addCompatibilityAlias("hudson.tasks.Mailer$DescriptorImpl",JenkinsLocationConfiguration.class);
file = new XmlFile(xs,new File(Jenkins.getInstance().getRootDir(),"hudson.tasks.Mailer.xml"));
if (file.exists()) {
try {
file.unmarshal(this);
if (jenkinsUrl==null)
jenkinsUrl = hudsonUrl;
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to load "+file, e);
}
}
} else {
super.load();
}
updateSecureSessionFlag();
}
public String getAdminAddress() {
String v = adminAddress;
if(v==null) v = Messages.Mailer_Address_Not_Configured();
return v;
}
public void setAdminAddress(String adminAddress) {
if(adminAddress.startsWith("\"") && adminAddress.endsWith("\"")) {
// some users apparently quote the whole thing. Don't konw why
// anyone does this, but it's a machine's job to forgive human mistake
adminAddress = adminAddress.substring(1,adminAddress.length()-1);
}
this.adminAddress = adminAddress;
save();
}
public String getUrl() {
return jenkinsUrl;
}
public void setUrl(String hudsonUrl) {
String url = Util.nullify(hudsonUrl);
if(url!=null && !url.endsWith("/"))
url += '/';
this.jenkinsUrl = url;
save();
updateSecureSessionFlag();
}
/**
* If the Jenkins URL starts from "https", force the secure session flag
*
* @see <a href="https://www.owasp.org/index.php/SecureFlag">discussion of this topic in OWASP</a>
*/
private void updateSecureSessionFlag() {
try {
ServletContext context = Jenkins.getInstance().servletContext;
Method m;
try {
m = context.getClass().getMethod("getSessionCookieConfig");
} catch (NoSuchMethodException x) { // 3.0+
LOGGER.log(Level.FINE, "Failed to set secure cookie flag", x);
return;
}
Object sessionCookieConfig = m.invoke(context);
Class scc = Class.forName("javax.servlet.SessionCookieConfig");
Method setSecure = scc.getMethod("setSecure", boolean.class);
boolean v = fixNull(jenkinsUrl).startsWith("https");
setSecure.invoke(sessionCookieConfig, v);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof IllegalStateException) {
// servlet 3.0 spec seems to prohibit this from getting set at runtime,
// though Winstone is happy to accept i. see JENKINS-25019
return;
}
LOGGER.log(Level.WARNING, "Failed to set secure cookie flag", e);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to set secure cookie flag", e);
}
}
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
req.bindJSON(this,json);
return true;
}
/**
* Checks the URL in <tt>global.jelly</tt>
*/
public FormValidation doCheckUrl(@QueryParameter String value) {
if(value.startsWith("http://localhost"))
return FormValidation.warning(Messages.Mailer_Localhost_Error());
return FormValidation.ok();
}
public FormValidation doCheckAdminAddress(@QueryParameter String value) {
try {
new InternetAddress(value);
return FormValidation.ok();
} catch (AddressException e) {
return FormValidation.error(e.getMessage());
}
}
private static final Logger LOGGER = Logger.getLogger(JenkinsLocationConfiguration.class.getName());
}
| ./CrossVul/dataset_final_sorted/CWE-254/java/good_2398_2 |
crossvul-java_data_bad_2398_1 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Jean-Baptiste Quenot, Tom Huybrechts
*
* 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;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
import com.thoughtworks.xstream.core.JVM;
import com.trilead.ssh2.util.IOUtils;
import hudson.model.Hudson;
import hudson.util.BootFailure;
import jenkins.model.Jenkins;
import hudson.util.HudsonIsLoading;
import hudson.util.IncompatibleServletVersionDetected;
import hudson.util.IncompatibleVMDetected;
import hudson.util.InsufficientPermissionDetected;
import hudson.util.NoHomeDir;
import hudson.util.RingBufferLogHandler;
import hudson.util.NoTempDir;
import hudson.util.IncompatibleAntVersionDetected;
import hudson.util.HudsonFailedToLoad;
import hudson.util.ChartUtil;
import hudson.util.AWTProblem;
import org.jvnet.localizer.LocaleProvider;
import org.kohsuke.stapler.jelly.JellyFacet;
import org.apache.tools.ant.types.FileSet;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletResponse;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.security.Security;
import java.util.logging.LogRecord;
import static java.util.logging.Level.*;
/**
* Entry point when Hudson is used as a webapp.
*
* @author Kohsuke Kawaguchi
*/
public class WebAppMain implements ServletContextListener {
private final RingBufferLogHandler handler = new RingBufferLogHandler() {
@Override public synchronized void publish(LogRecord record) {
if (record.getLevel().intValue() >= Level.INFO.intValue()) {
super.publish(record);
}
}
};
private static final String APP = "app";
private boolean terminated;
private Thread initThread;
/**
* Creates the sole instance of {@link jenkins.model.Jenkins} and register it to the {@link ServletContext}.
*/
public void contextInitialized(ServletContextEvent event) {
final ServletContext context = event.getServletContext();
File home=null;
try {
// use the current request to determine the language
LocaleProvider.setProvider(new LocaleProvider() {
public Locale get() {
return Functions.getCurrentLocale();
}
});
// quick check to see if we (seem to) have enough permissions to run. (see #719)
JVM jvm;
try {
jvm = new JVM();
new URLClassLoader(new URL[0],getClass().getClassLoader());
} catch(SecurityException e) {
throw new InsufficientPermissionDetected(e);
}
try {// remove Sun PKCS11 provider if present. See http://wiki.jenkins-ci.org/display/JENKINS/Solaris+Issue+6276483
Security.removeProvider("SunPKCS11-Solaris");
} catch (SecurityException e) {
// ignore this error.
}
installLogger();
final FileAndDescription describedHomeDir = getHomeDir(event);
home = describedHomeDir.file.getAbsoluteFile();
home.mkdirs();
System.out.println("Jenkins home directory: "+home+" found at: "+describedHomeDir.description);
// check that home exists (as mkdirs could have failed silently), otherwise throw a meaningful error
if (!home.exists())
throw new NoHomeDir(home);
recordBootAttempt(home);
// make sure that we are using XStream in the "enhanced" (JVM-specific) mode
if(jvm.bestReflectionProvider().getClass()==PureJavaReflectionProvider.class) {
throw new IncompatibleVMDetected(); // nope
}
// JNA is no longer a hard requirement. It's just nice to have. See HUDSON-4820 for more context.
// // make sure JNA works. this can fail if
// // - platform is unsupported
// // - JNA is already loaded in another classloader
// // see http://wiki.jenkins-ci.org/display/JENKINS/JNA+is+already+loaded
// // TODO: or shall we instead modify Hudson to work gracefully without JNA?
// try {
// /*
// java.lang.UnsatisfiedLinkError: Native Library /builds/apps/glassfish/domains/hudson-domain/generated/jsp/j2ee-modules/hudson-1.309/loader/com/sun/jna/sunos-sparc/libjnidispatch.so already loaded in another classloader
// at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1743)
// at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1674)
// at java.lang.Runtime.load0(Runtime.java:770)
// at java.lang.System.load(System.java:1005)
// at com.sun.jna.Native.loadNativeLibraryFromJar(Native.java:746)
// at com.sun.jna.Native.loadNativeLibrary(Native.java:680)
// at com.sun.jna.Native.<clinit>(Native.java:108)
// at hudson.util.jna.GNUCLibrary.<clinit>(GNUCLibrary.java:86)
// at hudson.Util.createSymlink(Util.java:970)
// at hudson.model.Run.run(Run.java:1174)
// at hudson.matrix.MatrixBuild.run(MatrixBuild.java:149)
// at hudson.model.ResourceController.execute(ResourceController.java:88)
// at hudson.model.Executor.run(Executor.java:123)
// */
// String.valueOf(Native.POINTER_SIZE); // this meaningless operation forces the classloading and initialization
// } catch (LinkageError e) {
// if (e.getMessage().contains("another classloader"))
// context.setAttribute(APP,new JNADoublyLoaded(e));
// else
// context.setAttribute(APP,new HudsonFailedToLoad(e));
// }
// make sure this is servlet 2.4 container or above
try {
ServletResponse.class.getMethod("setCharacterEncoding",String.class);
} catch (NoSuchMethodException e) {
throw new IncompatibleServletVersionDetected(ServletResponse.class);
}
// make sure that we see Ant 1.7
try {
FileSet.class.getMethod("getDirectoryScanner");
} catch (NoSuchMethodException e) {
throw new IncompatibleAntVersionDetected(FileSet.class);
}
// make sure AWT is functioning, or else JFreeChart won't even load.
if(ChartUtil.awtProblemCause!=null) {
throw new AWTProblem(ChartUtil.awtProblemCause);
}
// some containers (in particular Tomcat) doesn't abort a launch
// even if the temp directory doesn't exist.
// check that and report an error
try {
File f = File.createTempFile("test", "test");
f.delete();
} catch (IOException e) {
throw new NoTempDir(e);
}
// Tomcat breaks XSLT with JDK 5.0 and onward. Check if that's the case, and if so,
// try to correct it
try {
TransformerFactory.newInstance();
// if this works we are all happy
} catch (TransformerFactoryConfigurationError x) {
// no it didn't.
LOGGER.log(WARNING, "XSLT not configured correctly. Hudson will try to fix this. See http://issues.apache.org/bugzilla/show_bug.cgi?id=40895 for more details",x);
System.setProperty(TransformerFactory.class.getName(),"com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
try {
TransformerFactory.newInstance();
LOGGER.info("XSLT is set to the JAXP RI in JRE");
} catch(TransformerFactoryConfigurationError y) {
LOGGER.log(SEVERE, "Failed to correct the problem.");
}
}
installExpressionFactory(event);
context.setAttribute(APP,new HudsonIsLoading());
final File _home = home;
initThread = new Thread("Jenkins initialization thread") {
@Override
public void run() {
boolean success = false;
try {
Jenkins instance = new Hudson(_home, context);
context.setAttribute(APP, instance);
BootFailure.getBootFailureFile(_home).delete();
// at this point we are open for business and serving requests normally
LOGGER.info("Jenkins is fully up and running");
success = true;
} catch (Error e) {
new HudsonFailedToLoad(e).publish(context,_home);
throw e;
} catch (Exception e) {
new HudsonFailedToLoad(e).publish(context,_home);
} finally {
Jenkins instance = Jenkins.getInstance();
if(!success && instance!=null)
instance.cleanUp();
}
}
};
initThread.start();
} catch (BootFailure e) {
e.publish(context,home);
} catch (Error e) {
LOGGER.log(SEVERE, "Failed to initialize Jenkins",e);
throw e;
} catch (RuntimeException e) {
LOGGER.log(SEVERE, "Failed to initialize Jenkins",e);
throw e;
}
}
public void joinInit() throws InterruptedException {
initThread.join();
}
/**
* To assist boot failure script, record the number of boot attempts.
* This file gets deleted in case of successful boot.
*
* @see BootFailure
*/
private void recordBootAttempt(File home) {
FileOutputStream o=null;
try {
o = new FileOutputStream(BootFailure.getBootFailureFile(home), true);
o.write((new Date().toString() + System.getProperty("line.separator", "\n")).toString().getBytes());
} catch (IOException e) {
LOGGER.log(WARNING, "Failed to record boot attempts",e);
} finally {
IOUtils.closeQuietly(o);
}
}
public static void installExpressionFactory(ServletContextEvent event) {
JellyFacet.setExpressionFactory(event, new ExpressionFactory2());
}
/**
* Installs log handler to monitor all Hudson logs.
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings("LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE")
private void installLogger() {
Jenkins.logRecords = handler.getView();
Logger.getLogger("").addHandler(handler);
}
/** Add some metadata to a File, allowing to trace setup issues */
public static class FileAndDescription {
public final File file;
public final String description;
public FileAndDescription(File file,String description) {
this.file = file;
this.description = description;
}
}
/**
* Determines the home directory for Jenkins.
*
* <p>
* We look for a setting that affects the smallest scope first, then bigger ones later.
*
* <p>
* People makes configuration mistakes, so we are trying to be nice
* with those by doing {@link String#trim()}.
*
* <p>
* @return the File alongside with some description to help the user troubleshoot issues
*/
public FileAndDescription getHomeDir(ServletContextEvent event) {
// check JNDI for the home directory first
for (String name : HOME_NAMES) {
try {
InitialContext iniCtxt = new InitialContext();
Context env = (Context) iniCtxt.lookup("java:comp/env");
String value = (String) env.lookup(name);
if(value!=null && value.trim().length()>0)
return new FileAndDescription(new File(value.trim()),"JNDI/java:comp/env/"+name);
// look at one more place. See issue #1314
value = (String) iniCtxt.lookup(name);
if(value!=null && value.trim().length()>0)
return new FileAndDescription(new File(value.trim()),"JNDI/"+name);
} catch (NamingException e) {
// ignore
}
}
// next the system property
for (String name : HOME_NAMES) {
String sysProp = System.getProperty(name);
if(sysProp!=null)
return new FileAndDescription(new File(sysProp.trim()),"System.getProperty(\""+name+"\")");
}
// look at the env var next
for (String name : HOME_NAMES) {
String env = EnvVars.masterEnvVars.get(name);
if(env!=null)
return new FileAndDescription(new File(env.trim()).getAbsoluteFile(),"EnvVars.masterEnvVars.get(\""+name+"\")");
}
// otherwise pick a place by ourselves
String root = event.getServletContext().getRealPath("/WEB-INF/workspace");
if(root!=null) {
File ws = new File(root.trim());
if(ws.exists())
// Hudson <1.42 used to prefer this before ~/.hudson, so
// check the existence and if it's there, use it.
// otherwise if this is a new installation, prefer ~/.hudson
return new FileAndDescription(ws,"getServletContext().getRealPath(\"/WEB-INF/workspace\")");
}
File legacyHome = new File(new File(System.getProperty("user.home")),".hudson");
if (legacyHome.exists()) {
return new FileAndDescription(legacyHome,"$user.home/.hudson"); // before rename, this is where it was stored
}
File newHome = new File(new File(System.getProperty("user.home")),".jenkins");
return new FileAndDescription(newHome,"$user.home/.jenkins");
}
public void contextDestroyed(ServletContextEvent event) {
terminated = true;
Jenkins instance = Jenkins.getInstance();
if(instance!=null)
instance.cleanUp();
Thread t = initThread;
if (t!=null)
t.interrupt();
// Logger is in the system classloader, so if we don't do this
// the whole web app will never be undepoyed.
Logger.getLogger("").removeHandler(handler);
}
private static final Logger LOGGER = Logger.getLogger(WebAppMain.class.getName());
private static final String[] HOME_NAMES = {"JENKINS_HOME","HUDSON_HOME"};
}
| ./CrossVul/dataset_final_sorted/CWE-254/java/bad_2398_1 |
crossvul-java_data_good_1902_4 | package com.bijay.onlinevotingsystem.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.sql.Date;
import com.bijay.onlinevotingsystem.controller.SHA256;
import com.bijay.onlinevotingsystem.dto.Voter;
import com.bijay.onlinevotingsystem.util.DbUtil;
public class VoterDaoImpl implements VoterDao {
PreparedStatement ps = null;
@Override
public void saveVoterInfo(Voter voter) {
String sql = "insert into voter_table(voter_name, password, gender, state_no, district, email, dob, imageurl) values(?,?,?,?,?,?,?,?)";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setString(1, voter.getVoterName());
ps.setString(2, voter.getPassword());
ps.setString(3, voter.getGender());
ps.setInt(4, voter.getStateNo());
ps.setString(5, voter.getDistrictName());
ps.setString(6, voter.getEmail());
ps.setDate(7, new Date(voter.getDob().getTime()));
ps.setString(8, voter.getImgUrl());
ps.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@Override
public List<Voter> getAllVoterInfo() {
List<Voter> voterList = new ArrayList<>();
String sql = "select * from voter_table";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Voter voter = new Voter();
voter.setId(rs.getInt("id"));
voter.setVoterName(rs.getString("voter_name"));
voter.setPassword(rs.getString("password"));
voter.setStateNo(rs.getInt("state_no"));
voter.setDistrictName(rs.getString("district"));
voter.setGender(rs.getString("gender"));
voter.setImgUrl(rs.getString("imageurl"));
voter.setEmail(rs.getString("email"));
voter.setDob(rs.getDate("dob"));
voterList.add(voter);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return voterList;
}
@Override
public void updateVoterInfo(Voter voter) {
// TODO Auto-generated method stub
}
@Override
public void deleteVoterInfo(int id) {
String sql = "delete from voter_table where id=?";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@Override
public boolean loginValidate(String userName, String password, String email) {
String sql = "select * from voter_table where voter_name=? and email=?";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setString(1, userName);
ps.setString(2, email);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String cipherText = rs.getString("password");
return SHA256.validatePassword(password, cipherText);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return false;
}
} | ./CrossVul/dataset_final_sorted/CWE-759/java/good_1902_4 |
crossvul-java_data_bad_1902_4 | package com.bijay.onlinevotingsystem.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.sql.Date;
import com.bijay.onlinevotingsystem.dto.Voter;
import com.bijay.onlinevotingsystem.util.DbUtil;
public class VoterDaoImpl implements VoterDao {
PreparedStatement ps = null;
@Override
public void saveVoterInfo(Voter voter) {
String sql = "insert into voter_table(voter_name, password, gender, state_no, district, email, dob, imageurl) values(?,?,?,?,?,?,?,?)";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setString(1, voter.getVoterName());
ps.setString(2, voter.getPassword());
ps.setString(3, voter.getGender());
ps.setInt(4, voter.getStateNo());
ps.setString(5, voter.getDistrictName());
ps.setString(6, voter.getEmail());
ps.setDate(7, new Date(voter.getDob().getTime()));
ps.setString(8, voter.getImgUrl());
ps.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@Override
public List<Voter> getAllVoterInfo() {
List<Voter> voterList = new ArrayList<>();
String sql = "select * from voter_table";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Voter voter = new Voter();
voter.setId(rs.getInt("id"));
voter.setVoterName(rs.getString("voter_name"));
voter.setPassword(rs.getString("password"));
voter.setStateNo(rs.getInt("state_no"));
voter.setDistrictName(rs.getString("district"));
voter.setGender(rs.getString("gender"));
voter.setImgUrl(rs.getString("imageurl"));
voter.setEmail(rs.getString("email"));
voter.setDob(rs.getDate("dob"));
voterList.add(voter);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return voterList;
}
@Override
public void updateVoterInfo(Voter voter) {
// TODO Auto-generated method stub
}
@Override
public void deleteVoterInfo(int id) {
String sql = "delete from voter_table where id=?";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@Override
public boolean loginValidate(String userName, String password, String email) {
String sql = "select * from voter_table where voter_name=? and password=? and email=?";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setString(1, userName);
ps.setString(2, password);
ps.setString(3, email);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return true;
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return false;
}
} | ./CrossVul/dataset_final_sorted/CWE-759/java/bad_1902_4 |
crossvul-java_data_bad_1902_3 | package com.bijay.onlinevotingsystem.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.bijay.onlinevotingsystem.dto.Admin;
import com.bijay.onlinevotingsystem.util.DbUtil;
public class AdminDaoImpl implements AdminDao {
PreparedStatement ps = null;
@Override
public void saveAdminInfo(Admin admin) {
String sql = "insert into admin_table(admin_name, password) values(?,?)";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setString(1, admin.getAdminName());
ps.setString(2, admin.getPassword());
ps.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@Override
public List<Admin> getAllAdminInfo() {
List<Admin> adminList = new ArrayList<>();
String sql = "select * from admin_table";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Admin admin = new Admin();
admin.setId(rs.getInt("id"));
admin.setAdminName(rs.getString("admin_name"));
admin.setPassword(rs.getString("password"));
adminList.add(admin);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return adminList;
}
@Override
public void deleteAdminInfo(int id) {
String sql = "delete from admin_table where id=?";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@Override
public Admin getAdminInfoById(int id) {
Admin admin = new Admin();
String sql = "select * from admin_table where id=?";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
admin.setId(rs.getInt("id"));
admin.setAdminName(rs.getString("admin_name"));
admin.setPassword(rs.getString("password"));
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return admin;
}
@Override
public void updateAdminInfo(Admin admin) {
String sql = "update admin_table set admin_name=?, password=? where id=?";
try {
ps = DbUtil.getConnection().prepareStatement(sql);
ps.setString(1, admin.getAdminName());
ps.setString(2, admin.getPassword());
ps.setInt(3, admin.getId());
ps.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@Override
public boolean loginValidate(String userName, String password) {
String sql = "select * from admin_table where admin_name=? and password=?";
try {
ps=DbUtil.getConnection().prepareStatement(sql);
ps.setString(1, userName);
ps.setString(2,password);
ResultSet rs =ps.executeQuery();
if (rs.next()) {
return true;
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return false;
}
} | ./CrossVul/dataset_final_sorted/CWE-759/java/bad_1902_3 |
crossvul-java_data_bad_1902_1 | package com.bijay.onlinevotingsystem.controller;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA256 {
public String getSHA(String password) {
try {
// Static getInstance method is called with hashing SHA
MessageDigest md = MessageDigest.getInstance("SHA-256");
// digest() method called
// to calculate message digest of an input
// and return array of byte
byte[] messageDigest = md.digest(password.getBytes());
// Convert byte array into signum representation
BigInteger no = new BigInteger(1, messageDigest);
// Convert message digest into hex value
String hashPass = no.toString(16);
while (hashPass.length() < 32) {
hashPass = "0" + hashPass;
}
return hashPass;
// For specifying wrong message digest algorithms
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-759/java/bad_1902_1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.