repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
ceph-main/examples/rgw/java/ceph-s3-upload/src/main/java/org/example/cephs3upload/App.java
package org.example.cephs3upload; import com.amazonaws.services.s3.model.AmazonS3Exception; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import java.io.File; import java.nio.file.Paths; public class App { public static void main( String[] args ) { final String USAGE = "\n" + "To run this example, supply the name of an S3 bucket and a file to\n" + "upload to it.\n" + "\n" + "Ex: java -jar target/ceph-s3-upload-1.0-SNAPSHOT-jar-with-dependencies.jar <bucketname> <filename>\n"; if (args.length < 2) { System.out.println(USAGE); System.exit(1); } String bucket_name = args[0]; String file_path = args[1]; String key_name = Paths.get(file_path).getFileName().toString(); System.out.format("Uploading %s to S3 bucket %s...\n", file_path, bucket_name); // Put in the CEPH RGW access and secret keys here in that order "access key" "secret key" // Must also be specified here BasicAWSCredentials credentials = new BasicAWSCredentials("0555b35654ad1656d804","h7GhxuBLTrlhVUyxSPUKUV8r/2EI4ngqJxD7iBdBYLhwluN30JaT3Q=="); // Note That the AWSClient builder takes in the endpoint and the region // This has to be specified in this file final AmazonS3 s3 = AmazonS3ClientBuilder .standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://127.0.0.1:8000", "default")) .build(); try { s3.putObject(bucket_name, key_name, new File(file_path)); } catch (AmazonS3Exception e) { System.err.println(e.getMessage()); // raises more explicit error message than e.getErrorMessage() e.g when Bucket is not available System.exit(1); } System.out.println("Object upload successful!"); } }
2,294
43.134615
149
java
null
ceph-main/examples/rgw/java/ceph-s3-upload/src/test/java/org/example/cephs3upload/AppTest.java
package org.example.cephs3upload; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
652
15.74359
46
java
null
ceph-main/src/java/java/com/ceph/crush/Bucket.java
/* * 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 com.ceph.crush; public class Bucket { private String type; private String name; public Bucket(String type, String name) { this.type = type; this.name = name; } public String getType() { return type; } public String getName() { return name; } public String toString() { return "bucket[" + type + "," + name + "]"; } }
1,449
32.72093
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephAlreadyMountedException.java
/* * 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 com.ceph.fs; import java.io.IOException; /** * Ceph is already mounted. */ public class CephAlreadyMountedException extends IOException { private static final long serialVersionUID = 1L; /** * Construct CephAlreadyMountedException. */ public CephAlreadyMountedException() { super(); } /** * Construct CephAlreadyMountedException with message. */ public CephAlreadyMountedException(String s) { super(s); } }
1,535
33.133333
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephFileAlreadyExistsException.java
/* * 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 com.ceph.fs; import java.io.IOException; /** * Ceph file/directory already exists. */ public class CephFileAlreadyExistsException extends IOException { private static final long serialVersionUID = 1L; /** * Construct CephFileAlreadyExistsException. */ public CephFileAlreadyExistsException() { super(); } /** * Construct CephFileAlreadyExistsException with message. */ public CephFileAlreadyExistsException(String s) { super(s); } }
1,561
33.711111
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephFileExtent.java
/* * 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 com.ceph.fs; import java.util.Arrays; /** * Holds information about a file extent in CephFS. */ public class CephFileExtent { private long offset; private long length; private int[] osds; CephFileExtent(long offset, long length, int[] osds) { this.offset = offset; this.length = length; this.osds = osds; } /** * Get starting offset of extent. */ public long getOffset() { return offset; } /** * Get length of extent. */ public long getLength() { return length; } /** * Get list of OSDs with this extent. */ public int[] getOSDs() { return osds; } /** * Pretty print. */ public String toString() { return "extent[" + offset + "," + length + "," + Arrays.toString(osds) + "]"; } }
1,868
26.895522
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephMount.java
/* * 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 com.ceph.fs; import java.io.IOException; import java.io.FileNotFoundException; import java.net.InetAddress; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.lang.String; import com.ceph.crush.Bucket; public class CephMount { /* * Set via JNI callback in native_ceph_create * * Do not touch! */ private long instance_ptr; /* * Flags for open(). * * Must be synchronized with JNI if changed. */ public static final int O_RDONLY = 1; public static final int O_RDWR = 2; public static final int O_APPEND = 4; public static final int O_CREAT = 8; public static final int O_TRUNC = 16; public static final int O_EXCL = 32; public static final int O_WRONLY = 64; public static final int O_DIRECTORY = 128; /* * Whence flags for seek(). * * Must be synchronized with JNI if changed. */ public static final int SEEK_SET = 1; public static final int SEEK_CUR = 2; public static final int SEEK_END = 3; /* * Attribute flags for setattr(). * * Must be synchronized with JNI if changed. */ public static final int SETATTR_MODE = 1; public static final int SETATTR_UID = 2; public static final int SETATTR_GID = 4; public static final int SETATTR_MTIME = 8; public static final int SETATTR_ATIME = 16; /* * Flags for setxattr(); * * Must be synchronized with JNI if changed. */ public static final int XATTR_CREATE = 1; public static final int XATTR_REPLACE = 2; public static final int XATTR_NONE = 3; /* * Flags for flock(); * * Must be synchronized with JNI if changed. */ public static final int LOCK_SH = 1; public static final int LOCK_EX = 2; public static final int LOCK_NB = 4; public static final int LOCK_UN = 8; /* * This is run by the class loader and will report early any problems * finding or linking in the shared JNI library. */ static { loadLibrary(); } static synchronized void loadLibrary() { CephNativeLoader.getInstance().loadLibrary(); } /* * Package-private: called from CephNativeLoader */ static native void native_initialize(); /* * RW lock used for fine grained synchronization to native */ private final ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock(); private final Lock rlock = rwlock.readLock(); private final Lock wlock = rwlock.writeLock(); /* * Controls clean-up synchronization between the constructor and finalize(). * If native_ceph_create fails, then we want a call to finalize() to not * attempt to clean-up native context, because there is none. */ private boolean initialized = false; /* * Try to clean-up. First, unmount() will catch users who forget to do the * unmount manually. Second, release() will destroy the entire context. It * is safe to call release after a failure in unmount. */ protected void finalize() throws Throwable { if (initialized) { try { unmount(); } catch (Exception e) {} try { native_ceph_release(instance_ptr); } catch (Exception e) {} } super.finalize(); } /** * Create a new CephMount with specific client id. * * @param id client id. */ public CephMount(String id) { native_ceph_create(this, id); initialized = true; } private static native int native_ceph_create(CephMount mount, String id); /** * Create a new CephMount with default client id. */ public CephMount() { this(null); } /** * Activate the mount with a given root path. * * @param root The path to use as the root (pass null for "/"). */ public void mount(String root) { wlock.lock(); try { native_ceph_mount(instance_ptr, root); } finally { wlock.unlock(); } } private static native int native_ceph_mount(long mountp, String root); /** * Deactivate the mount. * * The mount can be reactivated using mount(). Configuration parameters * previously set are not reset. */ public void unmount() { wlock.lock(); try { native_ceph_unmount(instance_ptr); } finally { wlock.unlock(); } } private static native int native_ceph_unmount(long mountp); /* * Private access to low-level ceph_release. */ private static native int native_ceph_release(long mountp); /** * Load configuration from a file. * * @param path The path to the configuration file. */ public void conf_read_file(String path) throws FileNotFoundException { rlock.lock(); try { native_ceph_conf_read_file(instance_ptr, path); } finally { rlock.unlock(); } } private static native int native_ceph_conf_read_file(long mountp, String path); /** * Set the value of a configuration option. * * @param option The configuration option to modify. * @param value The new value of the option. */ public void conf_set(String option, String value) { rlock.lock(); try { native_ceph_conf_set(instance_ptr, option, value); } finally { rlock.unlock(); } } private static native int native_ceph_conf_set(long mountp, String option, String value); /** * Get the value of a configuration option. * * @param option The name of the configuration option. * @return The value of the option or null if option not found */ public String conf_get(String option) { rlock.lock(); try { return native_ceph_conf_get(instance_ptr, option); } finally { rlock.unlock(); } } private static native String native_ceph_conf_get(long mountp, String option); /** * Get file system status. * * @param path Path to file in file system. * @param statvfs CephStatVFS structure to hold status. */ public void statfs(String path, CephStatVFS statvfs) throws FileNotFoundException { rlock.lock(); try { native_ceph_statfs(instance_ptr, path, statvfs); } finally { rlock.unlock(); } } private static native int native_ceph_statfs(long mountp, String path, CephStatVFS statvfs); /** * Get the current working directory. * * @return The current working directory in Ceph. */ public String getcwd() { rlock.lock(); try { return native_ceph_getcwd(instance_ptr); } finally { rlock.unlock(); } } private static native String native_ceph_getcwd(long mountp); /** * Set the current working directory. * * @param path The directory set as the cwd. */ public void chdir(String path) throws FileNotFoundException { rlock.lock(); try { native_ceph_chdir(instance_ptr, path); } finally { rlock.unlock(); } } private static native int native_ceph_chdir(long mountp, String cwd); /** * List the contents of a directory. * * @param dir The directory. * @return List of files and directories excluding "." and "..". */ public String[] listdir(String dir) throws FileNotFoundException { rlock.lock(); try { return native_ceph_listdir(instance_ptr, dir); } finally { rlock.unlock(); } } private static native String[] native_ceph_listdir(long mountp, String path); /** * Create a hard link to an existing file. * * @param oldpath The target path of the link. * @param newpath The name of the link. */ public void link(String oldpath, String newpath) throws FileNotFoundException { rlock.lock(); try { native_ceph_link(instance_ptr, oldpath, newpath); } finally { rlock.unlock(); } } private static native int native_ceph_link(long mountp, String existing, String newname); /** * Unlink/delete a name from the file system. * * @param path The name to unlink/delete. */ public void unlink(String path) throws FileNotFoundException { rlock.lock(); try { native_ceph_unlink(instance_ptr, path); } finally { rlock.unlock(); } } private static native int native_ceph_unlink(long mountp, String path); /** * Rename a file or directory. * * @param from The current path. * @param to The new path. */ public void rename(String from, String to) throws FileNotFoundException { rlock.lock(); try { native_ceph_rename(instance_ptr, from, to); } finally { rlock.unlock(); } } private static native int native_ceph_rename(long mountp, String from, String to); /** * Create a directory. * * @param path The directory to create. * @param mode The mode of the new directory. */ public void mkdir(String path, int mode) { rlock.lock(); try { native_ceph_mkdir(instance_ptr, path, mode); } finally { rlock.unlock(); } } private static native int native_ceph_mkdir(long mountp, String path, int mode); /** * Create a directory and all parents. * * @param path The directory to create. * @param mode The mode of the new directory. */ public void mkdirs(String path, int mode) throws IOException { rlock.lock(); try { native_ceph_mkdirs(instance_ptr, path, mode); } finally { rlock.unlock(); } } private static native int native_ceph_mkdirs(long mountp, String path, int mode); /** * Delete a directory. * * @param path The directory to delete. */ public void rmdir(String path) throws FileNotFoundException { rlock.lock(); try { native_ceph_rmdir(instance_ptr, path); } finally { rlock.unlock(); } } private static native int native_ceph_rmdir(long mountp, String path); /** * Read the value of a symbolic link. */ public String readlink(String path) throws FileNotFoundException { rlock.lock(); try { return native_ceph_readlink(instance_ptr, path); } finally { rlock.unlock(); } } private static native String native_ceph_readlink(long mountp, String path); /** * Create a symbolic link. * * @param oldpath Target of the symbolic link. * @param newpath Name of the link. */ public void symlink(String oldpath, String newpath) { rlock.lock(); try { native_ceph_symlink(instance_ptr, oldpath, newpath); } finally { rlock.unlock(); } } private static native int native_ceph_symlink(long mountp, String existing, String newname); /** * Get file status. * * @param path Path of file to stat. * @param stat CephStat structure to hold file status. */ public void stat(String path, CephStat stat) throws FileNotFoundException, CephNotDirectoryException { rlock.lock(); try { native_ceph_stat(instance_ptr, path, stat); } finally { rlock.unlock(); } } private static native int native_ceph_stat(long mountp, String path, CephStat stat); /** * Get file status, without following symlinks. * * @param path Path of file to stat. * @param stat CephStat structure to hold file status. */ public void lstat(String path, CephStat stat) throws FileNotFoundException, CephNotDirectoryException { rlock.lock(); try { native_ceph_lstat(instance_ptr, path, stat); } finally { rlock.unlock(); } } private static native int native_ceph_lstat(long mountp, String path, CephStat stat); /** * Set file attributes. * * @param path Path to file. * @param stat CephStat structure holding attributes. * @param mask Mask specifying which attributes to set. */ public void setattr(String path, CephStat stat, int mask) throws FileNotFoundException { rlock.lock(); try { native_ceph_setattr(instance_ptr, path, stat, mask); } finally { rlock.unlock(); } } private static native int native_ceph_setattr(long mountp, String relpath, CephStat stat, int mask); /** * Change file mode. * * @param path Path to file. * @param mode New mode bits. */ public void chmod(String path, int mode) throws FileNotFoundException { rlock.lock(); try { native_ceph_chmod(instance_ptr, path, mode); } finally { rlock.unlock(); } } private static native int native_ceph_chmod(long mountp, String path, int mode); /** * Change file mode of an open file. * * @param fd The open file descriptor to change the mode bits on. * @param mode New mode bits. */ public void fchmod(int fd, int mode) { rlock.lock(); try { native_ceph_fchmod(instance_ptr, fd, mode); } finally { rlock.unlock(); } } private static native int native_ceph_fchmod(long mountp, int fd, int mode); /** * Truncate a file to a specified length. * * @param path Path of the file. * @param size New file length. */ public void truncate(String path, long size) throws FileNotFoundException { rlock.lock(); try { native_ceph_truncate(instance_ptr, path, size); } finally { rlock.unlock(); } } private static native int native_ceph_truncate(long mountp, String path, long size); /** * Open a file. * * @param path Path of file to open or create. * @param flags Open flags. * @param mode Permission mode. * @return File descriptor. */ public int open(String path, int flags, int mode) throws FileNotFoundException { rlock.lock(); try { return native_ceph_open(instance_ptr, path, flags, mode); } finally { rlock.unlock(); } } private static native int native_ceph_open(long mountp, String path, int flags, int mode); /** * Open a file with a specific file layout. * * @param path Path of file to open or create. * @param flags Open flags. * @param mode Permission mode. * @param stripe_unit File layout stripe unit size. * @param stripe_count File layout stripe count. * @param object_size Size of each object. * @param data_pool The target data pool. * @return File descriptor. */ public int open(String path, int flags, int mode, int stripe_unit, int stripe_count, int object_size, String data_pool) throws FileNotFoundException { rlock.lock(); try { return native_ceph_open_layout(instance_ptr, path, flags, mode, stripe_unit, stripe_count, object_size, data_pool); } finally { rlock.unlock(); } } private static native int native_ceph_open_layout(long mountp, String path, int flags, int mode, int stripe_unit, int stripe_count, int object_size, String data_pool); /** * Close an open file. * * @param fd The file descriptor. */ public void close(int fd) { rlock.lock(); try { native_ceph_close(instance_ptr, fd); } finally { rlock.unlock(); } } private static native int native_ceph_close(long mountp, int fd); /** * Seek to a position in a file. * * @param fd File descriptor. * @param offset New offset. * @param whence Whence value. * @return The new offset. */ public long lseek(int fd, long offset, int whence) { rlock.lock(); try { return native_ceph_lseek(instance_ptr, fd, offset, whence); } finally { rlock.unlock(); } } private static native long native_ceph_lseek(long mountp, int fd, long offset, int whence); /** * Read from a file. * * @param fd The file descriptor. * @param buf Buffer to for data read. * @param size Amount of data to read into the buffer. * @param offset Offset to read from (-1 for current position). * @return The number of bytes read. */ public long read(int fd, byte[] buf, long size, long offset) { rlock.lock(); try { return native_ceph_read(instance_ptr, fd, buf, size, offset); } finally { rlock.unlock(); } } private static native long native_ceph_read(long mountp, int fd, byte[] buf, long size, long offset); /** * Write to a file at a specific offset. * * @param fd The file descriptor. * @param buf Buffer to write. * @param size Amount of data to write. * @param offset Offset to write from (-1 for current position). * @return The number of bytes written. */ public long write(int fd, byte[] buf, long size, long offset) { rlock.lock(); try { return native_ceph_write(instance_ptr, fd, buf, size, offset); } finally { rlock.unlock(); } } private static native long native_ceph_write(long mountp, int fd, byte[] buf, long size, long offset); /** * Truncate a file. * * @param fd File descriptor of the file to truncate. * @param size New file size. */ public void ftruncate(int fd, long size) { rlock.lock(); try { native_ceph_ftruncate(instance_ptr, fd, size); } finally { rlock.unlock(); } } private static native int native_ceph_ftruncate(long mountp, int fd, long size); /** * Synchronize a file with the file system. * * @param fd File descriptor to synchronize. * @param dataonly Synchronize only data. */ public void fsync(int fd, boolean dataonly) { rlock.lock(); try { native_ceph_fsync(instance_ptr, fd, dataonly); } finally { rlock.unlock(); } } private static native int native_ceph_fsync(long mountp, int fd, boolean dataonly); /** * Apply or remove an advisory lock. * * @param fd File descriptor to lock or unlock. * @param operation the advisory lock operation to be performed on the file * descriptor among LOCK_SH (shared lock), LOCK_EX (exclusive lock), * or LOCK_UN (remove lock). The LOCK_NB value can be ORed to perform a * non-blocking operation. * @param owner the user-supplied owner identifier (an arbitrary integer) */ public void flock(int fd, int operation, long owner) throws IOException { rlock.lock(); try { native_ceph_flock(instance_ptr, fd, operation, owner); } finally { rlock.unlock(); } } private static native int native_ceph_flock(long mountp, int fd, int operation, long owner); /** * Get file status. * * @param fd The file descriptor. * @param stat The object in which to store the status. */ public void fstat(int fd, CephStat stat) { rlock.lock(); try { native_ceph_fstat(instance_ptr, fd, stat); } finally { rlock.unlock(); } } private static native int native_ceph_fstat(long mountp, int fd, CephStat stat); /** * Synchronize the client with the file system. */ public void sync_fs() { rlock.lock(); try { native_ceph_sync_fs(instance_ptr); } finally { rlock.unlock(); } } private static native int native_ceph_sync_fs(long mountp); /** * Get an extended attribute value. * * If the buffer is large enough to hold the entire attribute value, or * buf is null, the size of the value is returned. * * @param path File path. * @param name Name of the attribute. * @param buf Buffer to store attribute value. * @return The length of the attribute value. See description for more * details. */ public long getxattr(String path, String name, byte[] buf) throws FileNotFoundException { rlock.lock(); try { return native_ceph_getxattr(instance_ptr, path, name, buf); } finally { rlock.unlock(); } } private static native long native_ceph_getxattr(long mountp, String path, String name, byte[] buf); /** * Get an extended attribute value of a symbolic link. * * If the buffer is large enough to hold the entire attribute value, or * buf is null, the size of the value is returned. * * @param path File path. * @param name Name of attribute. * @param buf Buffer to store attribute value. * @return The length of the attribute value. See description for more * details. */ public long lgetxattr(String path, String name, byte[] buf) throws FileNotFoundException { rlock.lock(); try { return native_ceph_lgetxattr(instance_ptr, path, name, buf); } finally { rlock.unlock(); } } private static native long native_ceph_lgetxattr(long mountp, String path, String name, byte[] buf); /** * List extended attributes. * * @param path File path. * @return List of attribute names. */ public String[] listxattr(String path) throws FileNotFoundException { rlock.lock(); try { return native_ceph_listxattr(instance_ptr, path); } finally { rlock.unlock(); } } private static native String[] native_ceph_listxattr(long mountp, String path); /** * List extended attributes of a symbolic link. * * @param path File path. * @return List of attribute names. */ public String[] llistxattr(String path) throws FileNotFoundException { rlock.lock(); try { return native_ceph_llistxattr(instance_ptr, path); } finally { rlock.unlock(); } } private static native String[] native_ceph_llistxattr(long mountp, String path); /** * Remove an extended attribute. * * @param path File path. * @param name Name of attribute. */ public void removexattr(String path, String name) throws FileNotFoundException { rlock.lock(); try { native_ceph_removexattr(instance_ptr, path, name); } finally { rlock.unlock(); } } private static native int native_ceph_removexattr(long mountp, String path, String name); /** * Remove an extended attribute from a symbolic link. * * @param path File path. * @param name Name of attribute. */ public void lremovexattr(String path, String name) throws FileNotFoundException { rlock.lock(); try { native_ceph_lremovexattr(instance_ptr, path, name); } finally { rlock.unlock(); } } private static native int native_ceph_lremovexattr(long mountp, String path, String name); /** * Set the value of an extended attribute. * * @param path The file path. * @param name The attribute name. * @param buf The attribute value. * @param size The size of the attribute value. * @param flags Flag controlling behavior (XATTR_CREATE/REPLACE/NONE). */ public void setxattr(String path, String name, byte[] buf, long size, int flags) throws FileNotFoundException { rlock.lock(); try { native_ceph_setxattr(instance_ptr, path, name, buf, size, flags); } finally { rlock.unlock(); } } private static native int native_ceph_setxattr(long mountp, String path, String name, byte[] buf, long size, int flags); /** * Set the value of an extended attribute on a symbolic link. * * @param path The file path. * @param name The attribute name. * @param buf The attribute value. * @param size The size of the attribute value. * @param flags Flag controlling behavior (XATTR_CREATE/REPLACE/NONE). */ public void lsetxattr(String path, String name, byte[] buf, long size, int flags) throws FileNotFoundException { rlock.lock(); try { native_ceph_lsetxattr(instance_ptr, path, name, buf, size, flags); } finally { rlock.unlock(); } } private static native int native_ceph_lsetxattr(long mountp, String path, String name, byte[] buf, long size, int flags); /** * Get the stripe unit of a file. * * @param fd The file descriptor. * @return The stripe unit. */ public int get_file_stripe_unit(int fd) { rlock.lock(); try { return native_ceph_get_file_stripe_unit(instance_ptr, fd); } finally { rlock.unlock(); } } private static native int native_ceph_get_file_stripe_unit(long mountp, int fd); /** * Get the name of the pool a file is stored in. * * @param fd An open file descriptor. * @return The pool name. */ public String get_file_pool_name(int fd) { rlock.lock(); try { return native_ceph_get_file_pool_name(instance_ptr, fd); } finally { rlock.unlock(); } } private static native String native_ceph_get_file_pool_name(long mountp, int fd); /** * Get the default data pool of cephfs. * * @return The pool name. */ public String get_default_data_pool_name() { rlock.lock(); try { return native_ceph_get_default_data_pool_name(instance_ptr); } finally { rlock.unlock(); } } private static native String native_ceph_get_default_data_pool_name(long mountp); /** * Get the replication of a file. * * @param fd The file descriptor. * @return The file replication. */ public int get_file_replication(int fd) { rlock.lock(); try { return native_ceph_get_file_replication(instance_ptr, fd); } finally { rlock.unlock(); } } private static native int native_ceph_get_file_replication(long mountp, int fd); /** * Favor reading from local replicas when possible. * * @param state Enable or disable localized reads. */ public void localize_reads(boolean state) { rlock.lock(); try { native_ceph_localize_reads(instance_ptr, state); } finally { rlock.unlock(); } } private static native int native_ceph_localize_reads(long mountp, boolean on); /** * Get file layout stripe unit granularity. * * @return Stripe unit granularity. */ public int get_stripe_unit_granularity() { rlock.lock(); try { return native_ceph_get_stripe_unit_granularity(instance_ptr); } finally { rlock.unlock(); } } private static native int native_ceph_get_stripe_unit_granularity(long mountp); /** * Get the pool id for the named pool. * * @param name The pool name. * @return The pool id. */ public int get_pool_id(String name) throws CephPoolException { rlock.lock(); try { return native_ceph_get_pool_id(instance_ptr, name); } catch (FileNotFoundException e) { throw new CephPoolException("pool name " + name + " not found"); } finally { rlock.unlock(); } } private static native int native_ceph_get_pool_id(long mountp, String name) throws FileNotFoundException; /** * Get the pool replication factor. * * @param pool_id The pool id. * @return Number of replicas stored in the pool. */ public int get_pool_replication(int pool_id) throws CephPoolException { rlock.lock(); try { return native_ceph_get_pool_replication(instance_ptr, pool_id); } catch (FileNotFoundException e) { throw new CephPoolException("pool id " + pool_id + " not found"); } finally { rlock.unlock(); } } private static native int native_ceph_get_pool_replication(long mountp, int pool_id) throws FileNotFoundException; /** * Get file extent containing a given offset. * * @param fd The file descriptor. * @param offset Offset in file. * @return A CephFileExtent object. */ public CephFileExtent get_file_extent(int fd, long offset) { rlock.lock(); try { return native_ceph_get_file_extent_osds(instance_ptr, fd, offset); } finally { rlock.unlock(); } } private static native CephFileExtent native_ceph_get_file_extent_osds(long mountp, int fd, long offset); /** * Get the fully qualified CRUSH location of an OSD. * * Returns (type, name) string pairs for each device in the CRUSH bucket * hierarchy starting from the given OSD to the root. * * @param osd The OSD device id. * @return List of pairs. */ public Bucket[] get_osd_crush_location(int osd) { rlock.lock(); try { String[] parts = native_ceph_get_osd_crush_location(instance_ptr, osd); Bucket[] path = new Bucket[parts.length / 2]; for (int i = 0; i < path.length; i++) path[i] = new Bucket(parts[i*2], parts[i*2+1]); return path; } finally { rlock.unlock(); } } private static native String[] native_ceph_get_osd_crush_location(long mountp, int osd); /** * Get the network address of an OSD. * * @param osd The OSD device id. * @return The network address. */ public InetAddress get_osd_address(int osd) { rlock.lock(); try { return native_ceph_get_osd_addr(instance_ptr, osd); } finally { rlock.unlock(); } } private static native InetAddress native_ceph_get_osd_addr(long mountp, int osd); }
29,477
25.701087
123
java
null
ceph-main/src/java/java/com/ceph/fs/CephNativeLoader.java
/* * 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 com.ceph.fs; class CephNativeLoader { private static final CephNativeLoader instance = new CephNativeLoader(); private static boolean initialized = false; private static final String JNI_PATH_ENV_VAR = "CEPH_JNI_PATH"; private static final String LIBRARY_NAME = "cephfs_jni"; private static final String LIBRARY_FILE = "libcephfs_jni.so"; private CephNativeLoader() {} public static CephNativeLoader getInstance() { return instance; } public synchronized void loadLibrary() { if (initialized) return; boolean success = false; /* * Allow a Ceph specific environment variable to force * the loading path. */ String path = System.getenv(JNI_PATH_ENV_VAR); try { if (path != null) { System.out.println("Loading libcephfs-jni: " + path); System.load(path); success = true; } else { try { /* * Try default Java loading path(s) */ System.out.println("Loading libcephfs-jni from default path: " + System.getProperty("java.library.path")); System.loadLibrary(LIBRARY_NAME); success = true; } catch (final UnsatisfiedLinkError ule1) { try { /* * Try RHEL/CentOS default path */ path = "/usr/lib64/" + LIBRARY_FILE; System.out.println("Loading libcephfs-jni: " + path); System.load(path); success = true; } catch (final UnsatisfiedLinkError ule2) { /* * Try Ubuntu default path */ path = "/usr/lib/jni/" + LIBRARY_FILE; System.out.println("Loading libcephfs-jni: " + path); System.load(path); success = true; } } } } finally { System.out.println("Loading libcephfs-jni: " + (success ? "Success!" : "Failure!")); } /* * Finish initialization */ CephMount.native_initialize(); initialized = true; } }
3,139
32.404255
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephNotDirectoryException.java
/* * 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 com.ceph.fs; import java.io.IOException; /** * Component of path is not a directory. */ public class CephNotDirectoryException extends IOException { private static final long serialVersionUID = 1L; /** * Construct CephNotDirectoryException. */ public CephNotDirectoryException() { super(); } /** * Construct CephNotDirectoryException with message. */ public CephNotDirectoryException(String s) { super(s); } }
1,538
33.2
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephNotMountedException.java
/* * 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 com.ceph.fs; import java.io.IOException; /** * Ceph is not mounted. */ public class CephNotMountedException extends IOException { private static final long serialVersionUID = 1L; /** * Construct CephNotMountedException. */ public CephNotMountedException() { super(); } /** * Construct CephNotMountedException with message. */ public CephNotMountedException(String s) { super(s); } }
1,511
32.6
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephPoolException.java
/* * 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 com.ceph.fs; import java.io.IOException; /** * Exception related to Ceph pool. */ public class CephPoolException extends IOException { private static final long serialVersionUID = 1L; /** * Construct CephPoolException. */ public CephPoolException() { super(); } /** * Construct CephPoolException with message. */ public CephPoolException(String s) { super(s); } }
1,492
32.177778
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephStat.java
/* * 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 com.ceph.fs; /** * Holds struct stat fields. */ public class CephStat { /* Set from native */ private boolean is_file; /* S_ISREG */ private boolean is_directory; /* S_ISDIR */ private boolean is_symlink; /* S_ISLNK */ public int mode; public int uid; public int gid; public long size; public long blksize; public long blocks; public long a_time; public long m_time; public boolean isFile() { return is_file; } public boolean isDir() { return is_directory; } public boolean isSymlink() { return is_symlink; } }
1,665
29.851852
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephStatVFS.java
/* * 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 com.ceph.fs; /** * Holds struct statvfs fields. */ public class CephStatVFS { public long bsize; public long frsize; public long blocks; public long bavail; public long files; public long fsid; public long namemax; }
1,321
37.882353
78
java
null
ceph-main/src/java/test/com/ceph/fs/CephAllTests.java
/* * 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 com.ceph.fs; import java.io.FileNotFoundException; import java.io.IOException; import java.util.UUID; import org.junit.*; import org.junit.runners.Suite; import org.junit.runner.RunWith; import static org.junit.Assert.*; @RunWith( Suite.class ) @Suite.SuiteClasses( { CephDoubleMountTest.class, CephMountCreateTest.class, CephMountTest.class, CephUnmountedTest.class, }) /** * Every Java test class must be added to this list in order to be executed with 'ant test' */ public class CephAllTests{ }
1,601
34.6
91
java
null
ceph-main/src/java/test/com/ceph/fs/CephDoubleMountTest.java
/* * 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 com.ceph.fs; import java.io.FileNotFoundException; import java.io.IOException; import java.util.UUID; import org.junit.*; import static org.junit.Assert.*; public class CephDoubleMountTest { @Test(expected=CephAlreadyMountedException.class) public void test_double_mount() throws Exception { CephMount mount = new CephMount("admin"); String conf_file = System.getProperty("CEPH_CONF_FILE"); if (conf_file != null) mount.conf_read_file(conf_file); mount.mount(null); try { mount.mount(null); } finally { mount.unmount(); } } }
1,670
35.326087
78
java
null
ceph-main/src/java/test/com/ceph/fs/CephMountCreateTest.java
/* * 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 com.ceph.fs; import java.io.FileNotFoundException; import org.junit.*; import java.util.UUID; import static org.junit.Assert.*; /* * This tests the mount root dir functionality. It creates an empty * directory in the real root, then it re-mounts the file system * with the empty directory specified as the root. Assertions are * that the "/" in the normal mount is non-empty, and that "/" is * empty in the mount with the empty directory as the root. */ public class CephMountCreateTest { private static String conf_file; @BeforeClass public static void class_setup() throws Exception { conf_file = System.getProperty("CEPH_CONF_FILE"); } private CephMount setupMount(String root) throws Exception { CephMount mount = new CephMount("admin"); if (conf_file != null) mount.conf_read_file(conf_file); mount.conf_set("client_permissions", "0"); mount.mount(root); return mount; } @Test public void test_CephMountCreate() throws Exception { CephMount mount; boolean found; String dir = "libcephfs_junit_" + UUID.randomUUID(); /* root dir has more than one dir */ mount = setupMount("/"); try { mount.rmdir("/" + dir); } catch (FileNotFoundException e) {} mount.mkdirs("/" + dir, 777); String[] subdirs = mount.listdir("/"); found = false; for (String d : subdirs) { if (d.compareTo(dir) == 0) found = true; } assertTrue(found); mount.unmount(); /* changing root to empty dir */ mount = setupMount("/" + dir); subdirs = mount.listdir("/"); found = false; for (String d : subdirs) { found = true; } assertFalse(found); mount.unmount(); /* cleanup */ mount = setupMount("/"); mount.rmdir("/" + dir); mount.unmount(); } }
2,896
30.48913
78
java
null
ceph-main/src/java/test/com/ceph/fs/CephMountTest.java
/* * 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 com.ceph.fs; import java.io.FileNotFoundException; import java.io.IOException; import java.net.InetAddress; import java.util.UUID; import org.junit.*; import static org.junit.Assert.*; import com.ceph.crush.Bucket; /* * Coverage * - Everything is covered in at least success cases. * - l[set,get,remove]xattr are not working */ public class CephMountTest { private static CephMount mount; private static String basedir = null; @BeforeClass public static void setup() throws Exception { mount = new CephMount("admin"); String conf_file = System.getProperty("CEPH_CONF_FILE"); if (conf_file != null) mount.conf_read_file(conf_file); mount.conf_set("client_permissions", "0"); mount.mount(null); basedir = "/libcephfs_junit_" + UUID.randomUUID(); mount.mkdir(basedir, 0777); } @AfterClass public static void destroy() throws Exception { String[] list = mount.listdir(basedir); for (String l : list) System.out.println(l); mount.rmdir(basedir); mount.unmount(); } /* * Helper function to construct a unique path. */ public String makePath() { String path = basedir + "/" + UUID.randomUUID(); return path; } /* * Helper to learn the data pool name, by reading it * from the '/' dir inode. */ public String getRootPoolName() throws Exception { int fd = mount.open("/", CephMount.O_DIRECTORY, 0600); String pool = mount.get_file_pool_name(fd); mount.close(fd); return pool; } /* * Helper function to create a file with the given path and size. The file * is filled with size bytes and the file descriptor is returned. */ public int createFile(String path, int size) throws Exception { int fd = mount.open(path, CephMount.O_RDWR|CephMount.O_CREAT, 0600); byte[] buf = new byte[4096]; int left = size; while (left > 0) { size = Math.min(buf.length, left); long ret = mount.write(fd, buf, size, -1); left -= ret; } return fd; } /* * Helper function to create a unique file and fill it with size bytes. The * file descriptor is returned. */ public int createFile(int size) throws Exception { return createFile(makePath(), size); } @Test(expected=FileNotFoundException.class) public void test_mount_dne() throws Exception { CephMount mount2 = new CephMount("admin"); String conf_file = System.getProperty("CEPH_CONF_FILE"); if (conf_file != null) mount2.conf_read_file(conf_file); mount2.mount("/wlfkjwlekfjwlejfwe"); mount2.unmount(); } /* * Test loading of conf file that doesn't exist. * * FIXME: * Ceph returns -ENOSYS rather than -ENOENT. Correct? */ //@Test(expected=FileNotFoundException.class) @Test public void test_conf_read_file_dne() throws Exception { //mount.conf_read_file("/this_file_does_not_exist"); } /* * Test loading of conf file that isn't valid * * FIXME: implement */ @Test public void test_conf_read_file_invalid() throws Exception { } @Test(expected=NullPointerException.class) public void test_conf_read_file_null() throws Exception { mount.conf_read_file(null); } /* * conf_set/conf_get */ @Test(expected=NullPointerException.class) public void test_conf_set_null_opt() throws Exception { mount.conf_set(null, "value"); } @Test(expected=NullPointerException.class) public void test_conf_set_null_val() throws Exception { mount.conf_set("option", null); } @Test(expected=NullPointerException.class) public void test_conf_get_null_opt() throws Exception { mount.conf_get(null); } @Test public void test_conf() throws Exception { String opt = "log to stderr"; String val1, val2, val3; /* get the current value */ val1 = mount.conf_get(opt); /* * flip the value. this may make some debug information be dumped to the * console when the value becomes true. TODO: find a better config option * to toggle. */ if (val1.compareTo("true") == 0) val2 = "false"; else val2 = "true"; mount.conf_set(opt, val2); /* verify the change */ val3 = mount.conf_get(opt); assertTrue(val3.compareTo(val2) == 0); /* reset to original value */ mount.conf_set(opt, val1); val3 = mount.conf_get(opt); assertTrue(val3.compareTo(val1) == 0); } /* * statfs */ @Test public void test_statfs() throws Exception { CephStatVFS st1 = new CephStatVFS(); mount.statfs("/", st1); /* * FIXME: a better test here is to see if changes to the file system are * reflected through statfs (e.g. increasing number of files). However, it * appears that the updates aren't immediately visible. */ assertTrue(st1.bsize > 0); assertTrue(st1.frsize > 0); assertTrue(st1.blocks > 0); assertTrue(st1.bavail > 0); assertTrue(st1.namemax > 0); } /* * getcwd/chdir */ @Test public void test_getcwd() throws Exception { mount.chdir(basedir); String cwd = mount.getcwd(); assertTrue(cwd.compareTo(basedir) == 0); /* Make sure to reset cwd to root */ mount.chdir("/"); cwd = mount.getcwd(); assertTrue(cwd.compareTo("/") == 0); } @Test(expected=NullPointerException.class) public void test_chdir_null() throws Exception { mount.chdir(null); } @Test(expected=FileNotFoundException.class) public void test_chdir_dne() throws Exception { mount.chdir("/this/path/does/not/exist/"); } /* * FIXME: this test should throw an error (but does not)? */ //@Test(expected=IOException.class) @Test public void test_chdir_not_dir() throws Exception { String path = makePath(); int fd = createFile(path, 1); mount.close(fd); //mount.chdir(path); shouldn't be able to do this? mount.unlink(path); /* * Switch back. Other tests seem to be sensitive to the current directory * being something other than "/". This shouldn't happen once this tests * passes and the call to chdir fails anyway. */ mount.chdir("/"); } /* * listdir */ @Test(expected=NullPointerException.class) public void test_listdir_null() throws Exception { mount.listdir(null); } @Test(expected=FileNotFoundException.class) public void test_listdir_dne() throws Exception { mount.listdir("/this/path/does/not/exist/"); } @Test(expected=IOException.class) public void test_listdir_not_dir() throws Exception { String path = makePath(); int fd = createFile(path, 1); mount.close(fd); try { mount.listdir(path); } finally { mount.unlink(path); } } @Test public void test_listdir() throws Exception { String dir = makePath(); mount.mkdir(dir, 0777); /* test that new directory is empty */ String[] list = mount.listdir(dir); assertTrue(list.length == 0); /* test that new directories are seen */ for (int i = 0; i < 3; i++) mount.mkdir(dir + "/" + i, 777); list = mount.listdir(dir); assertTrue(list.length == 3); /* test that more new directories are seen */ for (int i = 0; i < 30; i++) mount.mkdir(dir + "/x" + i, 777); list = mount.listdir(dir); assertTrue(list.length == 33); /* remove */ for (int i = 0; i < 30; i++) mount.rmdir(dir + "/x" + i); for (int i = 0; i < 3; i++) mount.rmdir(dir + "/" + i); mount.rmdir(dir); } /* * Missing * * ceph_link * ceph_unlink */ /* * rename */ @Test(expected=NullPointerException.class) public void test_rename_null_from() throws Exception { mount.rename(null, "to"); } @Test(expected=NullPointerException.class) public void test_rename_null_to() throws Exception { mount.rename("from", null); } @Test(expected=FileNotFoundException.class) public void test_rename_dne() throws Exception { mount.rename("/this/doesnt/exist", "/this/neither"); } @Test public void test_rename() throws Exception { /* create a file */ String path = makePath(); int fd = createFile(path, 1); mount.close(fd); /* move it to a new name */ String newpath = makePath(); mount.rename(path, newpath); /* verfiy the sizes are the same */ CephStat st = new CephStat(); mount.lstat(newpath, st); assertTrue(st.size == 1); /* remove the file */ mount.unlink(newpath); } /* * mkdir/mkdirs/rmdir */ @Test(expected=IOException.class) public void test_mkdir_exists() throws Exception { String path = makePath(); mount.mkdir(path, 0777); try { mount.mkdir(path, 0777); } finally { mount.rmdir(path); } } @Test(expected=IOException.class) public void test_mkdirs_exists() throws Exception { String path = makePath(); mount.mkdirs(path, 0777); try { mount.mkdirs(path, 0777); } finally { mount.rmdir(path); } } @Test public void test_mkdir() throws Exception { String path = makePath(); mount.mkdir(path, 0777); CephStat st = new CephStat(); mount.lstat(path, st); assertTrue(st.isDir()); mount.rmdir(path); } @Test public void test_mkdirs() throws Exception { String path = makePath(); mount.mkdirs(path + "/x/y", 0777); CephStat st = new CephStat(); mount.lstat(path, st); assertTrue(st.isDir()); mount.lstat(path + "/x", st); assertTrue(st.isDir()); mount.lstat(path + "/x/y", st); assertTrue(st.isDir()); mount.rmdir(path + "/x/y"); mount.rmdir(path + "/x"); mount.rmdir(path); } @Test(expected=FileNotFoundException.class) public void test_rmdir() throws Exception { /* make a new directory */ String path = makePath(); mount.mkdir(path, 0777); CephStat st = new CephStat(); mount.lstat(path, st); assertTrue(st.isDir()); /* remove it */ mount.rmdir(path); /* should not exist now */ mount.lstat(path, st); } /* * readlink * symlink */ @Test public void test_symlink() throws Exception { String oldpath = makePath(); String newpath = makePath(); mount.symlink(oldpath, newpath); CephStat stat = new CephStat(); mount.lstat(newpath, stat); assertTrue(stat.isSymlink()); String symlink = mount.readlink(newpath); assertTrue(symlink.compareTo(oldpath) == 0); mount.unlink(newpath); } /* * lstat */ @Test(expected=NullPointerException.class) public void test_lstat_null_path() throws Exception { mount.lstat(null, new CephStat()); } @Test(expected=NullPointerException.class) public void test_lstat_null_stat() throws Exception { mount.lstat("/path", null); } @Test(expected=FileNotFoundException.class) public void test_lstat_null_dne() throws Exception { mount.lstat("/path/does/not/exist", new CephStat()); } /* * test_stat covers lstat and fstat and stat. * * TODO: create test that for lstat vs stat with symlink follow/nofollow. */ @Test public void test_stat() throws Exception { /* create a new file */ String path = makePath(); int size = 12345; int fd = createFile(path, size); mount.close(fd); /* test some basic info about the new file */ CephStat orig_st = new CephStat(); mount.lstat(path, orig_st); assertTrue(orig_st.size == size); assertTrue(orig_st.blksize > 0); assertTrue(orig_st.blocks > 0); /* now try stat */ CephStat stat_st = new CephStat(); mount.stat(path, stat_st); /* now try fstat */ CephStat other_st = new CephStat(); fd = mount.open(path, CephMount.O_RDWR, 0); mount.fstat(fd, other_st); mount.close(fd); mount.unlink(path); /* compare to fstat results */ assertTrue(orig_st.mode == other_st.mode); assertTrue(orig_st.uid == other_st.uid); assertTrue(orig_st.gid == other_st.gid); assertTrue(orig_st.size == other_st.size); assertTrue(orig_st.blksize == other_st.blksize); assertTrue(orig_st.blocks == other_st.blocks); /* compare to stat results */ assertTrue(orig_st.mode == stat_st.mode); assertTrue(orig_st.uid == stat_st.uid); assertTrue(orig_st.gid == stat_st.gid); assertTrue(orig_st.size == stat_st.size); assertTrue(orig_st.blksize == stat_st.blksize); assertTrue(orig_st.blocks == stat_st.blocks); } /* * stat */ @Test(expected=NullPointerException.class) public void test_stat_null_path() throws Exception { mount.stat(null, new CephStat()); } @Test(expected=NullPointerException.class) public void test_stat_null_stat() throws Exception { mount.stat("/path", null); } @Test(expected=FileNotFoundException.class) public void test_stat_null_dne() throws Exception { mount.stat("/path/does/not/exist", new CephStat()); } @Test(expected=CephNotDirectoryException.class) public void test_enotdir() throws Exception { String path = makePath(); int fd = createFile(path, 1); mount.close(fd); try { CephStat stat = new CephStat(); mount.lstat(path + "/blah", stat); } finally { mount.unlink(path); } } /* * setattr */ @Test(expected=NullPointerException.class) public void test_setattr_null_path() throws Exception { mount.setattr(null, new CephStat(), 0); } @Test(expected=NullPointerException.class) public void test_setattr_null_stat() throws Exception { mount.setattr("/path", null, 0); } @Test(expected=FileNotFoundException.class) public void test_setattr_dne() throws Exception { mount.setattr("/path/does/not/exist", new CephStat(), 0); } @Test public void test_setattr() throws Exception { /* create a file */ String path = makePath(); int fd = createFile(path, 1); mount.close(fd); CephStat st1 = new CephStat(); mount.lstat(path, st1); st1.uid += 1; st1.gid += 1; mount.setattr(path, st1, mount.SETATTR_UID|mount.SETATTR_GID); CephStat st2 = new CephStat(); mount.lstat(path, st2); assertTrue(st2.uid == st1.uid); assertTrue(st2.gid == st1.gid); /* remove the file */ mount.unlink(path); } /* * chmod */ @Test(expected=NullPointerException.class) public void test_chmod_null_path() throws Exception { mount.chmod(null, 0); } @Test(expected=FileNotFoundException.class) public void test_chmod_dne() throws Exception { mount.chmod("/path/does/not/exist", 0); } @Test public void test_chmod() throws Exception { /* create a file */ String path = makePath(); int fd = createFile(path, 1); mount.close(fd); CephStat st = new CephStat(); mount.lstat(path, st); /* flip a bit */ int mode = st.mode; if ((mode & 1) != 0) mode -= 1; else mode += 1; mount.chmod(path, mode); CephStat st2 = new CephStat(); mount.lstat(path, st2); assertTrue(st2.mode == mode); mount.unlink(path); } /* * fchmod */ @Test public void test_fchmod() throws Exception { /* create a file */ String path = makePath(); int fd = createFile(path, 1); CephStat st = new CephStat(); mount.lstat(path, st); /* flip a bit */ int mode = st.mode; if ((mode & 1) != 0) mode -= 1; else mode += 1; mount.fchmod(fd, mode); mount.close(fd); CephStat st2 = new CephStat(); mount.lstat(path, st2); assertTrue(st2.mode == mode); mount.unlink(path); } /* * truncate */ @Test(expected=FileNotFoundException.class) public void test_truncate_dne() throws Exception { mount.truncate("/path/does/not/exist", 0); } @Test(expected=NullPointerException.class) public void test_truncate_null_path() throws Exception { mount.truncate(null, 0); } @Test public void test_truncate() throws Exception { // make file String path = makePath(); int orig_size = 1398331; int fd = createFile(path, orig_size); mount.close(fd); // check file size CephStat st = new CephStat(); mount.lstat(path, st); assertTrue(st.size == orig_size); // truncate and check int crop_size = 333333; mount.truncate(path, crop_size); mount.lstat(path, st); assertTrue(st.size == crop_size); // check after re-open fd = mount.open(path, CephMount.O_RDWR, 0); mount.fstat(fd, st); assertTrue(st.size == crop_size); mount.close(fd); mount.unlink(path); } @Test public void test_open_layout() throws Exception { String path = makePath(); int fd = mount.open(path, CephMount.O_WRONLY|CephMount.O_CREAT, 0, (1<<20), 1, (1<<20), null); mount.close(fd); mount.unlink(path); } /* * open/close */ @Test(expected=FileNotFoundException.class) public void test_open_dne() throws Exception { mount.open("/path/doesnt/exist", 0, 0); } /* * lseek */ @Test public void test_lseek() throws Exception { /* create a new file */ String path = makePath(); int size = 12345; int fd = createFile(path, size); mount.close(fd); /* open and check size */ fd = mount.open(path, CephMount.O_RDWR, 0); long end = mount.lseek(fd, 0, CephMount.SEEK_END); mount.close(fd); mount.unlink(path); assertTrue(size == (int)end); } /* * read/write */ @Test public void test_read() throws Exception { String path = makePath(); int fd = createFile(path, 1500); byte[] buf = new byte[1500]; long ret = mount.read(fd, buf, 1500, 0); assertTrue(ret == 1500); mount.unlink(path); } /* * ftruncate */ @Test public void test_ftruncate() throws Exception { // make file String path = makePath(); int orig_size = 1398331; int fd = createFile(path, orig_size); // check file size CephStat st = new CephStat(); mount.fstat(fd, st); assertTrue(st.size == orig_size); // truncate and check int crop_size = 333333; mount.ftruncate(fd, crop_size); mount.fstat(fd, st); if (st.size != crop_size) { System.err.println("ftruncate error: st.size=" + st.size + " crop_size=" + crop_size); assertTrue(false); } assertTrue(st.size == crop_size); mount.close(fd); // check after re-open fd = mount.open(path, CephMount.O_RDWR, 0); mount.fstat(fd, st); assertTrue(st.size == crop_size); mount.close(fd); mount.unlink(path); } /* * fsync */ @Test public void test_fsync() throws Exception { String path = makePath(); int fd = createFile(path, 123); mount.fsync(fd, false); mount.fsync(fd, true); mount.close(fd); mount.unlink(path); } /* * flock */ @Test public void test_flock() throws Exception { String path = makePath(); int fd = createFile(path, 123); mount.flock(fd, CephMount.LOCK_SH | CephMount.LOCK_NB, 42); mount.flock(fd, CephMount.LOCK_SH | CephMount.LOCK_NB, 43); mount.flock(fd, CephMount.LOCK_UN, 42); mount.flock(fd, CephMount.LOCK_UN, 43); mount.flock(fd, CephMount.LOCK_EX | CephMount.LOCK_NB, 42); try { mount.flock(fd, CephMount.LOCK_SH | CephMount.LOCK_NB, 43); assertTrue(false); } catch(IOException io) {} try { mount.flock(fd, CephMount.LOCK_EX | CephMount.LOCK_NB, 43); assertTrue(false); } catch(IOException io) {} mount.flock(fd, CephMount.LOCK_SH, 42); // downgrade mount.flock(fd, CephMount.LOCK_SH, 43); mount.flock(fd, CephMount.LOCK_UN, 42); mount.flock(fd, CephMount.LOCK_UN, 43); mount.close(fd); mount.unlink(path); } /* * fstat * * success case is handled in test_stat along with lstat. */ /* * sync_fs */ @Test public void test_sync_fs() throws Exception { mount.sync_fs(); } /* * get/set/list/remove xattr */ @Test public void test_xattr() throws Exception { /* make file */ String path = makePath(); int fd = createFile(path, 123); mount.close(fd); /* make xattrs */ String val1 = "This is a new xattr"; String val2 = "This is a different xattr"; byte[] buf1 = val1.getBytes(); byte[] buf2 = val2.getBytes(); mount.setxattr(path, "user.attr1", buf1, buf1.length, mount.XATTR_CREATE); mount.setxattr(path, "user.attr2", buf2, buf2.length, mount.XATTR_CREATE); /* list xattrs */ String[] xattrs = mount.listxattr(path); assertTrue(xattrs.length == 2); int found = 0; for (String xattr : xattrs) { if (xattr.compareTo("user.attr1") == 0) { found++; continue; } if (xattr.compareTo("user.attr2") == 0) { found++; continue; } System.out.println("found unwanted xattr: " + xattr); } assertTrue(found == 2); /* get first xattr by looking up length */ long attr1_len = mount.getxattr(path, "user.attr1", null); byte[] out = new byte[(int)attr1_len]; mount.getxattr(path, "user.attr1", out); String outStr = new String(out); assertTrue(outStr.compareTo(val1) == 0); /* get second xattr assuming original length */ out = new byte[buf2.length]; mount.getxattr(path, "user.attr2", out); outStr = new String(out); assertTrue(outStr.compareTo(val2) == 0); /* remove the attributes */ /* FIXME: the MDS returns ENODATA for removexattr */ /* mount.removexattr(path, "attr1"); xattrs = mount.listxattr(path); assertTrue(xattrs.length == 1); mount.removexattr(path, "attr2"); xattrs = mount.listxattr(path); assertTrue(xattrs.length == 0); */ mount.unlink(path); } /* * get/set/list/remove symlink xattr * * Currently not working. Code is the same as for regular xattrs, so there * might be a deeper issue. */ @Test public void test_get_stripe_unit() throws Exception { String path = makePath(); int fd = createFile(path, 1); assertTrue(mount.get_file_stripe_unit(fd) > 0); mount.close(fd); mount.unlink(path); } @Test public void test_get_repl() throws Exception { String path = makePath(); int fd = createFile(path, 1); assertTrue(mount.get_file_replication(fd) > 0); mount.close(fd); mount.unlink(path); } /* * stripe unit granularity */ @Test public void test_get_stripe_unit_gran() throws Exception { assertTrue(mount.get_stripe_unit_granularity() > 0); } @Test public void test_get_pool_id() throws Exception { String data_pool_name = getRootPoolName(); /* returns valid pool id */ assertTrue(mount.get_pool_id(data_pool_name) >= 0); /* test non-existent pool name */ try { mount.get_pool_id("asdlfkjlsejflkjef"); assertTrue(false); } catch (CephPoolException e) {} } @Test public void test_get_pool_replication() throws Exception { /* test invalid pool id */ try { mount.get_pool_replication(-1); assertTrue(false); } catch (CephPoolException e) {} /* test valid pool id */ String data_pool_name = getRootPoolName(); int poolid = mount.get_pool_id(data_pool_name); assertTrue(poolid >= 0); assertTrue(mount.get_pool_replication(poolid) > 0); } @Test public void test_get_file_pool_name() throws Exception { String data_pool_name = getRootPoolName(); String path = makePath(); int fd = createFile(path, 1); String pool = mount.get_file_pool_name(fd); mount.close(fd); assertTrue(pool != null); /* assumes using default data pool */ assertTrue(pool.compareTo(data_pool_name) == 0); mount.unlink(path); } @Test(expected=IOException.class) public void test_get_file_pool_name_ebadf() throws Exception { String pool = mount.get_file_pool_name(-40); } @Test public void test_get_file_extent() throws Exception { int stripe_unit = 1<<18; String path = makePath(); int fd = mount.open(path, CephMount.O_WRONLY|CephMount.O_CREAT, 0, stripe_unit, 2, stripe_unit*2, null); CephFileExtent e = mount.get_file_extent(fd, 0); assertTrue(e.getOSDs().length > 0); assertTrue(e.getOffset() == 0); assertTrue(e.getLength() == stripe_unit); e = mount.get_file_extent(fd, stripe_unit/2); assertTrue(e.getOffset() == stripe_unit/2); assertTrue(e.getLength() == stripe_unit/2); e = mount.get_file_extent(fd, 3*stripe_unit/2-1); assertTrue(e.getOffset() == 3*stripe_unit/2-1); assertTrue(e.getLength() == stripe_unit/2+1); e = mount.get_file_extent(fd, 3*stripe_unit/2+1); assertTrue(e.getLength() == stripe_unit/2-1); mount.close(fd); mount.unlink(path); } @Test public void test_get_osd_crush_location() throws Exception { Bucket[] path = mount.get_osd_crush_location(0); assertTrue(path.length > 0); for (Bucket b : path) { assertTrue(b.getType().length() > 0); assertTrue(b.getName().length() > 0); } } @Test public void test_get_osd_address() throws Exception { InetAddress addr = mount.get_osd_address(0); assertTrue(addr.getHostAddress().length() > 0); } }
26,218
24.186359
92
java
null
ceph-main/src/java/test/com/ceph/fs/CephUnmountedTest.java
/* * 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 com.ceph.fs; import org.junit.*; import static org.junit.Assert.*; public class CephUnmountedTest { private CephMount mount; @Before public void setup() throws Exception { mount = new CephMount("admin"); } @Test(expected=CephNotMountedException.class) public void test_unmount() throws Exception { mount.unmount(); } @Test(expected=CephNotMountedException.class) public void test_statfs() throws Exception { CephStatVFS stat = new CephStatVFS(); mount.statfs("/a/path", stat); } @Test(expected=CephNotMountedException.class) public void test_getcwd() throws Exception { mount.getcwd(); } @Test(expected=CephNotMountedException.class) public void test_chdir() throws Exception { mount.chdir("/a/path"); } @Test(expected=CephNotMountedException.class) public void test_listdir() throws Exception { mount.listdir("/a/path"); } @Test(expected=CephNotMountedException.class) public void test_unlink() throws Exception { mount.unlink("/a/path"); } @Test(expected=CephNotMountedException.class) public void test_rename() throws Exception { mount.rename("/a/path", "/another/path"); } @Test(expected=CephNotMountedException.class) public void test_mkdirs() throws Exception { mount.mkdirs("/a/path", 0); } @Test(expected=CephNotMountedException.class) public void test_rmdir() throws Exception { mount.rmdir("/a/path"); } @Test(expected=CephNotMountedException.class) public void test_stat() throws Exception { CephStat stat = new CephStat(); mount.stat("/a/path", stat); } @Test(expected=CephNotMountedException.class) public void test_lstat() throws Exception { CephStat stat = new CephStat(); mount.lstat("/a/path", stat); } @Test(expected=CephNotMountedException.class) public void test_setattr() throws Exception { CephStat stat = new CephStat(); mount.setattr("/a/path", stat, 0); } @Test(expected=CephNotMountedException.class) public void test_open() throws Exception { mount.open("/a/path", 0, 0); } @Test(expected=CephNotMountedException.class) public void test_open_layout() throws Exception { mount.open("/a/path", 0, 0, 0, 0, 0, null); } @Test(expected=CephNotMountedException.class) public void test_close() throws Exception { mount.close(0); } @Test(expected=CephNotMountedException.class) public void test_lseek() throws Exception { mount.lseek(0, 0, CephMount.SEEK_CUR); } @Test(expected=CephNotMountedException.class) public void test_read() throws Exception { byte[] buf = new byte[1]; mount.read(0, buf, 1, 0); } @Test(expected=CephNotMountedException.class) public void test_write() throws Exception { byte[] buf = new byte[1]; mount.write(0, buf, 1, 0); } @Test(expected=CephNotMountedException.class) public void test_get_stripe_unit() throws Exception { mount.get_file_stripe_unit(0); } @Test(expected=CephNotMountedException.class) public void test_get_repl() throws Exception { mount.get_file_replication(0); } @Test(expected=CephNotMountedException.class) public void test_get_stripe_unit_gran() throws Exception { mount.get_stripe_unit_granularity(); } @Test(expected=CephNotMountedException.class) public void test_get_pool_id() throws Exception { mount.get_pool_id("data"); } @Test(expected=CephNotMountedException.class) public void test_get_pool_replication() throws Exception { mount.get_pool_replication(1); } @Test(expected=CephNotMountedException.class) public void test_fchmod() throws Exception { mount.fchmod(1, 0); } @Test(expected=CephNotMountedException.class) public void test_chmod() throws Exception { mount.chmod("/foo", 0); } }
4,869
28.515152
78
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/AndroidMethodReturnValueAnalyses.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.Collections; import java.util.Set; import soot.Scene; import edu.psu.cse.siis.coal.arguments.LanguageConstraints.Call; import edu.psu.cse.siis.coal.arguments.MethodReturnValueAnalysis; import edu.psu.cse.siis.coal.arguments.MethodReturnValueManager; public class AndroidMethodReturnValueAnalyses { public static void registerAndroidMethodReturnValueAnalyses(final String appName) { MethodReturnValueManager.v().registerMethodReturnValueAnalysis( "java.lang.String getPackageName()", new MethodReturnValueAnalysis() { @Override public Set<Object> computeMethodReturnValues(Call call) { if (Scene .v() .getActiveHierarchy() .isClassSubclassOfIncluding( call.stmt.getInvokeExpr().getMethod().getDeclaringClass(), Scene.v().getSootClass("android.content.Context"))) { return Collections.singleton((Object) appName); } else { return null; } } }); } }
1,840
35.098039
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/AuthorityValueAnalysis.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import soot.Unit; import soot.Value; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.Constants; import edu.psu.cse.siis.coal.arguments.Argument; import edu.psu.cse.siis.coal.arguments.ArgumentValueAnalysis; import edu.psu.cse.siis.coal.arguments.ArgumentValueManager; public class AuthorityValueAnalysis extends ArgumentValueAnalysis { private static final Object TOP_VALUE = new DataAuthority(Constants.ANY_STRING, Constants.ANY_STRING); @Override public Set<Object> computeArgumentValues(Argument argument, Unit callSite) { ArgumentValueAnalysis stringAnalysis = ArgumentValueManager.v().getArgumentValueAnalysis( Constants.DefaultArgumentTypes.Scalar.STRING); Stmt stmt = (Stmt) callSite; if (!stmt.containsInvokeExpr()) { throw new RuntimeException("Statement " + stmt + " does not contain an invoke expression"); } InvokeExpr invokeExpr = stmt.getInvokeExpr(); Set<Object> hosts = stringAnalysis.computeVariableValues(invokeExpr.getArg(argument.getArgnum()[0]), stmt); Set<Object> ports = stringAnalysis.computeVariableValues(invokeExpr.getArg(argument.getArgnum()[1]), stmt); Set<Object> result = new HashSet<>(); for (Object host : hosts) { for (Object port : ports) { result.add(new DataAuthority((String) host, (String) port)); } } return result; } @Override public Set<Object> computeInlineArgumentValues(String[] inlineValue) { return new HashSet<Object>(Arrays.asList(inlineValue)); } @Override public Object getTopValue() { return TOP_VALUE; } @Override public Set<Object> computeVariableValues(Value value, Stmt callSite) { throw new RuntimeException("Should not be reached."); } }
2,635
31.146341
97
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/ClassTypeValueAnalysis.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import soot.Scene; import soot.SootClass; import soot.Unit; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.arguments.Argument; import edu.psu.cse.siis.coal.arguments.ArgumentValueAnalysis; public class ClassTypeValueAnalysis extends ArgumentValueAnalysis { private static final String BROADCAST_RECEIVER = "android.content.BroadcastReceiver"; private static final String TOP_VALUE = BROADCAST_RECEIVER; @Override public Set<Object> computeArgumentValues(Argument argument, Unit callSite) { Stmt stmt = (Stmt) callSite; String classType = stmt.getInvokeExpr().getArg(argument.getArgnum()[0]).getType().toString(); if (classType.equals(BROADCAST_RECEIVER)) { List<SootClass> subclasses = Scene.v().getActiveHierarchy() .getSubclassesOf(Scene.v().getSootClass(BROADCAST_RECEIVER)); Set<Object> subclassStrings = new HashSet<>(); for (SootClass sootClass : subclasses) { subclassStrings.add(sootClass.getName()); } if (subclassStrings.size() == 0) { subclassStrings.add(BROADCAST_RECEIVER); } return subclassStrings; } return Collections.singleton((Object) classType); } @Override public Set<Object> computeInlineArgumentValues(String[] inlineValue) { return new HashSet<Object>(Arrays.asList(inlineValue)); } @Override public Object getTopValue() { return TOP_VALUE; } @Override public Set<Object> computeVariableValues(Value value, Stmt callSite) { throw new RuntimeException("Should not be reached."); } }
2,474
31.565789
97
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/ContextValueAnalysis.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import soot.Unit; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.Constants; import edu.psu.cse.siis.coal.arguments.Argument; import edu.psu.cse.siis.coal.arguments.ArgumentValueAnalysis; public class ContextValueAnalysis extends ArgumentValueAnalysis { private static final String TOP_VALUE = Constants.ANY_STRING; private final String appName; public ContextValueAnalysis(String appName) { this.appName = appName != null ? appName : Constants.ANY_STRING; } @Override public Set<Object> computeArgumentValues(Argument argument, Unit callSite) { return Collections.singleton((Object) this.appName); } @Override public Set<Object> computeInlineArgumentValues(String[] inlineValue) { return new HashSet<Object>(Arrays.asList(inlineValue)); } @Override public Object getTopValue() { return TOP_VALUE; } @Override public Set<Object> computeVariableValues(Value value, Stmt callSite) { throw new RuntimeException("Should not be reached."); } }
1,896
28.640625
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/DataAuthority.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.Objects; import edu.psu.cse.siis.coal.Constants; public class DataAuthority { private final String host; private final String port; public DataAuthority(String host, String port) { this.host = host; this.port = port; } public String getHost() { return host; } public String getPort() { return port; } public boolean isPrecise() { return !(Constants.ANY_STRING.equals(host) || Constants.ANY_STRING.equals(port)); } @Override public String toString() { return "host " + host + ", port " + port; } @Override public int hashCode() { return Objects.hash(host, port); } @Override public boolean equals(Object other) { if (!(other instanceof DataAuthority)) { return false; } DataAuthority secondDataAuthority = (DataAuthority) other; return Objects.equals(this.host, secondDataAuthority.host) && Objects.equals(this.port, secondDataAuthority.port); } }
1,738
24.573529
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/EntryPointMappingSceneTransformer.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Hierarchy; import soot.MethodOrMethodContext; import soot.Scene; import soot.SceneTransformer; import soot.SootClass; import soot.SootMethod; import soot.Type; import soot.jimple.infoflow.entryPointCreators.AndroidEntryPointConstants; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Edge; import soot.jimple.toolkits.callgraph.ReachableMethods; import edu.psu.cse.siis.coal.AnalysisParameters; import edu.psu.cse.siis.coal.PropagationTimers; public class EntryPointMappingSceneTransformer extends SceneTransformer { private final Logger logger = LoggerFactory.getLogger(getClass()); private static SootClass activityClass = null; private static SootClass serviceClass = null; private static SootClass gcmBaseIntentServiceClass = null; private static SootClass receiverClass = null; private static SootClass providerClass = null; private static SootClass applicationClass = null; private final Set<String> entryPointClasses; private final Map<String, Set<String>> callbackMethods; private final Map<SootMethod, Set<String>> entryPointMap; private final Set<SootMethod> visitedEntryPoints = new HashSet<>(); public EntryPointMappingSceneTransformer(Set<String> entryPointClasses, Map<String, Set<String>> callbackMethods, Map<SootMethod, Set<String>> entryPointMap) { this.entryPointClasses = entryPointClasses; this.callbackMethods = callbackMethods; this.entryPointMap = entryPointMap; } @Override protected void internalTransform(String phaseName, @SuppressWarnings("rawtypes") Map options) { PropagationTimers.v().totalTimer.start(); Timers.v().entryPointMapping.start(); // Set<String> signatures = new HashSet<>(); Map<SootMethod, Set<String>> entryPointMap = this.entryPointMap; if (logger.isDebugEnabled()) { Set<String> difference = new HashSet<>(this.callbackMethods.keySet()); difference.removeAll(entryPointClasses); if (difference.size() == 0) { logger.debug("Difference size is 0"); } else { logger.debug("Difference is " + difference); } } // Set<String> lifecycleMethods = new HashSet<>(); // lifecycleMethods.addAll(AndroidEntryPointConstants.getActivityLifecycleMethods()); // lifecycleMethods.addAll(AndroidEntryPointConstants.getApplicationLifecycleMethods()); // lifecycleMethods.addAll(AndroidEntryPointConstants.getBroadcastLifecycleMethods()); // lifecycleMethods.addAll(AndroidEntryPointConstants.getContentproviderLifecycleMethods()); // lifecycleMethods.addAll(AndroidEntryPointConstants.getServiceLifecycleMethods()); activityClass = Scene.v().getSootClass(AndroidEntryPointConstants.ACTIVITYCLASS); serviceClass = Scene.v().getSootClass(AndroidEntryPointConstants.SERVICECLASS); gcmBaseIntentServiceClass = Scene.v().getSootClass(AndroidEntryPointConstants.GCMBASEINTENTSERVICECLASS); receiverClass = Scene.v().getSootClass(AndroidEntryPointConstants.BROADCASTRECEIVERCLASS); providerClass = Scene.v().getSootClass(AndroidEntryPointConstants.CONTENTPROVIDERCLASS); applicationClass = Scene.v().getSootClass(AndroidEntryPointConstants.APPLICATIONCLASS); if (logger.isDebugEnabled()) { logger.debug(this.callbackMethods.toString()); } for (String entryPoint : entryPointClasses) { // if (!entryPointClasses.contains(entryPoint)) { // System.err.println("Warning: " + entryPoint + " is not an entry point"); // continue; // } SootClass entryPointClass = Scene.v().getSootClass(entryPoint); List<MethodOrMethodContext> callbacks = new ArrayList<>(); // Add methods for component. boolean knownComponentType = addLifecycleMethods(entryPointClass, callbacks); for (SootMethod method : entryPointClass.getMethods()) { String methodName = method.getName(); if (methodName.equals(SootMethod.constructorName) || methodName.equals(SootMethod.staticInitializerName) || !knownComponentType) { callbacks.add(method); } } Set<String> callbackMethodStrings = this.callbackMethods.get(entryPoint); if (callbackMethodStrings != null) { for (String callbackMethodString : callbackMethodStrings) { if (!Scene.v().containsMethod(callbackMethodString)) { if (logger.isWarnEnabled()) { logger.warn("Warning: " + callbackMethodString + " is not in scene"); } continue; } SootMethod method = Scene.v().getMethod(callbackMethodString); // Add constructors for callbacks. for (SootMethod potentialInit : method.getDeclaringClass().getMethods()) { if (potentialInit.isPrivate()) { continue; } String name = potentialInit.getName(); if (name.equals(SootMethod.constructorName)) { addConstructorStack(potentialInit, callbacks); } else if (name.equals(SootMethod.staticInitializerName)) { callbacks.add(potentialInit); } } callbacks.add(method); } } if (logger.isDebugEnabled()) { logger.debug(callbacks.toString()); } ReachableMethods reachableMethods = new ReachableMethods(Scene.v().getCallGraph(), callbacks.iterator(), null); reachableMethods.update(); for (Iterator<MethodOrMethodContext> iter = reachableMethods.listener(); iter.hasNext();) { SootMethod method = iter.next().method(); if (!AnalysisParameters.v().isAnalysisClass(method.getDeclaringClass().getName())) { continue; } if (logger.isDebugEnabled()) { logger.debug(method.toString()); } Set<String> entryPoints = entryPointMap.get(method); if (entryPoints == null) { entryPoints = new HashSet<>(); entryPointMap.put(method, entryPoints); } entryPoints.add(entryPoint); } } if (logger.isDebugEnabled()) { logger.debug("Entry points"); logger.debug(entryPointMap.toString()); CallGraph cg = Scene.v().getCallGraph(); Iterator<Edge> it = cg.listener(); StringBuilder stringBuilder = new StringBuilder("Call graph:\n"); while (it.hasNext()) { soot.jimple.toolkits.callgraph.Edge e = it.next(); stringBuilder.append("" + e.src() + e.srcStmt() + " =" + e.kind() + "=> " + e.tgt() + "\n"); } logger.debug(stringBuilder.toString()); } Timers.v().entryPointMapping.end(); PropagationTimers.v().totalTimer.end(); } private boolean addLifecycleMethods(SootClass entryPointClass, List<MethodOrMethodContext> callbacks) { boolean result = true; Hierarchy hierarchy = Scene.v().getActiveHierarchy(); if (hierarchy.isClassSubclassOf(entryPointClass, activityClass)) { addLifecycleMethodsHelper(entryPointClass, AndroidEntryPointConstants.getActivityLifecycleMethods(), callbacks); } else if (hierarchy.isClassSubclassOf(entryPointClass, gcmBaseIntentServiceClass)) { addLifecycleMethodsHelper(entryPointClass, AndroidEntryPointConstants.getGCMIntentServiceMethods(), callbacks); } else if (hierarchy.isClassSubclassOf(entryPointClass, serviceClass)) { addLifecycleMethodsHelper(entryPointClass, AndroidEntryPointConstants.getServiceLifecycleMethods(), callbacks); } else if (hierarchy.isClassSubclassOf(entryPointClass, receiverClass)) { addLifecycleMethodsHelper(entryPointClass, AndroidEntryPointConstants.getBroadcastLifecycleMethods(), callbacks); } else if (hierarchy.isClassSubclassOf(entryPointClass, providerClass)) { addLifecycleMethodsHelper(entryPointClass, AndroidEntryPointConstants.getContentproviderLifecycleMethods(), callbacks); } else if (hierarchy.isClassSubclassOf(entryPointClass, applicationClass)) { addLifecycleMethodsHelper(entryPointClass, AndroidEntryPointConstants.getApplicationLifecycleMethods(), callbacks); } else { System.err.println("Unknown entry point type: " + entryPointClass); result = false; } return result; } private void addLifecycleMethodsHelper(SootClass entryPointClass, List<String> lifecycleMethods, List<MethodOrMethodContext> callbacks) { for (String lifecycleMethod : lifecycleMethods) { SootMethod method = findMethod(entryPointClass, lifecycleMethod); if (method != null) { callbacks.add(method); } } } /** * Finds a method with the given signature in the given class or one of its super classes * * @param currentClass The current class in which to start the search * @param subsignature The subsignature of the method to find * @return The method with the given signature if it has been found, otherwise null */ protected SootMethod findMethod(SootClass currentClass, String subsignature) { if (currentClass.declaresMethod(subsignature)) { return currentClass.getMethod(subsignature); } if (currentClass.hasSuperclass()) { return findMethod(currentClass.getSuperclass(), subsignature); } return null; } private void addConstructorStack(SootMethod method, List<MethodOrMethodContext> callbacks) { if (visitedEntryPoints.contains(method)) { return; } callbacks.add(method); visitedEntryPoints.add(method); for (Type type : method.getParameterTypes()) { String typeString = type.toString(); if (AnalysisParameters.v().isAnalysisClass(typeString)) { if (Scene.v().containsClass(typeString)) { SootClass sootClass = Scene.v().getSootClass(typeString); for (SootMethod sootMethod : sootClass.getMethods()) { if (sootMethod.getName().equals(SootMethod.constructorName)) { addConstructorStack(sootMethod, callbacks); } } } else if (logger.isWarnEnabled()) { logger.warn("Warning: " + typeString + " is not in scene"); } } } } }
11,115
38.985612
100
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/Ic3Analysis.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xmlpull.v1.XmlPullParserException; import soot.PackManager; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.Transform; import soot.Value; import soot.jimple.StaticFieldRef; import soot.jimple.infoflow.android.data.AndroidMethod; import soot.jimple.infoflow.android.manifest.ProcessManifest; import soot.options.Options; import edu.psu.cse.siis.coal.Analysis; import edu.psu.cse.siis.coal.AnalysisParameters; import edu.psu.cse.siis.coal.FatalAnalysisException; import edu.psu.cse.siis.coal.PropagationSceneTransformer; import edu.psu.cse.siis.coal.PropagationSceneTransformerFilePrinter; import edu.psu.cse.siis.coal.SymbolFilter; import edu.psu.cse.siis.coal.arguments.ArgumentValueManager; import edu.psu.cse.siis.coal.arguments.MethodReturnValueManager; import edu.psu.cse.siis.coal.field.transformers.FieldTransformerManager; import edu.psu.cse.siis.ic3.db.SQLConnection; import edu.psu.cse.siis.ic3.manifest.ManifestPullParser; public class Ic3Analysis extends Analysis<Ic3CommandLineArguments> { private static final String INTENT = "android.content.Intent"; private static final String INTENT_FILTER = "android.content.IntentFilter"; private static final String BUNDLE = "android.os.Bundle"; private static final String COMPONENT_NAME = "android.content.ComponentName"; private static final String ACTIVITY = "android.app.Activity"; private static final String[] frameworkClassesArray = { INTENT, INTENT_FILTER, BUNDLE, COMPONENT_NAME, ACTIVITY }; protected static final List<String> frameworkClasses = Arrays.asList(frameworkClassesArray); private final Logger logger = LoggerFactory.getLogger(getClass()); private Ic3Data.Application.Builder ic3Builder; private Map<String, Ic3Data.Application.Component.Builder> componentNameToBuilderMap; protected String outputDir; protected Writer writer; protected ManifestPullParser detailedManifest; protected Map<String, Integer> componentToIdMap; protected SetupApplication setupApplication; protected String packageName; @Override protected void registerFieldTransformerFactories(Ic3CommandLineArguments commandLineArguments) { Timers.v().totalTimer.start(); FieldTransformerManager.v().registerDefaultFieldTransformerFactories(); } @Override protected void registerArgumentValueAnalyses(Ic3CommandLineArguments commandLineArguments) { ArgumentValueManager.v().registerDefaultArgumentValueAnalyses(); ArgumentValueManager.v().registerArgumentValueAnalysis("classType", new ClassTypeValueAnalysis()); ArgumentValueManager.v().registerArgumentValueAnalysis("authority", new AuthorityValueAnalysis()); ArgumentValueManager.v().registerArgumentValueAnalysis("Set<authority>", new AuthorityValueAnalysis()); ArgumentValueManager.v().registerArgumentValueAnalysis("path", new PathValueAnalysis()); ArgumentValueManager.v().registerArgumentValueAnalysis("Set<path>", new PathValueAnalysis()); } @Override protected void registerMethodReturnValueAnalyses(Ic3CommandLineArguments commandLineArguments) { MethodReturnValueManager.v().registerDefaultMethodReturnValueAnalyses(); } @Override protected void initializeAnalysis(Ic3CommandLineArguments commandLineArguments) throws FatalAnalysisException { long startTime = System.currentTimeMillis() / 1000; outputDir = commandLineArguments.getOutput(); prepareManifestFile(commandLineArguments); if (commandLineArguments.getProtobufDestination() != null) { ic3Builder = Ic3Data.Application.newBuilder(); ic3Builder.setAnalysisStart(startTime); if (commandLineArguments.getSample() != null) { ic3Builder.setSample(commandLineArguments.getSample()); } componentNameToBuilderMap = detailedManifest.populateProtobuf(ic3Builder); } else if (commandLineArguments.getDb() != null) { SQLConnection.init(commandLineArguments.getDbName(), commandLineArguments.getDb(), commandLineArguments.getSsh(), commandLineArguments.getDbLocalPort()); componentToIdMap = detailedManifest.writeToDb(false); } Timers.v().mainGeneration.start(); setupApplication = new SetupApplication(commandLineArguments.getManifest(), commandLineArguments.getInput(), commandLineArguments.getClasspath()); Map<String, Set<String>> callBackMethods; Set<String> entryPointClasses = null; if (detailedManifest == null) { ProcessManifest manifest; try { manifest = new ProcessManifest(commandLineArguments.getManifest()); entryPointClasses = manifest.getEntryPointClasses(); packageName = manifest.getPackageName(); } catch (IOException | XmlPullParserException e) { throw new FatalAnalysisException("Could not process manifest file " + commandLineArguments.getManifest() + ": " + e); } } else { entryPointClasses = detailedManifest.getEntryPointClasses(); packageName = detailedManifest.getPackageName(); } try { callBackMethods = setupApplication.calculateSourcesSinksEntrypoints(new HashSet<AndroidMethod>(), new HashSet<AndroidMethod>(), packageName, entryPointClasses); } catch (IOException e) { logger.error("Could not calculate entry points", e); throw new FatalAnalysisException(); } Timers.v().mainGeneration.end(); Timers.v().misc.start(); // Application package name is now known. ArgumentValueManager.v().registerArgumentValueAnalysis("context", new ContextValueAnalysis(packageName)); AndroidMethodReturnValueAnalyses.registerAndroidMethodReturnValueAnalyses(packageName); if (outputDir != null && packageName != null) { String outputFile = String.format("%s/%s.csv", outputDir, packageName); try { writer = new BufferedWriter(new FileWriter(outputFile, false)); } catch (IOException e1) { logger.error("Could not open file " + outputFile, e1); } } // reset Soot: soot.G.reset(); Map<SootMethod, Set<String>> entryPointMap = commandLineArguments.computeComponents() ? new HashMap<SootMethod, Set<String>>() : null; addSceneTransformer(entryPointMap); if (commandLineArguments.computeComponents()) { addEntryPointMappingSceneTransformer(entryPointClasses, callBackMethods, entryPointMap); } Options.v().set_no_bodies_for_excluded(true); Options.v().set_allow_phantom_refs(true); Options.v().set_output_format(Options.output_format_none); Options.v().set_whole_program(true); Options.v().set_soot_classpath( commandLineArguments.getInput() + File.pathSeparator + commandLineArguments.getClasspath()); Options.v().set_ignore_resolution_errors(true); Options.v().set_process_dir(frameworkClasses); Options.v().setPhaseOption("cg.spark", "on"); // do not merge variables (causes problems with PointsToSets) Options.v().setPhaseOption("jb.ulp", "off"); Options.v().setPhaseOption("jb.uce", "remove-unreachable-traps:true"); Options.v().setPhaseOption("cg", "trim-clinit:false"); Options.v().set_prepend_classpath(true); if (AnalysisParameters.v().useShimple()) { Options.v().set_via_shimple(true); Options.v().set_whole_shimple(true); } Options.v().set_src_prec(Options.src_prec_java); Timers.v().misc.end(); Timers.v().classLoading.start(); for (String frameworkClass : frameworkClasses) { SootClass c = Scene.v().loadClassAndSupport(frameworkClass); Scene.v().forceResolve(frameworkClass, SootClass.BODIES); c.setApplicationClass(); } Scene.v().loadNecessaryClasses(); Timers.v().classLoading.end(); Timers.v().entryPointMapping.start(); Scene.v().setEntryPoints( Collections.singletonList(setupApplication.getEntryPointCreator().createDummyMain())); Timers.v().entryPointMapping.end(); } protected void prepareManifestFile(Ic3CommandLineArguments commandLineArguments) { if (commandLineArguments.getDb() != null || commandLineArguments.getProtobufDestination() != null) { detailedManifest = new ManifestPullParser(); detailedManifest.loadManifestFile(commandLineArguments.getManifest()); } } @Override protected void setApplicationClasses(Ic3CommandLineArguments commandLineArguments) throws FatalAnalysisException { AnalysisParameters.v().addAnalysisClasses( computeAnalysisClasses(commandLineArguments.getInput())); AnalysisParameters.v().addAnalysisClasses(frameworkClasses); } @Override protected void handleFatalAnalysisException(Ic3CommandLineArguments commandLineArguments, FatalAnalysisException exception) { logger.error("Could not process application " + packageName, exception); if (outputDir != null && packageName != null) { try { if (writer == null) { String outputFile = String.format("%s/%s.csv", outputDir, packageName); writer = new BufferedWriter(new FileWriter(outputFile, false)); } writer.write(commandLineArguments.getInput() + " -1\n"); writer.close(); } catch (IOException e1) { logger.error("Could not write to file after failure to process application", e1); } } } @Override protected void processResults(Ic3CommandLineArguments commandLineArguments) throws FatalAnalysisException { System.out.println("\n*****Manifest*****"); System.out.println(detailedManifest.toString()); if (commandLineArguments.getProtobufDestination() != null) { ProtobufResultProcessor resultProcessor = new ProtobufResultProcessor(); try { resultProcessor.processResult(packageName, ic3Builder, commandLineArguments.getProtobufDestination(), commandLineArguments.binary(), componentNameToBuilderMap, AnalysisParameters.v().getAnalysisClasses().size(), writer); } catch (IOException e) { logger.error("Could not process analysis results", e); throw new FatalAnalysisException(); } } else { ResultProcessor resultProcessor = new ResultProcessor(); try { resultProcessor.processResult(commandLineArguments.getDb() != null, packageName, componentToIdMap, AnalysisParameters.v().getAnalysisClasses().size(), writer); } catch (IOException | SQLException e) { logger.error("Could not process analysis results", e); throw new FatalAnalysisException(); } } } @Override protected void finalizeAnalysis(Ic3CommandLineArguments commandLineArguments) { } protected void addSceneTransformer(Map<SootMethod, Set<String>> entryPointMap) { Ic3ResultBuilder resultBuilder = new Ic3ResultBuilder(); resultBuilder.setEntryPointMap(entryPointMap); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); String debugDirPath = System.getProperty("user.home") + File.separator + "debug"; File debugDir = new File(debugDirPath); if (!debugDir.exists()) { debugDir.mkdir(); } String fileName = dateFormat.format(new Date()) + ".txt"; String debugFilename = debugDirPath + File.separator + fileName; String pack = AnalysisParameters.v().useShimple() ? "wstp" : "wjtp"; Transform transform = new Transform(pack + ".ifds", new PropagationSceneTransformer(resultBuilder, new PropagationSceneTransformerFilePrinter(debugFilename, new SymbolFilter() { @Override public boolean filterOut(Value symbol) { return symbol instanceof StaticFieldRef && ((StaticFieldRef) symbol).getField().getDeclaringClass().getName() .startsWith("android.provider"); } }))); if (PackManager.v().getPack(pack).get(pack + ".ifds") == null) { PackManager.v().getPack(pack).add(transform); } else { Iterator<?> it = PackManager.v().getPack(pack).iterator(); while (it.hasNext()) { Object current = it.next(); if (current instanceof Transform && ((Transform) current).getPhaseName().equals(pack + ".ifds")) { it.remove(); break; } } PackManager.v().getPack(pack).add(transform); } } protected void addEntryPointMappingSceneTransformer(Set<String> entryPointClasses, Map<String, Set<String>> entryPointMapping, Map<SootMethod, Set<String>> entryPointMap) { String pack = AnalysisParameters.v().useShimple() ? "wstp" : "wjtp"; Transform transform = new Transform(pack + ".epm", new EntryPointMappingSceneTransformer(entryPointClasses, entryPointMapping, entryPointMap)); if (PackManager.v().getPack(pack).get(pack + ".epm") == null) { PackManager.v().getPack(pack).add(transform); } else { Iterator<?> it = PackManager.v().getPack(pack).iterator(); while (it.hasNext()) { Object current = it.next(); if (current instanceof Transform && ((Transform) current).getPhaseName().equals(pack + ".epm")) { it.remove(); break; } } PackManager.v().getPack(pack).add(transform); } } }
14,560
38.142473
100
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/Ic3CommandLineArguments.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import org.apache.commons.cli.ParseException; import edu.psu.cse.siis.coal.CommandLineArguments; /** * Command line arguments for IC3. */ public class Ic3CommandLineArguments extends CommandLineArguments { private static final String DEFAULT_SSH_PROPERTIES_PATH = "/db/ssh.properties"; private static final String DEFAULT_DATABASE_PROPERTIES_PATH = "/db/cc.properties"; private static final int DEFAULT_LOCAL_PORT = 3369; private static final String DEFAULT_COMPILED_MODEL_PATH = "/res/icc.cmodel"; private static final String DEFAULT_DB_NAME = "cc"; private String manifest; private String db; private String ssh; private String iccStudy; private int dbLocalPort = DEFAULT_LOCAL_PORT; private boolean computeComponents; private String dbName; private String protobufDestination; private boolean binary; private String sample; public String getDbName() { return dbName != null ? dbName : DEFAULT_DB_NAME; } /** * Gets the path to the manifest or .apk file. * * @return The path to the manifest or .apk file. */ public String getManifest() { return manifest; } /** * Gets the path to the database properties file. * * @return The path to the database properties file if IC3 should output its results to a * database, null otherwise. */ public String getDb() { return db; } /** * Gets the path to the SSH properties file. * * @return The path to the SSH properties file if an SSH connection is requested, null otherwise. */ public String getSsh() { return ssh; } public String getIccStudy() { return iccStudy; } /** * Gets the local port to which the database connection should be done. * * @return The local port to connect to. */ public int getDbLocalPort() { return dbLocalPort; } /** * Determines if mappings between ICC-sending locations and the components that contain them * should be computed. * * @return True if the components that contain ICC-sending locations should be determined. */ public boolean computeComponents() { return computeComponents; } /** * Returns the destination protocol buffer file path. * * @return The destination path if any, otherwise null. */ public String getProtobufDestination() { return protobufDestination; } /** * Determines if the output should be binary, in the case of a protobuf output. * * @return True if the output should be binary. */ public boolean binary() { return binary; } /** * Returns the name of the sample. * * @return The sample name, if any, otherwise null. */ public String getSample() { return sample; } /** * Process the command line arguments after initial parsing. This should be called be actually * using the arguments contained in this class. */ public void processCommandLineArguments() { manifest = getOptionValue("apkormanifest"); if (getCompiledModel() == null && getModel() == null) { setCompiledModel(DEFAULT_COMPILED_MODEL_PATH); } iccStudy = getOptionValue("iccstudy"); if (hasOption("db")) { db = getOptionValue("db", DEFAULT_DATABASE_PROPERTIES_PATH); } if (hasOption("ssh")) { ssh = getOptionValue("ssh", DEFAULT_SSH_PROPERTIES_PATH); } if (hasOption("localport")) { try { dbLocalPort = ((Number) getParsedOptionValue("localport")).intValue(); } catch (ParseException e) { e.printStackTrace(); } } if (hasOption("dbname")) { dbName = getOptionValue("dbname", DEFAULT_DB_NAME); } computeComponents = hasOption("computecomponents") || db != null; if (hasOption("protobuf")) { protobufDestination = getOptionValue("protobuf"); } computeComponents = hasOption("computecomponents") || db != null || protobufDestination != null; binary = hasOption("binary"); sample = getOptionValue("sample"); } }
4,758
26.508671
100
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/Ic3CommandLineParser.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import edu.psu.cse.siis.coal.CommandLineParser; /** * Command line parser for IC3. */ public class Ic3CommandLineParser extends CommandLineParser<Ic3CommandLineArguments> { private static final String COPYRIGHT = "Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin\n" + "Systems and Internet Infrastructure Security Laboratory\n"; @Override protected void parseAnalysisSpecificArguments(Options options) { options.addOption(Option.builder("apkormanifest") .desc("Path to the manifest file or the .apk of the application.").hasArg() .argName(".apk or manifest").required().build()); options.addOption(Option.builder("db").desc("Store entry points to database.").hasArg() .optionalArg(true).argName("DB properties file").build()); options.addOption(Option.builder("ssh").desc("Use SSH to connect to the database.").hasArg() .optionalArg(true).argName("SSH properties file").build()); options.addOption(Option.builder("localport").desc("Local DB port to connect to.").hasArg() .type(Number.class).argName("local DB port").build()); options.addOption(Option.builder("protobuf").desc("Destination path for the results.").hasArg() .argName("destination path").build()); options.addOption(Option.builder("sample").desc("Specify a sample name.").hasArg() .argName("sample name").build()); options.addOption(Option.builder("dbname").desc("DB name to connect to.").hasArg() .type(Number.class).argName("DB name").build()); options.addOption("computecomponents", false, "Compute which components each exit point belongs to."); options.addOption("binary", false, "Output a binary protobuf."); } @Override protected void printHelp(Options options) { HelpFormatter formatter = new HelpFormatter(); System.out.println(COPYRIGHT); formatter.printHelp("ic3 -input <Android directory> -classpath <classpath> " + "-apk <path to application .apk> [-computecomponents] " + "[-db <path to DB properties file>] [-ssh <path to SSH properties file>] " + "[-localport <DB local port>] [-modeledtypesonly] [-output <output directory>] " + "[-protobuf <destination path>] [-binary] [-sample <sample name>] " + "[-threadcount <thread count>]", options); } }
3,248
46.086957
99
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/Ic3Result.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import soot.SootMethod; import soot.Unit; import edu.psu.cse.siis.coal.AnalysisParameters; import edu.psu.cse.siis.coal.Result; import edu.psu.cse.siis.coal.arguments.Argument; public class Ic3Result extends Result { private final Map<SootMethod, Set<String>> entryPointMap; private final Map<Unit, Map<Integer, Object>> result = new HashMap<>(); private String statistics; public Ic3Result(Map<SootMethod, Set<String>> entryPointMap) { this.entryPointMap = entryPointMap; } @Override public Map<Unit, Map<Integer, Object>> getResults() { return result; } @Override public Object getResult(Unit unit, Argument argument) { Map<Integer, Object> unitResult = result.get(unit); if (unitResult != null) { return unitResult.get(argument.getArgnum()); } return null; } @Override public String getStatistics() { return statistics; } public Map<SootMethod, Set<String>> getEntryPointMap() { return entryPointMap; } @Override public void addResult(Unit unit, int argnum, Object value) { Map<Integer, Object> unitResult = result.get(unit); if (unitResult == null) { unitResult = new HashMap<>(); result.put(unit, unitResult); } unitResult.put(argnum, value); } @Override public void setStatistics(String statistics) { this.statistics = statistics; } public void dump() { System.out.println("*****Result*****"); List<String> results = new ArrayList<>(); boolean outputComponents = entryPointMap != null; for (Map.Entry<Unit, Map<Integer, Object>> entry : result.entrySet()) { Unit unit = entry.getKey(); SootMethod method = AnalysisParameters.v().getIcfg().getMethodOf(unit); String current = method.getDeclaringClass().getName() + "/" + method.getSubSignature() + " : " + unit + "\n"; if (outputComponents) { Set<String> components = entryPointMap.get(method); if (components != null) { current += "Components: " + components + "\n"; } else { current += "Unknown components" + "\n"; } } for (Map.Entry<Integer, Object> entry2 : entry.getValue().entrySet()) { current += " " + entry2.getKey() + " : " + entry2.getValue() + "\n"; } results.add(current); } Collections.sort(results); for (String result : results) { System.out.println(result); } } }
3,360
28.226087
94
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/Ic3ResultBuilder.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import soot.MethodOrMethodContext; import soot.Scene; import soot.SootMethod; import soot.Unit; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; import soot.jimple.toolkits.callgraph.ReachableMethods; import soot.toolkits.graph.ExceptionalUnitGraph; import edu.psu.cse.siis.coal.AnalysisParameters; import edu.psu.cse.siis.coal.Model; import edu.psu.cse.siis.coal.PropagationSolver; import edu.psu.cse.siis.coal.PropagationTimers; import edu.psu.cse.siis.coal.Result; import edu.psu.cse.siis.coal.ResultBuilder; import edu.psu.cse.siis.coal.arguments.Argument; import edu.psu.cse.siis.coal.arguments.ArgumentValueManager; import edu.psu.cse.siis.coal.values.BasePropagationValue; import edu.psu.cse.siis.coal.values.PropagationValue; public class Ic3ResultBuilder implements ResultBuilder { private Map<SootMethod, Set<String>> entryPointMap; public void setEntryPointMap(Map<SootMethod, Set<String>> entryPointMap) { this.entryPointMap = entryPointMap; } @Override public Result buildResult(PropagationSolver solver) { PropagationTimers.v().resultGeneration.start(); Result result = new Ic3Result(entryPointMap); List<MethodOrMethodContext> eps = new ArrayList<MethodOrMethodContext>(Scene.v().getEntryPoints()); ReachableMethods reachableMethods = new ReachableMethods(Scene.v().getCallGraph(), eps.iterator(), null); reachableMethods.update(); long reachableStatements = 0; for (Iterator<MethodOrMethodContext> iter = reachableMethods.listener(); iter.hasNext();) { SootMethod method = iter.next().method(); if (method.hasActiveBody() && !Model.v().isExcludedClass(method.getDeclaringClass().getName()) && !method.getDeclaringClass().getName().equals("dummyMainClass") && !method.getDeclaringClass().getName().startsWith("android.support") && !method.getDeclaringClass().getName().startsWith("android.provider")) { ++PropagationTimers.v().reachableMethods; ExceptionalUnitGraph cfg = new ExceptionalUnitGraph(method.getActiveBody()); Stack<Unit> stack = new Stack<>(); for (Unit unit : cfg.getHeads()) { stack.push(unit); } Set<Unit> visited = new HashSet<>(); while (!stack.empty()) { Unit unit = stack.pop(); if (visited.contains(unit)) { continue; } else { visited.add(unit); } for (Unit successor : cfg.getSuccsOf(unit)) { stack.push(successor); } Argument[] arguments = Model.v().getArgumentsForQuery((Stmt) unit); if (arguments != null) { boolean foundModeledType = false; for (Argument argument : arguments) { if (Model.v().isModeledType(argument.getType())) { foundModeledType = true; break; } } Stmt stmt = (Stmt) unit; for (Argument argument : arguments) { if (Model.v().isModeledType(argument.getType())) { int argnum = argument.getArgnum()[0]; BasePropagationValue basePropagationValue; InvokeExpr invokeExpr = stmt.getInvokeExpr(); if (argnum >= 0) { basePropagationValue = solver.resultAt(unit, invokeExpr.getArg(argnum)); } else if (invokeExpr instanceof InstanceInvokeExpr && argnum == -1) { InstanceInvokeExpr instanceInvokeExpr = (InstanceInvokeExpr) invokeExpr; basePropagationValue = solver.resultAt(stmt, instanceInvokeExpr.getBase()); } else { throw new RuntimeException("Unexpected argument number " + argnum + " for invoke expression " + invokeExpr); } if (basePropagationValue instanceof PropagationValue) { PropagationValue propagationValue = (PropagationValue) basePropagationValue; PropagationTimers.v().resultGeneration.end(); PropagationTimers.v().valueComposition.start(); propagationValue.makeFinalValue(solver); PropagationTimers.v().valueComposition.end(); PropagationTimers.v().resultGeneration.start(); result.addResult(unit, argument.getArgnum()[0], propagationValue); } else { result.addResult(unit, argument.getArgnum()[0], basePropagationValue); } } else if (foundModeledType || AnalysisParameters.v().inferNonModeledTypes()) { // We infer non-modeled types if one of the arguments of the query is a modeled type // or if the analysis settings tell us to do so. result.addResult(unit, argument.getArgnum()[0], ArgumentValueManager.v() .getArgumentValues(argument, unit)); } } } } reachableStatements += visited.size(); } PropagationTimers.v().reachableStatements += reachableStatements; } PropagationTimers.v().resultGeneration.end(); return result; } }
6,182
39.149351
100
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/Main.java
package edu.psu.cse.siis.ic3; public class Main { public static void main(String[] args) { Ic3Analysis analysis = new Ic3Analysis(); Ic3CommandLineParser parser = new Ic3CommandLineParser(); Ic3CommandLineArguments commandLineArguments = parser.parseCommandLine(args, Ic3CommandLineArguments.class); if (commandLineArguments == null) { return; } commandLineArguments.processCommandLineArguments(); analysis.performAnalysis(commandLineArguments); } }
498
28.352941
69
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/PathValueAnalysis.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import soot.Unit; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.Constants; import edu.psu.cse.siis.coal.arguments.Argument; import edu.psu.cse.siis.coal.arguments.ArgumentValueAnalysis; import edu.psu.cse.siis.coal.arguments.ArgumentValueManager; public class PathValueAnalysis extends ArgumentValueAnalysis { private static final String TOP_VALUE = Constants.ANY_STRING; private static final int PATTERN_LITERAL = 0; private static final int PATTERN_PREFIX = 1; private static final int PATTERN_SIMPLE_GLOB = 2; @Override public Set<Object> computeArgumentValues(Argument argument, Unit callSite) { Argument argument0 = new Argument(argument); argument0.setArgnum(new int[] { argument.getArgnum()[0] }); argument0.setType(Constants.DefaultArgumentTypes.Scalar.STRING); Argument argument1 = new Argument(argument); argument1.setArgnum(new int[] { argument.getArgnum()[1] }); argument1.setType(Constants.DefaultArgumentTypes.Scalar.INT); Set<Object> paths = ArgumentValueManager.v().getArgumentValues(argument0, callSite); Set<Object> types = ArgumentValueManager.v().getArgumentValues(argument1, callSite); Set<Object> result = new HashSet<>(); for (Object path : paths) { for (Object type : types) { result.add(computePathForType((String) path, (Integer) type)); } } return result; } private String computePathForType(String path, int type) { if (type == PATTERN_LITERAL || type == PATTERN_SIMPLE_GLOB) { return path; } else if (type == PATTERN_PREFIX || type == Constants.ANY_INT) { if (path.equals(Constants.ANY_STRING)) { return Constants.ANY_STRING; } else { return String.format("%s(.*)", path); } } else { throw new RuntimeException("Unknown path type: " + type); } } @Override public Set<Object> computeInlineArgumentValues(String[] inlineValue) { return new HashSet<Object>(Arrays.asList(inlineValue)); } @Override public Object getTopValue() { return TOP_VALUE; } @Override public Set<Object> computeVariableValues(Value value, Stmt callSite) { throw new RuntimeException("Should not be reached."); } }
3,071
32.032258
88
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/ProtobufResultProcessor.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Scene; import soot.SootMethod; import soot.Type; import soot.Unit; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; import com.google.protobuf.TextFormat; import edu.psu.cse.siis.coal.AnalysisParameters; import edu.psu.cse.siis.coal.Constants; import edu.psu.cse.siis.coal.Model; import edu.psu.cse.siis.coal.PropagationTimers; import edu.psu.cse.siis.coal.Result; import edu.psu.cse.siis.coal.Results; import edu.psu.cse.siis.coal.arguments.Argument; import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.ScalarFieldValue; import edu.psu.cse.siis.coal.field.values.TopFieldValue; import edu.psu.cse.siis.coal.values.BasePropagationValue; import edu.psu.cse.siis.coal.values.BottomPropagationValue; import edu.psu.cse.siis.coal.values.PathValue; import edu.psu.cse.siis.coal.values.PropagationValue; import edu.psu.cse.siis.coal.values.TopPropagationValue; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component.ComponentKind; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component.ExitPoint; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component.ExitPoint.Intent; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component.ExitPoint.Uri; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component.Extra; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component.Instruction; import edu.psu.cse.siis.ic3.Ic3Data.Attribute; import edu.psu.cse.siis.ic3.Ic3Data.AttributeKind; import edu.psu.cse.siis.ic3.manifest.ManifestComponent; import edu.psu.cse.siis.ic3.manifest.ManifestData; import edu.psu.cse.siis.ic3.manifest.ManifestIntentFilter; import edu.psu.cse.siis.ic3.manifest.ManifestPullParser; public class ProtobufResultProcessor { private final Logger logger = LoggerFactory.getLogger(getClass()); private static final String ENTRY_POINT_INTENT = "<INTENT>"; private final int[] preciseNonLinking = { 0, 0, 0, 0 }; private final int[] preciseLinking = { 0, 0, 0, 0 }; private final int[] imprecise = { 0, 0, 0, 0, 0 }; private final int[] top = { 0, 0, 0 }; private final int[] bottom = { 0, 0, 0 }; private final int[] nonexistent = { 0, 0, 0 }; private final int[] preciseFieldValueCount = { 0, 0, 0 }; private final int[] partiallyPreciseFieldValueCount = { 0, 0, 0 }; private final int[] impreciseFieldValueCount = { 0, 0, 0 }; private int intentWithData = 0; private int providerArgument = 0; public void processResult(String appName, Ic3Data.Application.Builder ic3Builder, String protobufDestination, boolean binary, Map<String, Ic3Data.Application.Component.Builder> componentNameToBuilderMap, int analysisClassesCount, Writer writer) throws IOException { for (Result result : Results.getResults()) { ((Ic3Result) result).dump(); analyzeResult(result); writeResultToProtobuf(result, ic3Builder, componentNameToBuilderMap); } ic3Builder.setAnalysisEnd(System.currentTimeMillis() / 1000); String extension = binary ? "dat" : "txt"; String path = String.format("%s/%s_%s.%s", protobufDestination, ic3Builder.getName(), ic3Builder.getVersion(), extension); System.out.println("PATH: " + path); if (binary) { FileOutputStream fileOutputStream = new FileOutputStream(path); ic3Builder.build().writeTo(fileOutputStream); fileOutputStream.close(); } else { FileWriter fileWriter = new FileWriter(path); TextFormat.print(ic3Builder, fileWriter); fileWriter.close(); } Timers.v().totalTimer.end(); String statistics = appName + " " + analysisClassesCount + " " + PropagationTimers.v().reachableMethods + " " + preciseNonLinking[0] + " " + preciseNonLinking[3] + " " + preciseNonLinking[1] + " " + preciseNonLinking[2] + " " + preciseLinking[0] + " " + preciseLinking[3] + " " + preciseLinking[1] + " " + preciseLinking[2] + " " + imprecise[0] + " " + imprecise[3] + " " + imprecise[1] + " " + imprecise[2] + " " + bottom[0] + " " + bottom[1] + " " + bottom[2] + " " + top[0] + " " + top[1] + " " + top[2] + " " + nonexistent[0] + " " + nonexistent[1] + " " + nonexistent[2] + " " + providerArgument + " " + imprecise[4] + " " + preciseFieldValueCount[0] + " " + preciseFieldValueCount[1] + " " + preciseFieldValueCount[2] + " " + partiallyPreciseFieldValueCount[0] + " " + partiallyPreciseFieldValueCount[1] + " " + partiallyPreciseFieldValueCount[2] + " " + impreciseFieldValueCount[0] + " " + impreciseFieldValueCount[1] + " " + impreciseFieldValueCount[2] + " " + PropagationTimers.v().modelParsing.getTime() + " " + Timers.v().mainGeneration.getTime() + " " + Timers.v().entryPointMapping.getTime() + " " + Timers.v().classLoading.getTime() + " " + PropagationTimers.v().problemGeneration.getTime() + " " + PropagationTimers.v().ideSolution.getTime() + " " + PropagationTimers.v().valueComposition.getTime() + " " + PropagationTimers.v().resultGeneration.getTime() + " " + (PropagationTimers.v().soot.getTime() - PropagationTimers.v().totalTimer.getTime()) + " " + (Timers.v().misc.getTime() + PropagationTimers.v().misc.getTime()) + " " + Timers.v().totalTimer.getTime() + "\n"; if (logger.isInfoEnabled()) { logger.info(statistics); } if (writer != null) { writer.write(statistics); writer.close(); } } @SuppressWarnings("unchecked") private void writeResultToProtobuf(Result result, Ic3Data.Application.Builder ic3Builder, Map<String, Component.Builder> componentNameToBuilderMap) { Map<String, Set<Extra>> componentToExtrasMap = new HashMap<>(); Map<String, ManifestComponent> dynamicReceivers = new HashMap<>(); Map<SootMethod, Set<String>> entryPointMap = ((Ic3Result) result).getEntryPointMap(); for (Map.Entry<Unit, Map<Integer, Object>> entry : result.getResults().entrySet()) { Unit unit = entry.getKey(); Argument[] arguments = Model.v().getArgumentsForQuery((Stmt) unit); if (arguments != null) { SootMethod method = AnalysisParameters.v().getIcfg().getMethodOf(unit); Instruction.Builder instructionBuilder = unitToInstructionBuilder(method, unit); Map<String, Object> valueMap = new HashMap<>(arguments.length); Map<Integer, Object> argnumToValueMap = entry.getValue(); for (Argument argument : arguments) { valueMap.put(argument.getProperty("valueType"), argnumToValueMap.get(argument.getArgnum()[0])); } if (valueMap.containsKey("activity")) { insertProtobufExitPoint(instructionBuilder, (BasePropagationValue) valueMap.get("activity"), ComponentKind.ACTIVITY, null, null, entryPointMap.get(method), componentNameToBuilderMap); } else if (valueMap.containsKey("service")) { insertProtobufExitPoint(instructionBuilder, (BasePropagationValue) valueMap.get("service"), ComponentKind.SERVICE, null, null, entryPointMap.get(method), componentNameToBuilderMap); } else if (valueMap.containsKey("receiver")) { insertProtobufExitPoint(instructionBuilder, (BasePropagationValue) valueMap.get("receiver"), ComponentKind.RECEIVER, (Set<String>) valueMap.get("permission"), null, entryPointMap.get(method), componentNameToBuilderMap); } else if (valueMap.containsKey("intentFilter")) { insertDynamicReceiver(dynamicReceivers, (Set<String>) valueMap.get("permission"), (Set<String>) valueMap.get("receiverType"), (BasePropagationValue) valueMap.get("intentFilter"), method, unit); } else if (valueMap.containsKey("provider")) { insertProtobufExitPoint(instructionBuilder, (BasePropagationValue) valueMap.get("provider"), ComponentKind.PROVIDER, null, null, entryPointMap.get(method), componentNameToBuilderMap); } else if (valueMap.containsKey("authority")) { insertProtobufExitPoint(instructionBuilder, getUriValueForAuthorities((Set<String>) valueMap.get("authority")), ComponentKind.PROVIDER, null, null, entryPointMap.get(method), componentNameToBuilderMap); } else if (valueMap.containsKey("pendingIntent")) { BasePropagationValue baseCollectingValue = (BasePropagationValue) valueMap.get("pendingIntent"); String targetType = baseCollectingValue instanceof PropagationValue ? (String) ((PropagationValue) baseCollectingValue) .getValuesForField("targetType").iterator().next().getValue() : null; Set<String> permissions = (Set<String>) valueMap.get("permission"); if (targetType != null) { insertProtobufExitPoint(instructionBuilder, baseCollectingValue, stringToComponentKind(targetType), permissions, null, entryPointMap.get(method), componentNameToBuilderMap); } else { for (ComponentKind target : Arrays.asList(ComponentKind.ACTIVITY, ComponentKind.RECEIVER, ComponentKind.SERVICE)) { insertProtobufExitPoint(instructionBuilder, baseCollectingValue, target, null, null, entryPointMap.get(method), componentNameToBuilderMap); } } } else if (valueMap.containsKey("componentExtra")) { Set<String> extras = (Set<String>) valueMap.get("componentExtra"); if (extras != null) { for (String component : entryPointMap.get(method)) { Set<Extra> existingExtras = componentToExtrasMap.get(component); if (existingExtras == null) { existingExtras = new HashSet<>(); componentToExtrasMap.put(component, existingExtras); } for (String extra : extras) { Extra.Builder extraBuilder = Extra.newBuilder(); extraBuilder.setExtra(extra); extraBuilder.setInstruction(instructionBuilder); existingExtras.add(extraBuilder.build()); } } } } } } for (Map.Entry<String, Set<Extra>> entry : componentToExtrasMap.entrySet()) { componentNameToBuilderMap.get(entry.getKey()).addAllExtras(entry.getValue()); } for (Component.Builder componentBuilder : componentNameToBuilderMap.values()) { ic3Builder.addComponents(componentBuilder); } for (ManifestComponent manifestComponent : dynamicReceivers.values()) { Component.Builder componentBuilder = ManifestPullParser.makeProtobufComponentBuilder(manifestComponent, ComponentKind.DYNAMIC_RECEIVER); componentBuilder.setRegistrationInstruction(unitToInstructionBuilder( manifestComponent.getRegistrationMethod(), manifestComponent.getRegistrationUnit())); ic3Builder.addComponents(componentBuilder); } } private Instruction.Builder unitToInstructionBuilder(SootMethod method, Unit unit) { Instruction.Builder builder = Instruction.newBuilder(); builder.setClassName(method.getDeclaringClass().getName()); builder.setMethod(method.getSignature()); builder.setStatement(unit.toString()); builder.setId(getIdForUnit(unit, method)); return builder; } private void insertProtobufExitPoint(Instruction.Builder instructionBuilder, BasePropagationValue intentValue, ComponentKind componentKind, Set<String> intentPermissions, Integer missingIntents, Set<String> exitPointComponents, Map<String, Component.Builder> componentNameToBuilderMap) { for (String exitPointComponent : exitPointComponents) { ExitPoint.Builder exitPointBuilder = ExitPoint.newBuilder(); exitPointBuilder.setInstruction(instructionBuilder).setKind(componentKind); PropagationValue collectingValue = null; if (intentValue == null || intentValue instanceof TopPropagationValue || intentValue instanceof BottomPropagationValue) { missingIntents = 0; } else if (intentValue instanceof PropagationValue) { collectingValue = (PropagationValue) intentValue; if (collectingValue.getPathValues() == null || collectingValue.getPathValues().size() == 0) { missingIntents = 0; } } else { throw new RuntimeException("Unknown CollectingValue type: " + intentValue.getClass()); } if (missingIntents != null) { exitPointBuilder.setMissing(missingIntents); } else { Set<PathValue> pathValues = collectingValue.getPathValues(); if (pathValues != null) { for (PathValue pathValue : pathValues) { if (componentKind.equals(ComponentKind.PROVIDER)) { exitPointBuilder.addUris(makeProtobufUriBuilder(pathValue)); } else { if (intentPermissions != null && intentPermissions.size() != 0) { for (String intentPermission : intentPermissions) { exitPointBuilder.addIntents(makeProtobufIntentBuilder(pathValue).setPermission( intentPermission)); } } else { exitPointBuilder.addIntents(makeProtobufIntentBuilder(pathValue)); } } } } } Component.Builder componentBuilder = componentNameToBuilderMap.get(exitPointComponent); componentBuilder.addExitPoints(exitPointBuilder); } } private Intent.Builder makeProtobufIntentBuilder(PathValue intentValue) { Intent.Builder intentBuilder = Intent.newBuilder(); insertSingleValuedIntentAttribute(intentValue, "action", AttributeKind.ACTION, intentBuilder); Set<String> categories = intentValue.getSetStringFieldValue("categories"); if (categories != null) { if (categories.contains(null)) { categories.remove(null); categories.add(Constants.NULL_STRING); } intentBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.CATEGORY) .addAllValue(categories)); } Set<Integer> flags = intentValue.getSetFieldValue("flags", Integer.class); if (flags != null) { intentBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.FLAG) .addAllIntValue(flags)); } // String mimeType = intentValue.getSingleStringFieldValue("dataType"); // if (mimeType != null) { // String[] typeParts = mimeType.split("/"); // String type; // String subtype; // if (typeParts.length == 2) { // type = typeParts[0]; // subtype = typeParts[1]; // } else { // type = Constants.ANY_STRING; // subtype = Constants.ANY_STRING; // } // intentBuilder // .addAttributes(Attribute.newBuilder().setKind(AttributeKind.TYPE).addValue(type)); // intentBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.SUBTYPE) // .addValue(subtype)); // } insertSingleValuedIntentAttribute(intentValue, "dataType", AttributeKind.TYPE, intentBuilder); Set<String> extras = intentValue.getSetStringFieldValue("extras"); if (extras != null) { if (extras.contains(null)) { extras.remove(null); extras.add(Constants.NULL_STRING); } intentBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.EXTRA) .addAllValue(extras)); } insertSingleValuedIntentAttribute(intentValue, "clazz", AttributeKind.CLASS, intentBuilder); insertSingleValuedIntentAttribute(intentValue, "package", AttributeKind.PACKAGE, intentBuilder); insertSingleValuedIntentAttribute(intentValue, "scheme", AttributeKind.SCHEME, intentBuilder); insertSingleValuedIntentAttribute(intentValue, "ssp", AttributeKind.SSP, intentBuilder); insertSingleValuedIntentAttribute(intentValue, "uri", AttributeKind.URI, intentBuilder); insertSingleValuedIntentAttribute(intentValue, "path", AttributeKind.PATH, intentBuilder); insertSingleValuedIntentAttribute(intentValue, "query", AttributeKind.QUERY, intentBuilder); insertSingleValuedIntentAttribute(intentValue, "authority", AttributeKind.AUTHORITY, intentBuilder); return intentBuilder; } private void insertSingleValuedIntentAttribute(PathValue pathValue, String attribute, AttributeKind kind, Intent.Builder intentBuilder) { String attributeValue = pathValue.getScalarStringFieldValue(attribute); if (attributeValue != null) { intentBuilder.addAttributes(Attribute.newBuilder().setKind(kind).addValue(attributeValue)); } } private Uri.Builder makeProtobufUriBuilder(PathValue uriValue) { Uri.Builder uriBuilder = Uri.newBuilder(); insertSingleValuedUriAttribute(uriValue, "scheme", AttributeKind.SCHEME, uriBuilder); insertSingleValuedUriAttribute(uriValue, "ssp", AttributeKind.SSP, uriBuilder); insertSingleValuedUriAttribute(uriValue, "uri", AttributeKind.URI, uriBuilder); insertSingleValuedUriAttribute(uriValue, "path", AttributeKind.PATH, uriBuilder); insertSingleValuedUriAttribute(uriValue, "query", AttributeKind.QUERY, uriBuilder); insertSingleValuedUriAttribute(uriValue, "authority", AttributeKind.AUTHORITY, uriBuilder); return uriBuilder; } private void insertSingleValuedUriAttribute(PathValue pathValue, String attribute, AttributeKind kind, Uri.Builder uriBuilder) { String attributeValue = pathValue.getScalarStringFieldValue(attribute); if (attributeValue != null) { uriBuilder.addAttributes(Attribute.newBuilder().setKind(kind).addValue(attributeValue)); } } private ComponentKind stringToComponentKind(String componentKind) { switch (componentKind) { case "a": return ComponentKind.ACTIVITY; case "s": return ComponentKind.SERVICE; case "r": return ComponentKind.RECEIVER; default: throw new RuntimeException("Unknown component kind: " + componentKind); } } private void insertDynamicReceiver(Map<String, ManifestComponent> dynamicReceivers, Set<String> permissions, Set<String> receiverTypes, BasePropagationValue intentFilters, SootMethod method, Unit unit) { if (permissions == null) { permissions = Collections.singleton(null); } for (String receiverType : receiverTypes) { for (String permission : permissions) { insertDynamicReceiverHelper(dynamicReceivers, permission, receiverType, intentFilters, method, unit); } } } private void insertDynamicReceiverHelper(Map<String, ManifestComponent> dynamicReceivers, String permission, String receiverType, BasePropagationValue intentFilters, SootMethod method, Unit unit) { Integer missingIntentFilters; Set<ManifestIntentFilter> manifestIntentFilters; if (intentFilters == null || intentFilters instanceof TopPropagationValue || intentFilters instanceof BottomPropagationValue) { missingIntentFilters = 0; manifestIntentFilters = null; } else if (intentFilters instanceof PropagationValue) { missingIntentFilters = null; PropagationValue collectingValue = (PropagationValue) intentFilters; manifestIntentFilters = new HashSet<>(); for (PathValue branchValue : collectingValue.getPathValues()) { Integer filterPriority = null; FieldValue priorityFieldValue = branchValue.getFieldValue("priority"); if (priorityFieldValue != null) { filterPriority = (Integer) priorityFieldValue.getValue(); } manifestIntentFilters.add(new ManifestIntentFilter(branchValue .getSetStringFieldValue("actions"), branchValue.getSetStringFieldValue("categories"), false, makeManifestData(branchValue), filterPriority)); } } else { throw new RuntimeException("Unknown intent filter type: " + intentFilters.getClass()); } ManifestComponent manifestComponent = dynamicReceivers.get(receiverType); if (manifestComponent == null) { manifestComponent = new ManifestComponent( edu.psu.cse.siis.ic3.db.Constants.ComponentShortType.DYNAMIC_RECEIVER, receiverType, true, true, permission, null, missingIntentFilters, method, unit); dynamicReceivers.put(receiverType, manifestComponent); } manifestComponent.addIntentFilters(manifestIntentFilters); } private List<ManifestData> makeManifestData(PathValue branchValue) { Set<String> mimeTypes = branchValue.getSetStringFieldValue("dataType"); Set<DataAuthority> authorities = branchValue.getSetFieldValue("authorities", DataAuthority.class); Set<String> paths = branchValue.getSetStringFieldValue("paths"); Set<String> schemes = branchValue.getSetStringFieldValue("schemes"); if (mimeTypes == null && authorities == null && paths == null && schemes == null) { return null; } if (mimeTypes == null) { mimeTypes = Collections.singleton(null); } if (authorities == null) { authorities = Collections.singleton(new DataAuthority(null, null)); } if (paths == null) { paths = Collections.singleton(null); } if (schemes == null) { schemes = Collections.singleton(null); } List<ManifestData> result = new ArrayList<>(); for (String mimeType : mimeTypes) { for (DataAuthority dataAuthority : authorities) { for (String dataPath : paths) { for (String scheme : schemes) { result.add(new ManifestData(scheme, dataAuthority.getHost(), dataAuthority.getPort(), dataPath, mimeType)); } } } } return result; } private BasePropagationValue getUriValueForAuthorities(Set<String> authorities) { if (authorities == null) { return null; } PropagationValue collectingValue = new PropagationValue(); for (String authority : authorities) { PathValue branchValue = new PathValue(); ScalarFieldValue schemeFieldValue = new ScalarFieldValue("content"); branchValue.addFieldEntry("scheme", schemeFieldValue); ScalarFieldValue authorityFieldValue = new ScalarFieldValue(authority); branchValue.addFieldEntry("authority", authorityFieldValue); collectingValue.addPathValue(branchValue); } return collectingValue; } private int getIdForUnit(Unit unit, SootMethod method) { int id = 0; for (Unit currentUnit : method.getActiveBody().getUnits()) { if (currentUnit == unit) { return id; } ++id; } return -1; } @SuppressWarnings("unchecked") private void analyzeResult(Result result) { Set<String> nonLinkingFieldNames = new HashSet<>(); nonLinkingFieldNames.add("extras"); nonLinkingFieldNames.add("flags"); nonLinkingFieldNames.add("fragment"); nonLinkingFieldNames.add("query"); for (Map.Entry<Unit, Map<Integer, Object>> entry0 : result.getResults().entrySet()) { Collection<Object> argumentValues = entry0.getValue().values(); boolean top = false; boolean bottom = false; // This is true only if the linking field are precisely known. boolean preciseLinking = true; // This is true only if all fields are precisely known. boolean preciseNonLinking = true; boolean nonexistent = false; boolean intentWithUri = false; boolean entryPointIntent = false; int resultIndex = getResultIndex((Stmt) entry0.getKey()); for (Object value2 : argumentValues) { if (value2 == null) { nonexistent = true; } else if (value2 instanceof TopPropagationValue) { top = true; } else if (value2 instanceof BottomPropagationValue) { bottom = true; } else if (value2 instanceof PropagationValue) { PropagationValue collectingValue = (PropagationValue) value2; for (PathValue branchValue : collectingValue.getPathValues()) { intentWithUri = intentWithUri || isIntentWithUri(branchValue.getFieldMap()); for (Map.Entry<String, FieldValue> entry : branchValue.getFieldMap().entrySet()) { String fieldName = entry.getKey(); FieldValue fieldValue = entry.getValue(); if (fieldValue instanceof TopFieldValue) { if (nonLinkingFieldNames.contains(fieldName)) { preciseNonLinking = false; } else { preciseNonLinking = false; preciseLinking = false; } } else { Object value = fieldValue.getValue(); if (value == null) { continue; } if (value instanceof Set) { Set<Object> values = (Set<Object>) value; if (values.contains(Constants.ANY_STRING) || values.contains(Constants.ANY_CLASS) || values.contains(Constants.ANY_INT) || values.contains(ENTRY_POINT_INTENT) || values.contains("top")) { if (values.contains(ENTRY_POINT_INTENT)) { entryPointIntent = true; } preciseNonLinking = false; if (!nonLinkingFieldNames.contains(fieldName)) { preciseLinking = false; } } } else { if (value.equals(Constants.ANY_STRING) || value.equals(Constants.ANY_CLASS) || value.equals(Constants.ANY_INT) || value.equals(ENTRY_POINT_INTENT) || value.equals("top")) { if (value.equals(ENTRY_POINT_INTENT)) { entryPointIntent = true; } preciseNonLinking = false; if (!nonLinkingFieldNames.contains(fieldName)) { preciseLinking = false; } } } } } } } } if (intentWithUri) { ++this.intentWithData; } if (nonexistent) { if (Scene .v() .getActiveHierarchy() .isClassSubclassOfIncluding( AnalysisParameters.v().getIcfg().getMethodOf(entry0.getKey()).getDeclaringClass(), Scene.v().getSootClass("android.content.ContentProvider"))) { ++this.providerArgument; } else { ++this.nonexistent[resultIndex]; } } else if (top) { ++this.top[resultIndex]; } else if (bottom) { ++this.bottom[resultIndex]; } else if (preciseNonLinking) { if (intentWithUri) { ++this.preciseNonLinking[3]; } else { ++this.preciseNonLinking[resultIndex]; } } else if (preciseLinking) { if (intentWithUri) { ++this.preciseLinking[3]; } else { ++this.preciseLinking[resultIndex]; } } else { if (entryPointIntent) { ++this.imprecise[4]; } else if (intentWithUri) { ++this.imprecise[3]; } else { ++this.imprecise[resultIndex]; } } } } private boolean isIntentWithUri(Map<String, FieldValue> fieldMap) { Set<String> fields = fieldMap.keySet(); if (fields.contains("action") || fields.contains("categories")) { if ((fields.contains("uri") && fieldMap.get("uri") != null && fieldMap.get("uri").getValue() != null) || (fields.contains("path") && fieldMap.get("path") != null && fieldMap.get("path") .getValue() != null) || (fields.contains("scheme") && fieldMap.get("scheme") != null && fieldMap.get("scheme") .getValue() != null) || (fields.contains("ssp") && fieldMap.get("ssp") != null && fieldMap.get("ssp") .getValue() != null)) { return true; } } return false; } private int getResultIndex(Stmt stmt) { InvokeExpr invokeExpr = stmt.getInvokeExpr(); List<Type> types = invokeExpr.getMethod().getParameterTypes(); for (Type type : types) { if (type.toString().equals("android.content.IntentFilter")) { return 1; } else if (type.toString().equals("android.net.Uri")) { return 2; } } return 0; } private boolean containsPartialDefinition(Set<Object> values) { for (Object value : values) { if (value instanceof String && ((String) value).contains("(.*)")) { return true; } } return false; } }
30,081
40.896936
113
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/ResultProcessor.java
package edu.psu.cse.siis.ic3; import java.io.IOException; import java.io.Writer; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Scene; import soot.SootMethod; import soot.Type; import soot.Unit; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.AnalysisParameters; import edu.psu.cse.siis.coal.Constants; import edu.psu.cse.siis.coal.Model; import edu.psu.cse.siis.coal.PropagationTimers; import edu.psu.cse.siis.coal.Result; import edu.psu.cse.siis.coal.Results; import edu.psu.cse.siis.coal.arguments.Argument; import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.ScalarFieldValue; import edu.psu.cse.siis.coal.field.values.TopFieldValue; import edu.psu.cse.siis.coal.values.BasePropagationValue; import edu.psu.cse.siis.coal.values.BottomPropagationValue; import edu.psu.cse.siis.coal.values.PathValue; import edu.psu.cse.siis.coal.values.PropagationValue; import edu.psu.cse.siis.coal.values.TopPropagationValue; import edu.psu.cse.siis.ic3.db.DbConnection; import edu.psu.cse.siis.ic3.db.SQLConnection; import edu.psu.cse.siis.ic3.manifest.ManifestComponent; import edu.psu.cse.siis.ic3.manifest.ManifestData; import edu.psu.cse.siis.ic3.manifest.ManifestIntentFilter; public class ResultProcessor { private final Logger logger = LoggerFactory.getLogger(getClass()); private static final String ENTRY_POINT_INTENT = "<INTENT>"; private final int[] preciseNonLinking = { 0, 0, 0, 0 }; private final int[] preciseLinking = { 0, 0, 0, 0 }; private final int[] imprecise = { 0, 0, 0, 0, 0 }; private final int[] top = { 0, 0, 0 }; private final int[] bottom = { 0, 0, 0 }; private final int[] nonexistent = { 0, 0, 0 }; private final int[] preciseFieldValueCount = { 0, 0, 0 }; private final int[] partiallyPreciseFieldValueCount = { 0, 0, 0 }; private final int[] impreciseFieldValueCount = { 0, 0, 0 }; private int intentWithData = 0; private int providerArgument = 0; public void processResult(boolean writeToDb, String appName, Map<String, Integer> componentToIdMap, int analysisClassesCount, Writer writer) throws IOException, SQLException { for (Result result : Results.getResults()) { ((Ic3Result) result).dump(); analyzeResult(result); if (writeToDb) { writeResultToDb(result, componentToIdMap); } } if (writeToDb) { SQLConnection.closeConnection(); } Timers.v().totalTimer.end(); String statistics = appName + " " + analysisClassesCount + " " + PropagationTimers.v().reachableMethods + " " + PropagationTimers.v().reachableStatements + " " + preciseNonLinking[0] + " " + preciseNonLinking[3] + " " + preciseNonLinking[1] + " " + preciseNonLinking[2] + " " + preciseLinking[0] + " " + preciseLinking[3] + " " + preciseLinking[1] + " " + preciseLinking[2] + " " + imprecise[0] + " " + imprecise[3] + " " + imprecise[1] + " " + imprecise[2] + " " + bottom[0] + " " + bottom[1] + " " + bottom[2] + " " + top[0] + " " + top[1] + " " + top[2] + " " + nonexistent[0] + " " + nonexistent[1] + " " + nonexistent[2] + " " + providerArgument + " " + imprecise[4] + " " + PropagationTimers.v().pathValues + " " + PropagationTimers.v().separatePathValues + " " + PropagationTimers.v().modelParsing.getTime() + " " + Timers.v().mainGeneration.getTime() + " " + Timers.v().entryPointMapping.getTime() + " " + Timers.v().classLoading.getTime() + " " + PropagationTimers.v().problemGeneration.getTime() + " " + PropagationTimers.v().ideSolution.getTime() + " " + PropagationTimers.v().valueComposition.getTime() + " " + PropagationTimers.v().resultGeneration.getTime() + " " + (PropagationTimers.v().soot.getTime() - PropagationTimers.v().totalTimer.getTime()) + " " + (Timers.v().misc.getTime() + PropagationTimers.v().misc.getTime()) + " " /* + PropagationTimers.v().argumentValueTime + " " */+ Timers.v().totalTimer.getTime() + "\n"; if (logger.isInfoEnabled()) { logger.info(statistics); } if (writer != null) { writer.write(statistics); writer.close(); } } @SuppressWarnings("unchecked") private void writeResultToDb(Result result, Map<String, Integer> componentToIdMap) throws SQLException { for (Map.Entry<Unit, Map<Integer, Object>> entry : result.getResults().entrySet()) { Unit unit = entry.getKey(); Argument[] arguments = Model.v().getArgumentsForQuery((Stmt) unit); Map<SootMethod, Set<String>> entryPointMap = ((Ic3Result) result).getEntryPointMap(); if (arguments != null) { SootMethod method = AnalysisParameters.v().getIcfg().getMethodOf(unit); int unitId = getIdForUnit(unit, method); Map<String, Object> valueMap = new HashMap<>(arguments.length); Map<Integer, Object> argnumToValueMap = entry.getValue(); for (Argument argument : arguments) { valueMap.put(argument.getProperty("valueType"), argnumToValueMap.get(argument.getArgnum()[0])); } String className = method.getDeclaringClass().getName(); String methodSignature = method.getSignature(); if (valueMap.containsKey("activity")) { DbConnection.insertIntentAtExitPoint(className, methodSignature, unitId, (BasePropagationValue) valueMap.get("activity"), edu.psu.cse.siis.ic3.db.Constants.ComponentShortType.ACTIVITY, null, null, entryPointMap.get(method), componentToIdMap); } else if (valueMap.containsKey("service")) { DbConnection.insertIntentAtExitPoint(className, methodSignature, unitId, (BasePropagationValue) valueMap.get("service"), edu.psu.cse.siis.ic3.db.Constants.ComponentShortType.SERVICE, null, null, entryPointMap.get(method), componentToIdMap); } else if (valueMap.containsKey("receiver")) { DbConnection.insertIntentAtExitPoint(className, methodSignature, unitId, (BasePropagationValue) valueMap.get("receiver"), edu.psu.cse.siis.ic3.db.Constants.ComponentShortType.RECEIVER, (Set<String>) valueMap.get("permission"), null, entryPointMap.get(method), componentToIdMap); } else if (valueMap.containsKey("intentFilter")) { insertDynamicReceiver((Set<String>) valueMap.get("permission"), (Set<String>) valueMap.get("receiverType"), (BasePropagationValue) valueMap.get("intentFilter"), method, unit); } else if (valueMap.containsKey("provider")) { DbConnection.insertIntentAtExitPoint(className, methodSignature, unitId, (BasePropagationValue) valueMap.get("provider"), edu.psu.cse.siis.ic3.db.Constants.ComponentShortType.PROVIDER, null, null, entryPointMap.get(method), componentToIdMap); } else if (valueMap.containsKey("authority")) { DbConnection.insertIntentAtExitPoint(className, methodSignature, unitId, getUriValueForAuthorities((Set<String>) valueMap.get("authority")), edu.psu.cse.siis.ic3.db.Constants.ComponentShortType.PROVIDER, null, null, entryPointMap.get(method), componentToIdMap); } else if (valueMap.containsKey("pendingIntent")) { BasePropagationValue basePropagationValue = (BasePropagationValue) valueMap.get("pendingIntent"); String targetType = basePropagationValue instanceof PropagationValue ? (String) ((PropagationValue) basePropagationValue) .getValuesForField("targetType").iterator().next().getValue() : null; Set<String> permissions = (Set<String>) valueMap.get("permission"); if (targetType != null) { DbConnection.insertIntentAtExitPoint(className, methodSignature, unitId, basePropagationValue, targetType, permissions, null, entryPointMap.get(method), componentToIdMap); } else { for (String target : Arrays.asList("a", "r", "s")) { DbConnection.insertIntentAtExitPoint(className, methodSignature, unitId, basePropagationValue, target, permissions, null, entryPointMap.get(method), componentToIdMap); } } } else if (valueMap.containsKey("componentExtra")) { DbConnection.insertComponentExtras(entryPointMap.get(method), componentToIdMap, (Set<String>) valueMap.get("componentExtra")); } } } } private void insertDynamicReceiver(Set<String> permissions, Set<String> receiverTypes, BasePropagationValue intentFilters, SootMethod method, Unit unit) throws SQLException { if (permissions == null) { permissions = Collections.singleton(null); } for (String receiverType : receiverTypes) { for (String permission : permissions) { insertDynamicReceiverHelper(permission, receiverType, intentFilters, method, unit); } } } private void insertDynamicReceiverHelper(String permission, String receiverType, BasePropagationValue intentFilters, SootMethod method, Unit unit) throws SQLException { Integer missingIntentFilters; Set<ManifestIntentFilter> manifestIntentFilters; if (intentFilters == null || intentFilters instanceof TopPropagationValue || intentFilters instanceof BottomPropagationValue) { missingIntentFilters = 0; manifestIntentFilters = null; } else if (intentFilters instanceof PropagationValue) { missingIntentFilters = null; PropagationValue propagationValue = (PropagationValue) intentFilters; manifestIntentFilters = new HashSet<>(); for (PathValue branchValue : propagationValue.getPathValues()) { Integer filterPriority = null; FieldValue priorityFieldValue = branchValue.getFieldValue("priority"); if (priorityFieldValue != null) { filterPriority = (Integer) priorityFieldValue.getValue(); } manifestIntentFilters.add(new ManifestIntentFilter(branchValue .getSetStringFieldValue("actions"), branchValue.getSetStringFieldValue("categories"), false, makeManifestData(branchValue), filterPriority)); } } else { throw new RuntimeException("Unknown intent filter type: " + intentFilters.getClass()); } ManifestComponent manifestComponent = new ManifestComponent(edu.psu.cse.siis.ic3.db.Constants.ComponentShortType.RECEIVER, receiverType, true, true, permission, null, missingIntentFilters, method, unit); manifestComponent.setIntentFilters(manifestIntentFilters); SQLConnection.insertIntentFilters(Collections.singletonList(manifestComponent)); } private List<ManifestData> makeManifestData(PathValue branchValue) { Set<String> mimeTypes = branchValue.getSetStringFieldValue("dataType"); Set<DataAuthority> authorities = branchValue.getSetFieldValue("authorities", DataAuthority.class); Set<String> paths = branchValue.getSetStringFieldValue("paths"); Set<String> schemes = branchValue.getSetStringFieldValue("schemes"); if (mimeTypes == null && authorities == null && paths == null && schemes == null) { return null; } if (mimeTypes == null) { mimeTypes = Collections.singleton(null); } if (authorities == null) { authorities = Collections.singleton(new DataAuthority(null, null)); } if (paths == null) { paths = Collections.singleton(null); } if (schemes == null) { schemes = Collections.singleton(null); } List<ManifestData> result = new ArrayList<>(); for (String mimeType : mimeTypes) { for (DataAuthority dataAuthority : authorities) { for (String dataPath : paths) { for (String scheme : schemes) { result.add(new ManifestData(scheme, dataAuthority.getHost(), dataAuthority.getPort(), dataPath, mimeType)); } } } } return result; } private BasePropagationValue getUriValueForAuthorities(Set<String> authorities) { if (authorities == null) { return null; } PropagationValue collectingValue = new PropagationValue(); for (String authority : authorities) { PathValue branchValue = new PathValue(); ScalarFieldValue schemeFieldValue = new ScalarFieldValue("content"); branchValue.addFieldEntry("scheme", schemeFieldValue); ScalarFieldValue authorityFieldValue = new ScalarFieldValue(authority); branchValue.addFieldEntry("authority", authorityFieldValue); collectingValue.addPathValue(branchValue); } return collectingValue; } private int getIdForUnit(Unit unit, SootMethod method) { int id = 0; for (Unit currentUnit : method.getActiveBody().getUnits()) { if (currentUnit == unit) { return id; } ++id; } return -1; } @SuppressWarnings("unchecked") private void analyzeResult(Result result) { Set<String> nonLinkingFieldNames = new HashSet<>(); nonLinkingFieldNames.add("extras"); nonLinkingFieldNames.add("flags"); nonLinkingFieldNames.add("fragment"); nonLinkingFieldNames.add("query"); for (Map.Entry<Unit, Map<Integer, Object>> entry0 : result.getResults().entrySet()) { Collection<Object> argumentValues = entry0.getValue().values(); boolean top = false; boolean bottom = false; // This is true only if the linking field are precisely known. boolean preciseLinking = true; // This is true only if all fields are precisely known. boolean preciseNonLinking = true; boolean nonexistent = false; boolean intentWithUri = false; boolean entryPointIntent = false; int resultIndex = getResultIndex((Stmt) entry0.getKey()); for (Object value2 : argumentValues) { if (value2 == null) { nonexistent = true; } else if (value2 instanceof TopPropagationValue) { top = true; } else if (value2 instanceof BottomPropagationValue) { bottom = true; } else if (value2 instanceof PropagationValue) { // System.out.println(value2); Set<PathValue> pathValues = ((PropagationValue) value2).getPathValues(); PropagationTimers.v().pathValues += pathValues.size(); // This keeps track of all the fields that are defined across all paths. Set<String> definedFields = new HashSet<>(); for (PathValue pathValue : pathValues) { definedFields.addAll(pathValue.getFieldMap().keySet()); } Map<String, Set<FieldValue>> separateFieldValues = new HashMap<>(); for (PathValue branchValue : pathValues) { intentWithUri = intentWithUri || isIntentWithUri(branchValue.getFieldMap()); Set<String> definedFieldsInPath = new HashSet<>(); for (Map.Entry<String, FieldValue> entry : branchValue.getFieldMap().entrySet()) { String fieldName = entry.getKey(); FieldValue fieldValue = entry.getValue(); addValueToSetMap(fieldName, fieldValue, separateFieldValues); definedFieldsInPath.add(fieldName); if (fieldValue instanceof TopFieldValue) { if (nonLinkingFieldNames.contains(fieldName)) { preciseNonLinking = false; } else { preciseNonLinking = false; preciseLinking = false; } } else { Object value = fieldValue.getValue(); if (value == null) { continue; } if (value instanceof Set) { Set<Object> values = (Set<Object>) value; if (values.contains(Constants.ANY_STRING) || values.contains(Constants.ANY_CLASS) || values.contains(Constants.ANY_INT) || values.contains(ENTRY_POINT_INTENT) || values.contains("top")) { if (values.contains(ENTRY_POINT_INTENT)) { entryPointIntent = true; } preciseNonLinking = false; if (!nonLinkingFieldNames.contains(fieldName)) { preciseLinking = false; } } } else { if (value.equals(Constants.ANY_STRING) || value.equals(Constants.ANY_CLASS) || value.equals(Constants.ANY_INT) || value.equals(ENTRY_POINT_INTENT) || value.equals("top")) { if (value.equals(ENTRY_POINT_INTENT)) { entryPointIntent = true; } preciseNonLinking = false; if (!nonLinkingFieldNames.contains(fieldName)) { preciseLinking = false; } } } } } // If some field is undefined in some path, then we need to keep track of a null value // for that field. Set<String> undefinedFieldForPath = new HashSet<>(definedFields); undefinedFieldForPath.removeAll(definedFieldsInPath); for (String fieldName : undefinedFieldForPath) { addValueToSetMap(fieldName, null, separateFieldValues); } } int separateCount = 1; for (Set<FieldValue> values : separateFieldValues.values()) { separateCount *= values.size(); } // System.out.println(separateCount); PropagationTimers.v().separatePathValues += separateCount; } } if (intentWithUri) { ++this.intentWithData; } if (nonexistent) { if (Scene .v() .getActiveHierarchy() .isClassSubclassOfIncluding( AnalysisParameters.v().getIcfg().getMethodOf(entry0.getKey()).getDeclaringClass(), Scene.v().getSootClass("android.content.ContentProvider"))) { ++this.providerArgument; } else { ++this.nonexistent[resultIndex]; } } else if (top) { ++this.top[resultIndex]; } else if (bottom) { ++this.bottom[resultIndex]; } else if (preciseNonLinking) { if (intentWithUri) { ++this.preciseNonLinking[3]; } else { ++this.preciseNonLinking[resultIndex]; } } else if (preciseLinking) { if (intentWithUri) { ++this.preciseLinking[3]; } else { ++this.preciseLinking[resultIndex]; } } else { if (entryPointIntent) { ++this.imprecise[4]; } else if (intentWithUri) { ++this.imprecise[3]; } else { ++this.imprecise[resultIndex]; } } } } private void addValueToSetMap(String key, FieldValue value, Map<String, Set<FieldValue>> map) { Set<FieldValue> separateValuesForField = map.get(key); if (separateValuesForField == null) { separateValuesForField = new HashSet<>(); map.put(key, separateValuesForField); } separateValuesForField.add(value); } private boolean isIntentWithUri(Map<String, FieldValue> fieldMap) { Set<String> fields = fieldMap.keySet(); if (fields.contains("action") || fields.contains("categories")) { if ((fields.contains("uri") && fieldMap.get("uri") != null && fieldMap.get("uri").getValue() != null) || (fields.contains("path") && fieldMap.get("path") != null && fieldMap.get("path") .getValue() != null) || (fields.contains("scheme") && fieldMap.get("scheme") != null && fieldMap.get("scheme") .getValue() != null) || (fields.contains("ssp") && fieldMap.get("ssp") != null && fieldMap.get("ssp") .getValue() != null)) { return true; } } return false; } private int getResultIndex(Stmt stmt) { InvokeExpr invokeExpr = stmt.getInvokeExpr(); List<Type> types = invokeExpr.getMethod().getParameterTypes(); for (Type type : types) { if (type.toString().equals("android.content.IntentFilter")) { return 1; } else if (type.toString().equals("android.net.Uri")) { return 2; } } return 0; } private boolean containsPartialDefinition(Set<Object> values) { for (Object value : values) { if (value instanceof String && ((String) value).contains("(.*)")) { return true; } } return false; } }
21,187
39.590038
115
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/SetupApplication.java
/******************************************************************************* * Copyright (c) 2012 Secure Software Engineering Group at EC SPRIDE. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: Christian Fritz, Steven Arzt, Siegfried Rasthofer, Eric * Bodden, and others. ******************************************************************************/ package edu.psu.cse.siis.ic3; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Main; import soot.PackManager; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.jimple.infoflow.android.AnalyzeJimpleClass; import soot.jimple.infoflow.android.data.AndroidMethod; import soot.jimple.infoflow.android.resources.ARSCFileParser; import soot.jimple.infoflow.android.resources.ARSCFileParser.AbstractResource; import soot.jimple.infoflow.android.resources.ARSCFileParser.StringResource; import soot.jimple.infoflow.android.resources.LayoutControl; import soot.jimple.infoflow.android.resources.LayoutFileParser; import soot.jimple.infoflow.data.SootMethodAndClass; import soot.jimple.infoflow.entryPointCreators.AndroidEntryPointCreator; import soot.options.Options; public class SetupApplication { private final Logger logger = LoggerFactory.getLogger(getClass()); private final Map<String, Set<SootMethodAndClass>> callbackMethods = new HashMap<String, Set<SootMethodAndClass>>(10000); private Set<String> entrypoints = null; private String appPackageName = ""; private final String apkFileLocation; private final String classDirectory; private final String androidClassPath; private AndroidEntryPointCreator entryPointCreator; public SetupApplication(String apkFileLocation, String classDirectory, String androidClassPath) { this.apkFileLocation = apkFileLocation; this.classDirectory = classDirectory; this.androidClassPath = androidClassPath; } /** * Gets the entry point creator used for generating the dummy main method emulating the Android * lifecycle and the callbacks. Make sure to call calculateSourcesSinksEntryPoints() first, or you * will get a null result. * * @return The entry point creator */ public AndroidEntryPointCreator getEntryPointCreator() { return entryPointCreator; } /** * Prints list of classes containing entry points to stdout */ public void printEntrypoints() { if (logger.isDebugEnabled()) { if (this.entrypoints == null) { logger.debug("Entry points not initialized"); } else { logger.debug("Classes containing entry points:"); for (String className : entrypoints) { logger.debug("\t" + className); } logger.debug("End of Entrypoints"); } } } /** * Calculates the sets of sources, modifiers, entry points, and callbacks methods for the given * APK file. * * @param sourceMethods The set of methods to be considered as sources * @param modifierMethods The set of methods to be considered as modifiers * @throws IOException Thrown if the given source/modifier file could not be read. */ public Map<String, Set<String>> calculateSourcesSinksEntrypoints( Set<AndroidMethod> sourceMethods, Set<AndroidMethod> modifierMethods, String packageName, Set<String> entryPointClasses) throws IOException { // To look for callbacks, we need to start somewhere. We use the Android // lifecycle methods for this purpose. this.appPackageName = packageName; this.entrypoints = entryPointClasses; boolean parseLayoutFile = !apkFileLocation.endsWith(".xml"); // Parse the resource file ARSCFileParser resParser = null; if (parseLayoutFile) { resParser = new ARSCFileParser(); resParser.parse(apkFileLocation); } AnalyzeJimpleClass jimpleClass = null; LayoutFileParser lfp = parseLayoutFile ? new LayoutFileParser(this.appPackageName, resParser) : null; boolean hasChanged = true; while (hasChanged) { hasChanged = false; soot.G.reset(); initializeSoot(); createMainMethod(); if (jimpleClass == null) { // Collect the callback interfaces implemented in the app's source code jimpleClass = new AnalyzeJimpleClass(entrypoints); jimpleClass.collectCallbackMethods(); // Find the user-defined sources in the layout XML files. This // only needs to be done once, but is a Soot phase. if (parseLayoutFile) { lfp.parseLayoutFile(apkFileLocation, entrypoints); } } else { jimpleClass.collectCallbackMethodsIncremental(); } // Run the soot-based operations PackManager.v().getPack("wjpp").apply(); PackManager.v().getPack("cg").apply(); PackManager.v().getPack("wjtp").apply(); // Collect the results of the soot-based phases for (Entry<String, Set<SootMethodAndClass>> entry : jimpleClass.getCallbackMethods() .entrySet()) { if (this.callbackMethods.containsKey(entry.getKey())) { if (this.callbackMethods.get(entry.getKey()).addAll(entry.getValue())) { hasChanged = true; } } else { this.callbackMethods.put(entry.getKey(), new HashSet<SootMethodAndClass>(entry.getValue())); hasChanged = true; } } } // Collect the XML-based callback methods for (Entry<String, Set<Integer>> lcentry : jimpleClass.getLayoutClasses().entrySet()) { final SootClass callbackClass = Scene.v().getSootClass(lcentry.getKey()); for (Integer classId : lcentry.getValue()) { AbstractResource resource = resParser.findResource(classId); if (resource instanceof StringResource) { final String layoutFileName = ((StringResource) resource).getValue(); // Add the callback methods for the given class Set<String> callbackMethods = lfp.getCallbackMethods().get(layoutFileName); if (callbackMethods != null) { for (String methodName : callbackMethods) { final String subSig = "void " + methodName + "(android.view.View)"; // The callback may be declared directly in the // class // or in one of the superclasses SootClass currentClass = callbackClass; while (true) { SootMethod callbackMethod = currentClass.getMethodUnsafe(subSig); if (callbackMethod != null) { addCallbackMethod(callbackClass.getName(), new AndroidMethod(callbackMethod)); break; } if (!currentClass.hasSuperclass()) { System.err.println("Callback method " + methodName + " not found in class " + callbackClass.getName()); break; } currentClass = currentClass.getSuperclass(); } } } // For user-defined views, we need to emulate their // callbacks Set<LayoutControl> controls = lfp.getUserControls().get(layoutFileName); if (controls != null) { for (LayoutControl lc : controls) { registerCallbackMethodsForView(callbackClass, lc); } } } else { System.err.println("Unexpected resource type for layout class"); } } } logger.info("Entry point calculation done."); // Clean up everything we no longer need soot.G.reset(); Map<String, Set<String>> result = new HashMap<>(this.callbackMethods.size()); for (Map.Entry<String, Set<SootMethodAndClass>> entry : this.callbackMethods.entrySet()) { Set<SootMethodAndClass> callbackSet = entry.getValue(); Set<String> callbackStrings = new HashSet<>(callbackSet.size()); for (SootMethodAndClass androidMethod : callbackSet) { callbackStrings.add(androidMethod.getSignature()); } result.put(entry.getKey(), callbackStrings); } entryPointCreator = createEntryPointCreator(); return result; } /** * Registers the callback methods in the given layout control so that they are included in the * dummy main method * * @param callbackClass The class with which to associate the layout callbacks * @param lc The layout control whose callbacks are to be associated with the given class */ private void registerCallbackMethodsForView(SootClass callbackClass, LayoutControl lc) { // Ignore system classes if (callbackClass.getName().startsWith("android.")) { return; } if (lc.getViewClass().getName().startsWith("android.")) { return; } // Check whether the current class is actually a view { SootClass sc = lc.getViewClass(); boolean isView = false; while (sc.hasSuperclass()) { if (sc.getName().equals("android.view.View")) { isView = true; break; } sc = sc.getSuperclass(); } if (!isView) { return; } } // There are also some classes that implement interesting callback // methods. // We model this as follows: Whenever the user overwrites a method in an // Android OS class, we treat it as a potential callback. SootClass sc = lc.getViewClass(); Set<String> systemMethods = new HashSet<String>(10000); for (SootClass parentClass : Scene.v().getActiveHierarchy().getSuperclassesOf(sc)) { if (parentClass.getName().startsWith("android.")) { for (SootMethod sm : parentClass.getMethods()) { if (!sm.isConstructor()) { systemMethods.add(sm.getSubSignature()); } } } } // Scan for methods that overwrite parent class methods for (SootMethod sm : sc.getMethods()) { if (!sm.isConstructor()) { if (systemMethods.contains(sm.getSubSignature())) { // This is a real callback method addCallbackMethod(callbackClass.getName(), new AndroidMethod(sm)); } } } } /** * Adds a method to the set of callback method * * @param layoutClass The layout class for which to register the callback * @param callbackMethod The callback method to register */ private void addCallbackMethod(String layoutClass, AndroidMethod callbackMethod) { Set<SootMethodAndClass> methods = this.callbackMethods.get(layoutClass); if (methods == null) { methods = new HashSet<SootMethodAndClass>(); this.callbackMethods.put(layoutClass, methods); } methods.add(new AndroidMethod(callbackMethod)); } /** * Creates the main method based on the current callback information, injects it into the Soot * scene. */ private void createMainMethod() { // Always update the entry point creator to reflect the newest set // of callback methods SootMethod entryPoint = createEntryPointCreator().createDummyMain(); Scene.v().setEntryPoints(Collections.singletonList(entryPoint)); if (Scene.v().containsClass(entryPoint.getDeclaringClass().getName())) { Scene.v().removeClass(entryPoint.getDeclaringClass()); } Scene.v().addClass(entryPoint.getDeclaringClass()); } /** * Initializes soot for running the soot-based phases of the application metadata analysis * * @return The entry point used for running soot */ public void initializeSoot() { Options.v().set_no_bodies_for_excluded(true); Options.v().set_allow_phantom_refs(true); Options.v().set_output_format(Options.output_format_none); Options.v().set_whole_program(true); Options.v().setPhaseOption("cg.spark", "on"); // Options.v().setPhaseOption("cg.spark", "geom-pta:true"); // Options.v().setPhaseOption("cg.spark", "geom-encoding:PtIns"); Options.v().set_ignore_resolution_errors(true); // Options.v().setPhaseOption("jb", "use-original-names:true"); Options.v() .set_soot_classpath(this.classDirectory + File.pathSeparator + this.androidClassPath); if (logger.isDebugEnabled()) { logger.debug("Android class path: " + this.androidClassPath); } // Options.v().set_android_jars(androidJar); // Options.v().set_src_prec(Options.src_prec_apk); Options.v().set_process_dir(new ArrayList<>(this.entrypoints)); // Options.v().set_app(true); Main.v().autoSetOptions(); Scene.v().loadNecessaryClasses(); // for (String className : this.entrypoints) { // SootClass c = Scene.v().forceResolve(className, SootClass.BODIES); // c.setApplicationClass(); // } // // SootMethod entryPoint = getEntryPointCreator().createDummyMain(); // Scene.v().setEntryPoints(Collections.singletonList(entryPoint)); // return entryPoint; } public AndroidEntryPointCreator createEntryPointCreator() { AndroidEntryPointCreator entryPointCreator = new AndroidEntryPointCreator(new ArrayList<String>(this.entrypoints)); Map<String, List<String>> callbackMethodSigs = new HashMap<String, List<String>>(); for (String className : this.callbackMethods.keySet()) { List<String> methodSigs = new ArrayList<String>(); callbackMethodSigs.put(className, methodSigs); for (SootMethodAndClass am : this.callbackMethods.get(className)) { methodSigs.add(am.getSignature()); } } entryPointCreator.setCallbackFunctions(callbackMethodSigs); return entryPointCreator; } }
13,964
36.04244
100
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/Timers.java
/* Soot - a J*va Optimization Framework * Copyright (C) 2003 Ondrej Lhotak * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* * Modified by the Sable Research Group and others 1997-1999. * See the 'credits' file distributed with Soot for the complete list of * contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot) */ package edu.psu.cse.siis.ic3; import java.text.DecimalFormat; import soot.G; import soot.Timer; import soot.options.Options; public class Timers { private static Timers instance = new Timers(); private Timers() { } public static Timers v() { synchronized (instance) { return instance; } } public static void clear() { instance = new Timers(); } public Timer modelParsing = new Timer("modelParsing"); public Timer mainGeneration = new Timer("mainGeneration"); public Timer misc = new Timer("Misc"); public Timer classLoading = new Timer("Class loading"); public Timer totalTimer = new Timer("totalTimer"); public Timer entryPointMapping = new Timer("entryPointMapping"); public int entryPoints = 0; public int reachableMethods = 0; public int classes = 0; public void printProfilingInformation() { long totalTime = totalTimer.getTime(); G.v().out.println("Time measurements"); G.v().out.println(); G.v().out.println(" Main generation: " + toTimeString(mainGeneration, totalTime)); G.v().out.println(); G.v().out.println(" Entry points: " + entryPoints); G.v().out.println(" Class count: " + classes); // Print out time stats. G.v().out.println("totalTime:" + toTimeString(totalTimer, totalTime)); if (Options.v().subtract_gc()) { G.v().out.println("Garbage collection was subtracted from these numbers."); G.v().out.println(" forcedGC:" + toTimeString(G.v().Timer_forcedGarbageCollectionTimer, totalTime)); } } private String toTimeString(Timer timer, long totalTime) { DecimalFormat format = new DecimalFormat("00.0"); DecimalFormat percFormat = new DecimalFormat("00.0"); long time = timer.getTime(); String timeString = format.format(time / 1000.0); return timeString + "s (" + percFormat.format(time * 100.0 / totalTime) + "%)"; } }
2,966
28.088235
89
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/AliasesTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class AliasesTable extends TwoIntTable { AliasesTable() { super("Aliases", "component_id", "target_id"); } public int insert(int componentId, int targetId) throws SQLException { return super.insert(componentId, targetId); } public int find(int componentId, int targetId) throws SQLException { return super.find(componentId, targetId); } }
1,173
31.611111
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/ApplicationTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; import java.sql.Types; public class ApplicationTable extends Table { private static final String INSERT = "INSERT INTO Applications (app, version) VALUES (?, ?)"; private static final String FIND = "SELECT id FROM Applications WHERE app = ? AND version %s ?"; public int insert(String app, int version) throws SQLException { int id = find(app, version); findStatement.close(); if (id != NOT_FOUND) { return id; } return forceInsert(app, version); } public int forceInsert(String app, int version) throws SQLException { if (insertStatement == null || insertStatement.isClosed()) { insertStatement = getConnection().prepareStatement(INSERT); } insertStatement.setString(1, app); if (version == NOT_FOUND) { insertStatement.setNull(2, Types.INTEGER); } else { insertStatement.setInt(2, version); } if (insertStatement.executeUpdate() == 0) { return NOT_FOUND; } return findAutoIncrement(); } public int find(String app, int version) throws SQLException { String formatArg = (version == NOT_FOUND) ? "IS" : "="; findStatement = getConnection().prepareStatement(String.format(FIND, formatArg)); findStatement.setString(1, app); if (version == NOT_FOUND) { findStatement.setNull(2, Types.INTEGER); } else { findStatement.setInt(2, version); } return processIntFindQuery(findStatement); } }
2,230
33.323077
98
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/ClassTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class ClassTable extends OneIntOneStringTable { ClassTable() { super("Classes", "app_id", "class"); } @Override public int insert(int appId, String clazz) throws SQLException { return super.insert(appId, clazz); } @Override public int find(int appId, String clazz) throws SQLException { return super.find(appId, clazz); } }
1,162
29.605263
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/ComponentExtraTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class ComponentExtraTable extends OneIntOneStringTable { ComponentExtraTable() { super("ComponentExtras", "component_id", "extra"); } @Override public int insert(int componentId, String extra) throws SQLException { return super.insert(componentId, extra); } @Override public int find(int componentId, String extra) throws SQLException { return super.find(componentId, extra); } }
1,218
31.078947
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/ComponentTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; import java.sql.Types; public class ComponentTable extends Table { private static final String INSERT = "INSERT INTO Components " + "(class_id, kind, exported, permission, missing) VALUES (?, ?, ?, ?, ?)"; private static final String FIND = "SELECT id FROM Components WHERE class_id = ? AND kind = ? AND exported = ? " + "AND permission %s ? AND missing %s ?"; // private static final String FIND_COMPONENT_FOR_EXPLICIT_INTENT = // "SELECT Components.id, kind FROM Applications " + // "JOIN Classes ON Applications.id = Classes.app_id " + // "JOIN Components ON Classes.id = Components.class_id " + // "LEFT JOIN UsesPermissions ON Applications.id = UsesPermissions.app_id " + // "WHERE (Applications.id = ? OR exported = ?) " + // "AND class = ? " + // "AND (permission IS ?"; // private PreparedStatement findComponentForIntentStatement = null; public int insert(int classId, String type, boolean exported, int permission, Integer missingIntentFilters) throws SQLException { int id = find(classId, type, exported, permission, missingIntentFilters); if (id != NOT_FOUND) { return id; } if (insertStatement == null || insertStatement.isClosed()) { insertStatement = getConnection().prepareStatement(INSERT); } insertStatement.setInt(1, classId); insertStatement.setString(2, type); insertStatement.setBoolean(3, exported); if (permission == NOT_FOUND) { insertStatement.setNull(4, Types.INTEGER); } else { insertStatement.setInt(4, permission); } if (missingIntentFilters == null) { insertStatement.setNull(5, Types.INTEGER); } else { insertStatement.setInt(5, missingIntentFilters); } if (insertStatement.executeUpdate() == 0) { return NOT_FOUND; } return findAutoIncrement(); } public int find(int classId, String type, boolean exported, int permission, Integer missingIntentFilters) throws SQLException { String formatArg1 = (permission == NOT_FOUND) ? "IS" : "="; String formatArg2 = (missingIntentFilters == null) ? "IS" : "="; findStatement = getConnection().prepareStatement(String.format(FIND, formatArg1, formatArg2)); findStatement.setInt(1, classId); findStatement.setString(2, type); findStatement.setBoolean(3, exported); if (permission == NOT_FOUND) { findStatement.setNull(4, Types.VARCHAR); } else { findStatement.setInt(4, permission); } if (missingIntentFilters == null) { findStatement.setNull(5, Types.INTEGER); } else { findStatement.setInt(5, missingIntentFilters); } return processIntFindQuery(findStatement); } // public int findComponentForIntent(int appId, String clazz, Set<String> usesPermissions) // throws SQLException { // StringBuilder queryBuilder = new StringBuilder(FIND_COMPONENT_FOR_EXPLICIT_INTENT); // // if (usesPermissions != null) { // for (int i = 0; i < usesPermissions.size(); ++i) { // queryBuilder.append(" OR permission = ?"); // } // } // queryBuilder.append(")"); // // findComponentForIntentStatement = getConnection().prepareStatement(queryBuilder.toString()); // // int parameterIndex = 1; // findComponentForIntentStatement.setInt(parameterIndex++, appId); // findComponentForIntentStatement.setBoolean(parameterIndex++, true); // findComponentForIntentStatement.setString(parameterIndex++, clazz.replace("/", ".")); // findComponentForIntentStatement.setNull(parameterIndex++, Types.VARCHAR); // if (usesPermissions != null) { // for (String usesPermission : usesPermissions) { // findComponentForIntentStatement.setString(parameterIndex++, usesPermission); // } // } // // // System.out.println("Explicit matching: " + findComponentForIntentStatement.toString()); // // long startTime = System.nanoTime(); // ResultSet resultSet = findComponentForIntentStatement.executeQuery(); // // long endTime = System.nanoTime(); // // long duration = endTime - startTime; // // System.out.println(duration); // int result; // if (resultSet.next()) { // result = resultSet.getInt("Components.id"); // } else { // result = NOT_FOUND; // } // resultSet.close(); // return result; // } }
5,066
37.097744
98
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/Constants.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; public class Constants { public static final class PermissionLevel { public static final String NORMAL_SHORT = "n"; public static final String DANGEROUS_SHORT = "d"; public static final String SIGNATURE_SHORT = "s"; public static final String SIGNATURE_OR_SYSTEM_SHORT = "o"; } public static final class ComponentShortType { public static final String ACTIVITY = "a"; public static final String SERVICE = "s"; public static final String RECEIVER = "r"; public static final String PROVIDER = "p"; public static final String DYNAMIC_RECEIVER = "d"; } public static final class ValueLimit { public static final int BUNDLE = 20 * 1024; public static final int INTENT = 20 * 1024; public static final int FILTER = 20 * 1024; } public static final String ANY_STRING = "(.*)"; public static final String ANY_CLASS = "<ANY_CLASS>"; public static final int NOT_FOUND = -1; }
1,705
35.297872
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/DbConnection.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import edu.psu.cse.siis.coal.values.BasePropagationValue; import edu.psu.cse.siis.coal.values.BottomPropagationValue; import edu.psu.cse.siis.coal.values.NullPathValue; import edu.psu.cse.siis.coal.values.PathValue; import edu.psu.cse.siis.coal.values.PropagationValue; import edu.psu.cse.siis.coal.values.TopPropagationValue; public class DbConnection extends SQLConnection { public static Map<PathValue, Integer> insertIntentAtExitPoint(String className, String method, int instruction, BasePropagationValue intentValue, String exit_kind, Set<String> intentPermissions, Integer missingIntents, Set<String> exitPointComponents, Map<String, Integer> componentToIdMap) throws SQLException { PropagationValue propagationValue = null; if (intentValue == null || intentValue instanceof TopPropagationValue || intentValue instanceof BottomPropagationValue) { missingIntents = 0; } else if (intentValue instanceof PropagationValue) { propagationValue = (PropagationValue) intentValue; if (propagationValue.getPathValues() == null || propagationValue.getPathValues().size() == 0) { missingIntents = 0; } } else { throw new RuntimeException("Unknown PropagationValue type: " + intentValue.getClass()); } int exitPointId = insertExitPoint(className, method, instruction, exit_kind, missingIntents); Set<Pair<Integer, Integer>> exitPointComponentPairs = new HashSet<>(); for (String exitPointComponent : exitPointComponents) { exitPointComponentPairs.add(new Pair<Integer, Integer>(exitPointId, componentToIdMap .get(exitPointComponent))); } exitPointComponentTable.batchInsert(exitPointComponentPairs); Map<PathValue, Integer> pairs = new HashMap<PathValue, Integer>(); // if (intentValue.getIgnored()) { // missedIntentTable.insert(exitPointId, Constants.NOT_FOUND); // } else { if (missingIntents == null) { Set<PathValue> singleIntentValues = propagationValue.getPathValues(); if (singleIntentValues != null) { for (PathValue singleIntentValue : singleIntentValues) { if (exit_kind.equals(Constants.ComponentShortType.PROVIDER)) { insertUriAndValue(exitPointId, singleIntentValue); } else { int intentId = insertIntentAndValue(exitPointId, singleIntentValue); if (intentId != Constants.NOT_FOUND) { pairs.put(singleIntentValue, intentId); } } } } } // } if (intentPermissions != null) { for (String intentPermission : intentPermissions) { insertIntentPermission(exitPointId, intentPermission); } } return pairs; } public static void insertComponentExtras(Set<String> entryPoints, Map<String, Integer> componentToIdMap, Set<String> extras) throws SQLException { for (String entryPoint : entryPoints) { for (String extra : extras) { componentExtraTable.insert(componentToIdMap.get(entryPoint), extra); } } } protected static int insertIntentAndValue(int exitPointId, PathValue singleIntentValue) throws SQLException { // System.out.println(singleIntentValue); List<Integer> actionIds = new ArrayList<Integer>(); List<Integer> categoryIds = new ArrayList<Integer>(); insertStrings(actionStringTable, Collections.singleton(singleIntentValue.getScalarStringFieldValue("action")), actionIds); insertStrings(categoryStringTable, singleIntentValue.getSetStringFieldValue("categories"), categoryIds); // if (find) { // int intentId = // intentTable.find(exitPointId, actionIds, categoryIds, // singleIntentValue.getSingleStringFieldValue("type"), // singleIntentValue.getStringFieldValue("extras"), false); // if (intentId != Constants.NOT_FOUND) { // return intentId; // } // } int intentId = intentTable.forceInsert(exitPointId, singleIntentValue.getScalarStringFieldValue("clazz") == null, false); // for (int actionId : actionIds) { // intentActionTable.forceInsert(intentId, actionId); // } intentActionTable.batchForceInsert(intentId, actionIds); // for (int categoryId : categoryIds) { // intentCategoryTable.forceInsert(intentId, categoryId); // } intentCategoryTable.batchForceInsert(intentId, categoryIds); String type = singleIntentValue.getScalarStringFieldValue("dataType"); if (type != null) { String[] typeParts = null; if (type.equals(Constants.ANY_STRING)) { typeParts = new String[] { Constants.ANY_STRING, Constants.ANY_STRING }; } else { typeParts = type.split("/"); if (typeParts.length != 2) { typeParts = null; } } if (typeParts != null) { intentMimeTypeTable.forceInsert(intentId, typeParts[0], typeParts[1]); } } Set<String> extras = singleIntentValue.getSetStringFieldValue("extras"); if (extras != null) { for (String extra : extras) { intentExtraTable.forceInsert(intentId, extra); } } int dataId = insertData(singleIntentValue); if (dataId != Constants.NOT_FOUND) { intentDataTable.forceInsert(intentId, dataId); } String clazz = singleIntentValue.getScalarStringFieldValue("clazz"); if (clazz != null) { intentClassTable.insert(intentId, clazz); } String pkg = singleIntentValue.getScalarStringFieldValue("package"); if (pkg != null) { intentPackageTable.insert(intentId, pkg); } return intentId; } protected static void insertUriAndValue(int exitPointId, PathValue singleIntentValue) throws SQLException { if (singleIntentValue instanceof NullPathValue) { return; } int dataId = insertData(singleIntentValue); uriTable.forceInsert(exitPointId, dataId != Constants.NOT_FOUND ? dataId : null); } protected static int insertData(PathValue singleIntentValue) throws SQLException { if (singleIntentValue.containsNonNullFieldValue("scheme") || singleIntentValue.containsNonNullFieldValue("ssp") || singleIntentValue.containsNonNullFieldValue("uri") || singleIntentValue.containsNonNullFieldValue("path") || singleIntentValue.containsNonNullFieldValue("query") || singleIntentValue.containsNonNullFieldValue("authority")) { return uriDataTable.forceInsert(singleIntentValue.getScalarStringFieldValue("scheme"), singleIntentValue.getScalarStringFieldValue("ssp"), singleIntentValue.getScalarStringFieldValue("uri"), singleIntentValue.getScalarStringFieldValue("path"), singleIntentValue.getScalarStringFieldValue("query"), singleIntentValue.getScalarStringFieldValue("authority")); } else { return Constants.NOT_FOUND; } } }
7,859
36.607656
101
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/ExitPointComponentTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class ExitPointComponentTable extends TwoIntTable { ExitPointComponentTable() { super("ExitPointComponents", "exit_id", "component_id"); } public int insert(int exitId, int componentId) throws SQLException { return super.insert(exitId, componentId); } public int find(int exitId, int componentId) throws SQLException { return super.find(exitId, componentId); } }
1,197
32.277778
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/ExitPointTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; import java.sql.Types; public class ExitPointTable extends Table { private static final String INSERT = "INSERT INTO ExitPoints " + "(class_id, method, instruction, exit_kind, missing) VALUES (?, ?, ?, ?, ?)"; // private static final String FIND = // "SELECT id FROM ExitPoints WHERE class_id = ? AND method = ? AND instruction = ? " + // "AND exit_kind = ?"; public int insert(int classId, String method, int instruction, String exit_kind, Integer missingIntents) throws SQLException { // int id = find(classId, method, instruction, exit_kind); // if (id != NOT_FOUND) { // return id; // } if (insertStatement == null || insertStatement.isClosed()) { insertStatement = getConnection().prepareStatement(INSERT); } insertStatement.setInt(1, classId); if (method.length() > 512) { method = method.substring(0, 512); } insertStatement.setString(2, method); insertStatement.setInt(3, instruction); insertStatement.setString(4, exit_kind); if (missingIntents == null) { insertStatement.setNull(5, Types.INTEGER); } else { insertStatement.setInt(5, missingIntents); } if (insertStatement.executeUpdate() == 0) { return NOT_FOUND; } return findAutoIncrement(); } // public int find(int classId, String method, int instruction, String exit_kind) // throws SQLException { // if (findStatement == null || findStatement.isClosed()) { // findStatement = getConnection().prepareStatement(FIND); // } // findStatement.setInt(1, classId); // findStatement.setString(2, method); // findStatement.setInt(3, instruction); // findStatement.setString(4, exit_kind); // return processIntFindQuery(findStatement); // } }
2,552
34.458333
89
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/FilterActionTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class FilterActionTable extends TwoIntTable { FilterActionTable() { super("IFActions", "filter_id", "action"); } public int insert(int filterId, int action) throws SQLException { return super.insert(filterId, action); } public int forceInsert(int filterId, int action) throws SQLException { return super.forceInsert(filterId, action); } public int find(int filterId, int action) throws SQLException { return super.find(filterId, action); } }
1,285
31.15
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/FilterCategoryTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class FilterCategoryTable extends TwoIntTable { FilterCategoryTable() { super("IFCategories", "filter_id", "category"); } public int insert(int filterId, int category) throws SQLException { return super.insert(filterId, category); } public int forceInsert(int filterId, int category) throws SQLException { return super.forceInsert(filterId, category); } public int find(int filterId, int category) throws SQLException { return super.find(filterId, category); } }
1,306
31.675
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/FilterDataTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; import java.sql.Types; public class FilterDataTable extends Table { private static final String INSERT = "INSERT INTO IFData " + "(filter_id, scheme, host, port, path, type, subtype) VALUES (?, ?, ?, ?, ?, ?, ?)"; public int insert(int filterId, String scheme, String host, String port, String path, String type, String subtype) throws SQLException { if (insertStatement == null || insertStatement.isClosed()) { insertStatement = getConnection().prepareStatement(INSERT); } insertStatement.setInt(1, filterId); if (scheme == null) { insertStatement.setNull(2, Types.VARCHAR); } else { insertStatement.setString(2, scheme); } if (host == null) { insertStatement.setNull(3, Types.VARCHAR); } else { insertStatement.setString(3, host); } if (port == null) { insertStatement.setNull(4, Types.VARCHAR); } else { insertStatement.setString(4, port); } if (path == null) { insertStatement.setNull(5, Types.INTEGER); } else { insertStatement.setString(5, path); } if (type == null) { insertStatement.setNull(6, Types.VARCHAR); } else { insertStatement.setString(6, type); } if (subtype == null) { insertStatement.setNull(7, Types.VARCHAR); } else { insertStatement.setString(7, subtype); } if (insertStatement.executeUpdate() == 0) { return NOT_FOUND; } return findAutoIncrement(); } }
2,279
30.666667
92
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/IntentActionTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class IntentActionTable extends TwoIntTable { IntentActionTable() { super("IActions", "intent_id", "action"); } public int insert(int intentId, int action) throws SQLException { return super.insert(intentId, action); } public int forceInsert(int intentId, int action) throws SQLException { return super.forceInsert(intentId, action); } public int find(int intentId, int action) throws SQLException { return super.find(intentId, action); } }
1,284
31.125
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/IntentCategoryTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class IntentCategoryTable extends TwoIntTable { IntentCategoryTable() { super("ICategories", "intent_id", "category"); } public int insert(int intentId, int category) throws SQLException { return super.insert(intentId, category); } public int forceInsert(int intentId, int category) throws SQLException { return super.forceInsert(intentId, category); } public int find(int intentId, int category) throws SQLException { return super.find(intentId, category); } }
1,305
31.65
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/IntentClassTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class IntentClassTable extends OneIntOneStringTable { IntentClassTable() { super("IClasses", "intent_id", "class"); } @Override public int insert(int intentId, String clazz) throws SQLException { return super.insert(intentId, clazz); } @Override public int find(int intentId, String clazz) throws SQLException { return super.find(intentId, clazz); } }
1,190
30.342105
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/IntentDataTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class IntentDataTable extends TwoIntTable { IntentDataTable() { super("IData", "intent_id", "data"); } public int forceInsert(int intentId, int data) throws SQLException { return super.forceInsert(intentId, data); } }
1,043
31.625
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/IntentExtraTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class IntentExtraTable extends OneIntOneStringTable { IntentExtraTable() { super("IExtras", "intent_id", "extra"); } @Override public int insert(int intentId, String extra) throws SQLException { return super.insert(intentId, extra); } @Override public int forceInsert(int intentId, String extra) throws SQLException { return super.forceInsert(intentId, extra); } @Override public int find(int intentId, String extra) throws SQLException { return super.find(intentId, extra); } }
1,328
29.906977
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/IntentFilterTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.List; import java.util.Set; public class IntentFilterTable extends Table { private static final String INSERT = "INSERT INTO IntentFilters (component_id, alias) " + "VALUES (?, ?)"; private static final String FIND = "SELECT IntentFilters.id, COUNT(IntentFilters.id) AS cnt " + "FROM IntentFilters " + "LEFT JOIN IFActions ON IntentFilters.id = IFActions.filter_id " + "LEFT JOIN IFCategories ON IntentFilters.id = IFCategories.filter_id " + "LEFT JOIN IFMimeTypes ON IntentFilters.id = IFMimeTypes.filter_id " + "WHERE component_id = ? AND alias = ?"; public int forceInsert(int componentId, boolean alias) throws SQLException { // int id = find(connection, componentId, actions, categories, mimeTypes); // if (id != NOT_FOUND) { // return id; // } if (insertStatement == null || insertStatement.isClosed()) { insertStatement = getConnection().prepareStatement(INSERT); } insertStatement.setInt(1, componentId); insertStatement.setBoolean(2, alias); if (insertStatement.executeUpdate() == 0) { return NOT_FOUND; } return findAutoIncrement(); } public int find(int componentId, List<Integer> actions, List<Integer> categories, Set<String> mimeTypes, boolean alias) throws SQLException { StringBuilder queryBuilder = new StringBuilder(FIND); int finalCount = 1; if (actions != null && actions.size() > 0) { queryBuilder.append(" AND (1 = 0"); for (int i = 0; i < actions.size(); ++i) { queryBuilder.append(" OR action = ?"); } queryBuilder.append(")"); finalCount *= actions.size(); } else { queryBuilder.append(" AND action IS ?"); } if (categories != null && categories.size() > 0) { queryBuilder.append(" AND (1 = 0"); for (int i = 0; i < categories.size(); ++i) { queryBuilder.append(" OR category = ?"); } queryBuilder.append(")"); finalCount *= categories.size(); } else { queryBuilder.append(" AND category IS ?"); } List<String[]> typePartList = null; if (mimeTypes != null && mimeTypes.size() > 0) { typePartList = new ArrayList<String[]>(); queryBuilder.append(" AND (1 = 0"); for (String mimeType : mimeTypes) { if (mimeType.equals(Constants.ANY_STRING)) { typePartList.add(new String[] { "*", "*" }); queryBuilder.append(" OR (type = ? AND subtype = ?)"); } else { String[] typeParts = mimeType.split("/"); if (typeParts.length == 2) { typePartList.add(typeParts); queryBuilder.append(" OR (type = ? AND subtype = ?)"); } } } queryBuilder.append(")"); if (typePartList.size() > 0) { finalCount *= mimeTypes.size(); } } else { queryBuilder.append(" AND type IS ? AND subtype IS ?"); } findStatement = getConnection().prepareStatement(queryBuilder.toString()); findStatement.setInt(1, componentId); findStatement.setBoolean(2, alias); int parameterIndex = 3; if (actions != null && actions.size() > 0) { for (Integer action : actions) { findStatement.setInt(parameterIndex++, action); } } else { findStatement.setNull(parameterIndex++, Types.INTEGER); } if (categories != null && categories.size() > 0) { for (Integer category : categories) { findStatement.setInt(parameterIndex++, category); } } else { findStatement.setNull(parameterIndex++, Types.INTEGER); } if (mimeTypes != null && mimeTypes.size() > 0) { for (String[] typePart : typePartList) { findStatement.setString(parameterIndex++, typePart[0]); findStatement.setString(parameterIndex++, typePart[1]); } } else { findStatement.setNull(parameterIndex++, Types.INTEGER); findStatement.setNull(parameterIndex, Types.INTEGER); } // System.out.println(findStatement); ResultSet resultSet = findStatement.executeQuery(); int result; if (resultSet.next() && resultSet.getInt("cnt") == finalCount) { result = resultSet.getInt("IntentFilters.id"); } else { result = NOT_FOUND; } resultSet.close(); findStatement.close(); return result; } }
5,195
33.872483
96
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/IntentMimeTypeTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class IntentMimeTypeTable extends IntentOrFilterMimeTypeTable { IntentMimeTypeTable() { super("IMimeTypes", "intent_id"); } @Override public int insert(int intentId, String type, String subtype) throws SQLException { return super.insert(intentId, type, subtype); } @Override public int forceInsert(int intentId, String type, String subtype) throws SQLException { return super.forceInsert(intentId, type, subtype); } @Override public int find(int intentId, String type, String subtype) throws SQLException { return super.find(intentId, type, subtype); } }
1,404
31.674419
89
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/IntentOrFilterMimeTypeTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; import edu.psu.cse.siis.coal.Constants; public abstract class IntentOrFilterMimeTypeTable extends Table { private static final String INSERT = "INSERT INTO %s (%s, type, subtype) VALUES (?, ?, ?)"; private static final String FIND = "SELECT id FROM %s WHERE %s = ? AND type = ? AND subtype = ?"; IntentOrFilterMimeTypeTable(String table, String column) { insertString = String.format(INSERT, table, column); findString = String.format(FIND, table, column); } public int insert(int intentOrFilterId, String type, String subtype) throws SQLException { if (type == null) { type = Constants.NULL_STRING; } if (subtype == null) { subtype = Constants.NULL_STRING; } int id = find(intentOrFilterId, type, subtype); if (id != NOT_FOUND) { return id; } return forceInsert(intentOrFilterId, type, subtype); } public int forceInsert(int intentOrFilterId, String type, String subtype) throws SQLException { if (insertStatement == null || insertStatement.isClosed()) { insertStatement = getConnection().prepareStatement(insertString); } if (type == null) { type = Constants.NULL_STRING; } if (subtype == null) { subtype = Constants.NULL_STRING; } insertStatement.setInt(1, intentOrFilterId); insertStatement.setString(2, type); insertStatement.setString(3, subtype); if (insertStatement.executeUpdate() == 0) { return NOT_FOUND; } return findAutoIncrement(); } public int find(int intentOrFilterId, String type, String subtype) throws SQLException { if (findStatement == null || findStatement.isClosed()) { findStatement = getConnection().prepareStatement(findString); } if (type == null) { type = Constants.NULL_STRING; } if (subtype == null) { subtype = Constants.NULL_STRING; } findStatement.setInt(1, intentOrFilterId); findStatement.setString(2, type); findStatement.setString(3, subtype); return processIntFindQuery(findStatement); } }
2,845
32.482353
99
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/IntentPackageTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class IntentPackageTable extends OneIntOneStringTable { IntentPackageTable() { super("IPackages", "intent_id", "package"); } @Override public int insert(int intentId, String pkg) throws SQLException { return super.insert(intentId, pkg); } @Override public int find(int intentId, String pkg) throws SQLException { return super.find(intentId, pkg); } }
1,189
30.315789
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/IntentPermissionTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class IntentPermissionTable extends TwoIntTable { IntentPermissionTable() { super("IntentPermissions", "exit_id", "i_permission"); } public int insert(int exitId, int iPermission) throws SQLException { return super.insert(exitId, iPermission); } public int find(int exitId, int iPermission) throws SQLException { return super.find(exitId, iPermission); } }
1,191
32.111111
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/IntentTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class IntentTable extends Table { private static final String INSERT = "INSERT INTO Intents (exit_id, implicit, alias) " + "VALUES (?, ?, ?)"; // private static final String FIND = "SELECT Intents.id, COUNT(Intents.id) AS cnt " // + "FROM Intents " + "LEFT JOIN IActions ON Intents.id = IActions.intent_id " // + "LEFT JOIN ICategories ON Intents.id = ICategories.intent_id " // + "LEFT JOIN IMimeTypes ON Intents.id = IMimeTypes.intent_id " // + "LEFT JOIN IExtras ON Intents.id = IExtras.intent_id " + "WHERE exit_id = ? AND alias = ?"; public int forceInsert(int exitId, boolean implicit, boolean alias) throws SQLException { // int id = find(connection, componentId, actions, categories, mimeTypes); // if (id != NOT_FOUND) { // return id; // } if (insertStatement == null || insertStatement.isClosed()) { insertStatement = getConnection().prepareStatement(INSERT); } insertStatement.setInt(1, exitId); insertStatement.setBoolean(2, implicit); insertStatement.setBoolean(3, alias); if (insertStatement.executeUpdate() == 0) { return NOT_FOUND; } return findAutoIncrement(); } // public int find(int exitId, List<Integer> actions, List<Integer> categories, String mimeType, // Set<String> extras, boolean alias) throws SQLException { // StringBuilder queryBuilder = new StringBuilder(FIND); // // if (actions != null && actions.size() > 0) { // queryBuilder.append(" AND (1 = 0"); // for (int i = 0; i < actions.size(); ++i) { // queryBuilder.append(" OR action = ?"); // } // queryBuilder.append(")"); // } else { // queryBuilder.append(" AND action IS ?"); // } // int finalCount = 1; // if (categories != null && categories.size() > 0) { // queryBuilder.append(" AND (1 = 0"); // for (int i = 0; i < categories.size(); ++i) { // queryBuilder.append(" OR category = ?"); // } // queryBuilder.append(")"); // finalCount *= categories.size(); // } else { // queryBuilder.append(" AND category IS ?"); // } // String[] typeParts = null; // if (mimeType != null) { // if (mimeType.equals(Constants.ANY_STRING)) { // queryBuilder.append(" AND type = ? AND subtype = ?"); // typeParts = new String[] { "*", "*" }; // } else { // typeParts = mimeType.split("/"); // if (typeParts.length == 2) { // queryBuilder.append(" AND type = ? AND subtype = ?"); // } else { // System.err.println("Warning: invalid type: " + mimeType); // queryBuilder.append(" AND type IS ? AND subtype IS ?"); // typeParts = null; // } // } // } else { // queryBuilder.append(" AND type IS ? AND subtype IS ?"); // } // if (extras != null && extras.size() > 0) { // queryBuilder.append(" AND (1 = 0"); // for (int i = 0; i < extras.size(); ++i) { // queryBuilder.append(" OR extra = ?"); // } // queryBuilder.append(")"); // finalCount *= extras.size(); // } else { // queryBuilder.append(" AND extra IS ?"); // } // // findStatement = getConnection().prepareStatement(queryBuilder.toString()); // // findStatement.setInt(1, exitId); // // findStatement.setBoolean(2, alias); // // int parameterIndex = 3; // // if (actions != null && actions.size() > 0) { // for (Integer action : actions) { // findStatement.setInt(parameterIndex++, action); // } // } else { // findStatement.setNull(parameterIndex++, Types.INTEGER); // } // if (categories != null && categories.size() > 0) { // for (Integer category : categories) { // findStatement.setInt(parameterIndex++, category); // } // } else { // findStatement.setNull(parameterIndex++, Types.INTEGER); // } // if (typeParts != null && typeParts.length == 2) { // findStatement.setString(parameterIndex++, typeParts[0]); // findStatement.setString(parameterIndex++, typeParts[1]); // } else { // findStatement.setNull(parameterIndex++, Types.VARCHAR); // findStatement.setNull(parameterIndex++, Types.VARCHAR); // } // if (extras != null && extras.size() > 0) { // for (String extra : extras) { // findStatement.setString(parameterIndex++, extra); // } // } else { // findStatement.setNull(parameterIndex, Types.VARCHAR); // } // // // System.out.println(findStatement); // ResultSet resultSet = findStatement.executeQuery(); // int result; // if (resultSet.next() && resultSet.getInt("cnt") == finalCount) { // result = resultSet.getInt("Intents.id"); // } else { // result = NOT_FOUND; // } // resultSet.close(); // findStatement.close(); // // return result; // } }
5,386
33.980519
98
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/LinkTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class LinkTable extends TwoIntTable { LinkTable() { super("Links", "intent_id", "component_id"); } public int insert(int intentId, int componentId) throws SQLException { return super.insert(intentId, componentId); } public int find(int intentId, int componentId) throws SQLException { return super.find(intentId, componentId); } }
1,165
31.388889
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/OneIntOneStringTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; import edu.psu.cse.siis.coal.Constants; public abstract class OneIntOneStringTable extends Table { private static final String INSERT = "INSERT INTO %s (%s, %s) VALUES (?, ?)"; private static final String FIND = "SELECT id FROM %s WHERE %s = ? AND %s = ?"; OneIntOneStringTable(String table, String firstColumn, String secondColumn) { insertString = String.format(INSERT, table, firstColumn, secondColumn); findString = String.format(FIND, table, firstColumn, secondColumn); } public int insert(int firstValue, String secondValue) throws SQLException { int id = find(firstValue, secondValue); if (id != NOT_FOUND) { return id; } return forceInsert(firstValue, secondValue); } public int forceInsert(int firstValue, String secondValue) throws SQLException { if (insertStatement == null || insertStatement.isClosed()) { insertStatement = getConnection().prepareStatement(insertString); } if (secondValue == null) { secondValue = Constants.NULL_STRING; } insertStatement.setInt(1, firstValue); insertStatement.setString(2, secondValue); if (insertStatement.executeUpdate() == 0) { return NOT_FOUND; } return findAutoIncrement(); } public int find(int firstValue, String secondValue) throws SQLException { if (findStatement == null || findStatement.isClosed()) { findStatement = getConnection().prepareStatement(findString); } findStatement.setInt(1, firstValue); findStatement.setString(2, secondValue); return processIntFindQuery(findStatement); } }
2,384
35.136364
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/Pair.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.util.Objects; public class Pair<T, U> { protected T o1; protected U o2; public Pair() { o1 = null; o2 = null; } public Pair(T o1, U o2) { this.o1 = o1; this.o2 = o2; } @Override public int hashCode() { return Objects.hash(this.o1, this.o2); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof Pair)) { return false; } Pair<?, ?> pair = (Pair<?, ?>) other; return Objects.equals(this.o1, pair.o1) && Objects.equals(this.o2, pair.o2); } @Override public String toString() { return "Pair " + o1 + "," + o2; } public T getO1() { return o1; } public U getO2() { return o2; } public void setO1(T no1) { o1 = no1; } public void setO2(U no2) { o2 = no2; } public void setPair(T no1, U no2) { o1 = no1; o2 = no2; } }
1,692
20.1625
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/PermissionTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.PreparedStatement; import java.sql.SQLException; public class PermissionTable extends Table { private static final String INSERT = "INSERT INTO Permissions (id, level) VALUES (?, ?)"; private static final String FIND = "SELECT id FROM Permissions WHERE id = ? AND level = ?"; private static final String FIND_SIGNATURE_OR_SYSTEM = "SELECT Permissions.id FROM Permissions " + "JOIN PermissionStrings ON Permissions.id = PermissionStrings.id " + "WHERE st = ? AND (level = ? OR level = ?)"; private PreparedStatement findSignatureOrSystemStatement; PermissionTable() { } public int insert(int permissionId, String level) throws SQLException { int id = find(permissionId, level); if (id != NOT_FOUND) { return id; } return forceInsert(permissionId, level); } public int forceInsert(int permissionId, String level) throws SQLException { if (insertStatement == null || insertStatement.isClosed()) { insertStatement = getConnection().prepareStatement(INSERT); } insertStatement.setInt(1, permissionId); insertStatement.setString(2, level); if (insertStatement.executeUpdate() == 0) { return NOT_FOUND; } return permissionId; } public int find(int permissionId, String level) throws SQLException { if (findStatement == null || findStatement.isClosed()) { findStatement = getConnection().prepareStatement(FIND); } findStatement.setInt(1, permissionId); findStatement.setString(2, level); return processIntFindQuery(findStatement); } /** * Figure out if a permission is a signature or signatureOrSystem one. * * @param permission The permission to look for. * @return True if the permission is found and it is has a signature or signatureOrSystem * protection level. Note that this returns false if the permission is not found, even if * it is in fact a signature or signatureOrSystem permission. * @throws SQLException */ public boolean isSignatureOrSystem(String permission) throws SQLException { if (findSignatureOrSystemStatement == null || findSignatureOrSystemStatement.isClosed()) { findStatement = getConnection().prepareStatement(FIND_SIGNATURE_OR_SYSTEM); } findStatement.setString(1, permission); findStatement.setString(2, Constants.PermissionLevel.SIGNATURE_SHORT); findStatement.setString(3, Constants.PermissionLevel.SIGNATURE_OR_SYSTEM_SHORT); return processIntFindQuery(findStatement) != NOT_FOUND; } }
3,306
38.369048
99
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/ProviderAuthorityTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class ProviderAuthorityTable extends OneIntOneStringTable { ProviderAuthorityTable() { super("PAuthorities", "provider_id", "authority"); } @Override public int insert(int providerId, String authority) throws SQLException { return super.insert(providerId, authority); } @Override public int find(int providerId, String authority) throws SQLException { return super.find(providerId, authority); } }
1,236
31.552632
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/ProviderTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; import java.sql.Types; public class ProviderTable extends Table { private static final String INSERT = "INSERT INTO Providers " + "(component_id, grant_uri_permissions, read_permission, write_permission) " + "VALUES (?, ?, ?, ?)"; public int insert(int componentId, boolean grantUriPermissions, String readPermission, String writePermission) throws SQLException { if (insertStatement == null || insertStatement.isClosed()) { insertStatement = getConnection().prepareStatement(INSERT); } insertStatement.setInt(1, componentId); insertStatement.setBoolean(2, grantUriPermissions); if (readPermission == null) { insertStatement.setNull(3, Types.VARCHAR); } else { insertStatement.setString(3, readPermission); } if (writePermission == null) { insertStatement.setNull(4, Types.VARCHAR); } else { insertStatement.setString(4, writePermission); } if (insertStatement.executeUpdate() == 0) { return NOT_FOUND; } return findAutoIncrement(); } }
1,853
33.333333
88
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/SQLConnection.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import edu.psu.cse.siis.ic3.manifest.ManifestComponent; import edu.psu.cse.siis.ic3.manifest.ManifestData; import edu.psu.cse.siis.ic3.manifest.ManifestIntentFilter; import edu.psu.cse.siis.ic3.manifest.ManifestProviderComponent; public class SQLConnection { protected static ApplicationTable applicationTable = new ApplicationTable(); protected static IntentTable intentTable = new IntentTable(); protected static IntentFilterTable intentFilterTable = new IntentFilterTable(); protected static IntentMimeTypeTable intentMimeTypeTable = new IntentMimeTypeTable(); protected static IntentActionTable intentActionTable = new IntentActionTable(); protected static FilterActionTable filterActionTable = new FilterActionTable(); protected static IntentCategoryTable intentCategoryTable = new IntentCategoryTable(); protected static FilterCategoryTable filterCategoryTable = new FilterCategoryTable(); protected static IntentDataTable intentDataTable = new IntentDataTable(); protected static FilterDataTable filterDataTable = new FilterDataTable(); protected static IntentClassTable intentClassTable = new IntentClassTable(); protected static IntentPackageTable intentPackageTable = new IntentPackageTable(); protected static StringTable actionStringTable = new StringTable("ActionStrings"); protected static StringTable categoryStringTable = new StringTable("CategoryStrings"); protected static StringTable permissionStringTable = new StringTable("PermissionStrings"); protected static UsesPermissionTable usesPermissionTable = new UsesPermissionTable(); protected static IntentPermissionTable intentPermissionTable = new IntentPermissionTable(); protected static ClassTable classTable = new ClassTable(); protected static IntentExtraTable intentExtraTable = new IntentExtraTable(); protected static ComponentTable componentTable = new ComponentTable(); protected static ComponentExtraTable componentExtraTable = new ComponentExtraTable(); protected static ExitPointTable exitPointTable = new ExitPointTable(); protected static ExitPointComponentTable exitPointComponentTable = new ExitPointComponentTable(); protected static PermissionTable permissionTable = new PermissionTable(); protected static UriDataTable uriDataTable = new UriDataTable(); protected static UriTable uriTable = new UriTable(); protected static ProviderTable providerTable = new ProviderTable(); protected static ProviderAuthorityTable providerAuthorityTable = new ProviderAuthorityTable(); protected static int appId = Constants.NOT_FOUND; public static void init(String dbName, String dbPropertiesPath, String sshPropertiesPath, int localDbPort) { Table.init(dbName, dbPropertiesPath, sshPropertiesPath, localDbPort); } public static void closeConnection() { Table.closeConnection(); } public static Map<String, Integer> insert(String app, int version, List<ManifestComponent> intentFilters, Set<String> usesPermissions, Map<String, String> permissions, boolean skipEntryPoints) { try { if (appId == Constants.NOT_FOUND) { appId = applicationTable.insert(app, version); } if (usesPermissions != null && !insertUsesPermissions(usesPermissions)) { return null; } if (permissions != null && !insertPermissions(permissions)) { return null; } if (skipEntryPoints) { return Collections.emptyMap(); } else { return insertIntentFilters(intentFilters); } } catch (SQLException e) { e.printStackTrace(); return null; } } protected static boolean insertUsesPermissions(Set<String> usesPermissions) throws SQLException { if (usesPermissions == null) { return true; } Set<Integer> permissionIds = permissionStringTable.batchInsert(usesPermissions, null); for (int permissionId : permissionIds) { usesPermissionTable.insert(appId, permissionId); } return true; } protected static boolean insertPermissions(Map<String, String> permissions) throws SQLException { for (Map.Entry<String, String> entry : permissions.entrySet()) { int permissionId = permissionStringTable.insert(entry.getKey()); permissionTable.insert(permissionId, entry.getValue()); } return true; } /** * Figure out if a permission is a signature or signatureOrSystem one. * * @param permission The permission to look for. * @return True if the permission is found and it is has a signature or signatureOrSystem * protection level. Note that this returns false if the permission is not found, even if * it is in fact a signature or signatureOrSystem permission. * @throws SQLException */ public static boolean isSignatureOrSystem(String permission) throws SQLException { return permissionTable.isSignatureOrSystem(permission); } public static Map<String, Integer> insertIntentFilters(List<ManifestComponent> components) throws SQLException { if (appId == Constants.NOT_FOUND) { throw new RuntimeException("appId has not been set"); } Map<String, Integer> componentIds = new HashMap<String, Integer>(); for (ManifestComponent component : components) { int componentId; if (component instanceof ManifestProviderComponent) { componentId = insertProvider((ManifestProviderComponent) component); componentIds.put(component.getName(), componentId); continue; } componentId = insertComponent(component.getName(), component.getType(), component.isExported(), component.getPermission(), component.missingIntentFilters()); componentIds.put(component.getName(), componentId); Set<ManifestIntentFilter> intentFilters = component.getIntentFilters(); // System.out.println("Inserting " + intentFilters); if (intentFilters != null) { for (ManifestIntentFilter intentFilter : component.getIntentFilters()) { List<Integer> actionIds = new ArrayList<Integer>(); List<Integer> categoryIds = new ArrayList<Integer>(); // System.out.println(intentFilter.getActions()); insertStrings(actionStringTable, intentFilter.getActions(), actionIds); insertStrings(categoryStringTable, intentFilter.getCategories(), categoryIds); // if (find) { // find = // (intentFilterTable.find(componentId, actionIds, categoryIds, // intentFilter.getMimeTypes(), intentFilter.isAlias()) != Constants.NOT_FOUND); // } // if (find) { // // System.out.println("Found"); // continue; // } int filterId = intentFilterTable.forceInsert(componentId, intentFilter.isAlias()); // System.out.println("Inserting actions " + actionIds); filterActionTable.batchForceInsert(filterId, actionIds); // for (int actionId : actionIds) { // filterActionTable.forceInsert(filterId, actionId); // } filterCategoryTable.batchForceInsert(filterId, categoryIds); // for (int categoryId : categoryIds) { // filterCategoryTable.forceInsert(filterId, categoryId); // } insertFilterData(filterId, intentFilter); } } } return componentIds; } protected static int insertProvider(ManifestProviderComponent component) throws SQLException { int componentId = insertComponent(component.getName(), component.getType(), component.isExported(), null, null); int providerId = providerTable.insert(componentId, component.getGrantUriPermissions(), component.getReadPermission(), component.getWritePermission()); Set<String> authorities = component.getAuthorities(); if (authorities != null) { for (String authority : authorities) { providerAuthorityTable.insert(providerId, authority); } } return componentId; } protected static void insertFilterData(Integer filterId, ManifestIntentFilter intentFilter) throws SQLException { List<ManifestData> data = intentFilter.getData(); if (data != null) { for (ManifestData manifestData : data) { String type = null; String subtype = null; String mimeType = manifestData.getMimeType(); if (mimeType != null) { String[] typeParts = null; if (mimeType.equals(Constants.ANY_STRING)) { type = "*"; subtype = "*"; } else { typeParts = mimeType.split("/"); if (typeParts.length != 2) { type = null; subtype = null; } else { type = typeParts[0]; subtype = typeParts[1]; } } } filterDataTable.insert(filterId, manifestData.getScheme(), manifestData.getHost(), manifestData.getPort(), manifestData.getPath(), type, subtype); } } } protected static boolean insertStrings(StringTable table, Set<String> strings, List<Integer> output) throws SQLException { boolean[] allThere = new boolean[] { false }; output.addAll(table.batchInsert(strings, allThere)); if (strings != null) { for (String string : strings) { if (string != null) { int stringId = table.find(string); if (stringId == Constants.NOT_FOUND) { throw new RuntimeException("error: string '" + string + "' not found in table."); } else { output.add(stringId); } } } } return allThere[0]; } protected static boolean findStrings(StringTable table, Set<String> strings, List<Integer> output) throws SQLException { if (strings == null) { return true; } // if (strings.contains(ConnectedComponents.ANY_STRING) // || strings.contains(ConnectedComponents.ANY_CLASS)) { // output.add(Constants.NOT_FOUND); // return true; // } for (String string : strings) { if (string != null) { if (string.equals(Constants.ANY_STRING) || string.equals(Constants.ANY_CLASS)) { output.add(Constants.NOT_FOUND); } int stringId = table.find(string); if (stringId == Constants.NOT_FOUND) { return false; } else { output.add(stringId); } } } return true; } // protected static boolean insertAndSplitStrings(StringTable table, Set<String> strings, // List<Integer[]> output) throws SQLException { // if (strings == null) { // return true; // } // boolean allThere = true; // for (String string : strings) { // if (string != null) { // String[] typeParts; // if (string.equals(Constants.ANY_STRING)) { // typeParts = new String[] {"*", "*"}; // } else { // typeParts = string.split("/"); // if (typeParts.length != 2) { // System.err.println("Wrong MIME type format: " + string); // } // } // int part1 = table.find(typeParts[0]); // if (part1 == Constants.NOT_FOUND) { // allThere = false; // part1 = table.forceInsert(typeParts[0]); // } // int part2 = table.find(typeParts[1]); // if (part2 == Constants.NOT_FOUND) { // allThere = false; // part2 = table.forceInsert(typeParts[1]); // } // output.add(new Integer[] { part1, part2 }); // } // } // return allThere; // } // // protected static boolean findAndSplitStrings(StringTable table, Set<String> strings, // List<Integer[]> output) throws SQLException { // if (strings == null) { // return true; // } // if (strings.contains(Constants.ANY_STRING)) { // output.add(null); // return true; // } // for (String string : strings) { // if (string != null) { // String[] typeParts; // if (string.equals(Constants.ANY_STRING)) { // typeParts = new String[] {"*", "*"}; // } else { // typeParts = string.split("/"); // if (typeParts.length != 2) { // System.err.println("Wrong MIME type format: " + string); // } // } // int part1 = table.find(typeParts[0]); // if (part1 == Constants.NOT_FOUND) { // return false; // } // int part2 = table.find(typeParts[1]); // if (part2 == Constants.NOT_FOUND) { // return false; // } // output.add(new Integer[] { part1, part2 }); // } // } // return true; // } public static int insertComponent(String name, String type, boolean exported, String permission, Integer missingIntentFilters) throws SQLException { int classId = insertClass(name); int permissionId = (permission == null) ? Constants.NOT_FOUND : permissionStringTable.insert(permission); return componentTable.insert(classId, type, exported, permissionId, missingIntentFilters); } protected static int insertClass(String clazz) throws SQLException { return classTable.insert(appId, clazz); } protected static boolean insertIntentPermission(int exitPointId, String intentPermission) throws SQLException { int permissionId = permissionStringTable.insert(intentPermission); intentPermissionTable.insert(exitPointId, permissionId); return true; } protected static int insertExitPoint(String className, String method, int instruction, String exit_kind, Integer missingIntentFilters) throws SQLException { int classId = insertClass(className); return exitPointTable.insert(classId, method, instruction, exit_kind, missingIntentFilters); } }
14,435
36.790576
101
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/StringTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import edu.psu.cse.siis.coal.Constants; public class StringTable extends Table { private static final String INSERT = "INSERT INTO %s (st) VALUES (?)"; private static final String FIND = "SELECT id FROM %s WHERE st = ?"; private static final String BATCH_INSERT = INSERT; private static final String BATCH_FIND = "SELECT id, st FROM %s WHERE st IN (?"; StringTable(String table) { insertString = String.format(INSERT, table); findString = String.format(FIND, table); batchInsertString = String.format(BATCH_INSERT, table); batchFindString = String.format(BATCH_FIND, table); } public Map<String, Integer> batchFind(Set<String> strings) throws SQLException { Map<String, Integer> result = new HashMap<String, Integer>(); if (strings == null || strings.size() == 0 || (strings.size() == 1 && strings.contains(null))) { return result; } StringBuilder queryBuilder = new StringBuilder(batchFindString); for (int i = 1; i < strings.size(); ++i) { queryBuilder.append(", ?"); } queryBuilder.append(")"); PreparedStatement batchFindStatement = getConnection().prepareStatement(queryBuilder.toString()); int parameterIndex = 1; for (String string : strings) { if (string == null) { string = Constants.NULL_STRING; } batchFindStatement.setString(parameterIndex++, string); } ResultSet resultSet = batchFindStatement.executeQuery(); while (resultSet.next()) { result.put(resultSet.getString("st"), resultSet.getInt("id")); } return result; } public Set<Integer> batchInsert(Set<String> strings, boolean[] allThere) throws SQLException { if (strings == null || (strings.size() == 1 && strings.contains(null))) { if (allThere != null) { // System.out.println("TEST1"); allThere[0] = true; } return new HashSet<Integer>(); } Map<String, Integer> alreadyThere = batchFind(strings); // System.out.println("Found " + alreadyThere + " for " + strings); Set<String> toBeInserted = new HashSet<String>(strings); toBeInserted.removeAll(alreadyThere.keySet()); Set<Integer> result = new HashSet<Integer>(alreadyThere.values()); if (toBeInserted.size() == 0) { if (allThere != null) { // System.out.println("TEST2"); allThere[0] = true; } return result; } StringBuilder queryBuilder = new StringBuilder(batchInsertString); for (int i = 1; i < toBeInserted.size(); ++i) { queryBuilder.append(", (?)"); } PreparedStatement batchInsertStatement = getConnection().prepareStatement(queryBuilder.toString(), AUTOGENERATED_ID); int parameterIndex = 1; for (String string : toBeInserted) { if (string == null) { string = Constants.NULL_STRING; } batchInsertStatement.setString(parameterIndex++, string); } batchInsertStatement.executeUpdate(); ResultSet resultSet = batchInsertStatement.getGeneratedKeys(); while (resultSet.next()) { result.add(resultSet.getInt(1)); } // System.out.println("TEST3"); return result; } public int insert(String st) throws SQLException { if (st == null) { st = Constants.NULL_STRING; } int id = find(st); if (id != NOT_FOUND) { return id; } return forceInsert(st); } public int forceInsert(String st) throws SQLException { if (insertStatement == null || insertStatement.isClosed()) { insertStatement = getConnection().prepareStatement(insertString); } if (st == null) { st = Constants.NULL_STRING; } insertStatement.setString(1, st); if (insertStatement.executeUpdate() == 0) { return NOT_FOUND; } return findAutoIncrement(); } public int find(String st) throws SQLException { if (findStatement == null || findStatement.isClosed()) { findStatement = getConnection().prepareStatement(findString); } if (st == null) { st = Constants.NULL_STRING; } findStatement.setString(1, st); return processIntFindQuery(findStatement); } }
5,081
32.215686
100
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/Table.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; public abstract class Table { private static final String SELECT_LAST_INSERT_ID = "SELECT LAST_INSERT_ID()"; private static final int MYSQL_PORT = 3306; protected static final String ID = "id"; protected static final String[] AUTOGENERATED_ID = new String[] { ID }; private static String url = null; private static Session session = null; private static Connection connection = null; private static String sshPropertiesPath; private static String dbPropertiesPath; private static int localPort; protected static final int NOT_FOUND = Constants.NOT_FOUND; protected String insertString; protected String findString; protected String batchInsertString; protected String batchFindString; protected PreparedStatement insertStatement = null; protected PreparedStatement findStatement = null; private PreparedStatement selectLastInsertId = null; public static void init(String dbName, String dbPropertiesPath, String sshPropertiesPath, int localPort) { Table.sshPropertiesPath = sshPropertiesPath; Table.dbPropertiesPath = dbPropertiesPath; Table.localPort = localPort; url = sshPropertiesPath != null ? "jdbc:mysql://localhost:" + localPort + "/" + dbName : "jdbc:mysql://localhost/" + dbName; } public static Connection getConnection() { connect(); return connection; } public static void closeConnection() { try { if (connection != null && !connection.isClosed()) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } if (session != null && session.isConnected()) { session.disconnect(); } } private static void makeSshTunnel() throws IOException, NumberFormatException, JSchException { if (session != null && session.isConnected()) { return; } Properties sshProperties = new Properties(); if (sshPropertiesPath.startsWith("/db/")) { sshProperties.load(Table.class.getResourceAsStream(sshPropertiesPath)); } else { sshProperties.load(new FileReader(sshPropertiesPath)); } JSch jSch = new JSch(); String host = sshProperties.getProperty("host"); session = jSch.getSession(sshProperties.getProperty("user"), host, Integer.valueOf(sshProperties.getProperty("port"))); session.setConfig("StrictHostKeyChecking", "no"); jSch.addIdentity(sshProperties.getProperty("identity")); session.connect(); session.setPortForwardingL(localPort, host, MYSQL_PORT); } private static void connect() { if (url == null) { throw new RuntimeException( "Method init() should be called first to initialize database connection"); } if (sshPropertiesPath != null) { try { makeSshTunnel(); } catch (NumberFormatException | IOException | JSchException e) { e.printStackTrace(); return; } } try { if (connection != null && !connection.isClosed()) { return; } } catch (SQLException e2) { e2.printStackTrace(); } Properties properties = new Properties(); try { if (dbPropertiesPath.startsWith("/db/")) { properties.load(SQLConnection.class.getResourceAsStream(dbPropertiesPath)); } else { properties.load(new FileReader(dbPropertiesPath)); } } catch (IOException e1) { e1.printStackTrace(); return; } try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { e.printStackTrace(); return; } try { connection = DriverManager.getConnection(url, properties); } catch (SQLException e) { e.printStackTrace(); return; } } protected int findAutoIncrement() throws SQLException { connect(); if (selectLastInsertId == null || selectLastInsertId.isClosed()) { selectLastInsertId = connection.prepareStatement(SELECT_LAST_INSERT_ID); } ResultSet resultSet = selectLastInsertId.executeQuery(); int autoinc; if (resultSet.next()) { autoinc = resultSet.getInt("LAST_INSERT_ID()"); } else { autoinc = NOT_FOUND; } resultSet.close(); return autoinc; } protected int processIntFindQuery(PreparedStatement statement) throws SQLException { return processIntFindQuery(statement, "id"); } protected int processIntFindQuery(PreparedStatement statement, String column) throws SQLException { ResultSet resultSet = statement.executeQuery(); int result; if (resultSet.next()) { result = resultSet.getInt(column); } else { result = NOT_FOUND; } resultSet.close(); return result; } }
5,851
29.479167
101
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/TwoIntTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public abstract class TwoIntTable extends Table { private static final String INSERT = "INSERT INTO %s (%s, %s) VALUES (?, ?)"; private static final String FIND = "SELECT id FROM %s WHERE %s = ? AND %s = ?"; private static final String BATCH_INSERT = INSERT; private static final String BATCH_FIND = "SELECT %s, %s, %s FROM %s WHERE 1 = 0"; private final String firstColumn; private final String secondColumn; private final String batchInsertPattern; private final String batchFindPattern; TwoIntTable(String table, String firstColumn, String secondColumn) { insertString = String.format(INSERT, table, firstColumn, secondColumn); findString = String.format(FIND, table, firstColumn, secondColumn); batchInsertString = String.format(BATCH_INSERT, table, firstColumn, secondColumn); batchFindString = String.format(BATCH_FIND, ID, firstColumn, secondColumn, table); this.firstColumn = firstColumn; this.secondColumn = secondColumn; this.batchInsertPattern = String.format(", (?, ?)"); this.batchFindPattern = String.format(" OR (%s = ? AND %s = ?)", firstColumn, secondColumn); } public Map<Pair<Integer, Integer>, Integer> batchFind(Set<Pair<Integer, Integer>> values) throws SQLException { Map<Pair<Integer, Integer>, Integer> found = new HashMap<Pair<Integer, Integer>, Integer>(); if (values == null || values.size() == 0) { return found; } StringBuilder queryBuilder = new StringBuilder(batchFindString); for (int i = 0; i < values.size(); ++i) { queryBuilder.append(batchFindPattern); } PreparedStatement batchFindStatement = getConnection().prepareStatement(queryBuilder.toString()); int parameterIndex = 1; for (Pair<Integer, Integer> value : values) { batchFindStatement.setInt(parameterIndex++, value.getO1()); batchFindStatement.setInt(parameterIndex++, value.getO2()); } ResultSet resultSet = batchFindStatement.executeQuery(); while (resultSet.next()) { found .put( new Pair<Integer, Integer>(resultSet.getInt(firstColumn), resultSet .getInt(secondColumn)), resultSet.getInt(ID)); } return found; } public Set<Integer> batchInsert(Set<Pair<Integer, Integer>> values) throws SQLException { Map<Pair<Integer, Integer>, Integer> found = batchFind(values); Set<Pair<Integer, Integer>> toBeInserted = new HashSet<Pair<Integer, Integer>>(values); // Take the set difference. Obtain the values which have not been found; toBeInserted.removeAll(found.keySet()); Set<Integer> result = batchForceInsert(toBeInserted); result.addAll(found.values()); return result; } public Set<Integer> batchForceInsert(Set<Pair<Integer, Integer>> values) throws SQLException { Set<Integer> result = new HashSet<Integer>(); if (values.size() > 0) { StringBuilder queryBuilder = new StringBuilder(batchInsertString); for (int i = 1; i < values.size(); ++i) { queryBuilder.append(batchInsertPattern); } PreparedStatement batchInsertStatement = getConnection().prepareStatement(queryBuilder.toString(), AUTOGENERATED_ID); int parameterIndex = 1; for (Pair<Integer, Integer> value : values) { batchInsertStatement.setInt(parameterIndex++, value.getO1()); batchInsertStatement.setInt(parameterIndex++, value.getO2()); } batchInsertStatement.executeUpdate(); ResultSet resultSet = batchInsertStatement.getGeneratedKeys(); while (resultSet.next()) { result.add(resultSet.getInt(1)); } } return result; } public Set<Integer> batchForceInsert(Integer firstValue, List<Integer> values) throws SQLException { Set<Pair<Integer, Integer>> newValues = new HashSet<Pair<Integer, Integer>>(); if (values == null || values.size() == 0) { return new HashSet<Integer>(); } for (int value : values) { newValues.add(new Pair<Integer, Integer>(firstValue, value)); } return batchForceInsert(newValues); } public int insert(Integer firstValue, Integer secondValue) throws SQLException { int id = find(firstValue, secondValue); if (id != NOT_FOUND) { return id; } return forceInsert(firstValue, secondValue); } public int forceInsert(Integer firstValue, Integer secondValue) throws SQLException { if (insertStatement == null || insertStatement.isClosed()) { insertStatement = getConnection().prepareStatement(insertString); } if (firstValue != null) { insertStatement.setInt(1, firstValue); } else { insertStatement.setNull(1, Types.INTEGER); } if (secondValue != null) { insertStatement.setInt(2, secondValue); } else { insertStatement.setNull(2, Types.INTEGER); } if (insertStatement.executeUpdate() == 0) { return NOT_FOUND; } return findAutoIncrement(); } public int find(Integer firstValue, Integer secondValue) throws SQLException { if (findStatement == null || findStatement.isClosed()) { findStatement = getConnection().prepareStatement(findString); } if (firstValue != null) { findStatement.setInt(1, firstValue); } else { findStatement.setNull(1, Types.INTEGER); } if (secondValue != null) { findStatement.setInt(2, secondValue); } else { findStatement.setNull(2, Types.INTEGER); } return processIntFindQuery(findStatement); } }
6,504
35.960227
96
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/UriDataTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; import java.sql.Types; public class UriDataTable extends Table { private static final String INSERT = "INSERT INTO UriData " + "(scheme, ssp, uri, path, query, authority) VALUES (?, ?, ?, ?, ?, ?)"; public int forceInsert(String scheme, String ssp, String uri, String path, String query, String authority) throws SQLException { // int id = find(connection, componentId, actions, categories, mimeTypes); // if (id != NOT_FOUND) { // return id; // } if (insertStatement == null || insertStatement.isClosed()) { insertStatement = getConnection().prepareStatement(INSERT); } if (scheme == null) { insertStatement.setNull(1, Types.VARCHAR); } else { insertStatement.setString(1, scheme); } if (ssp == null) { insertStatement.setNull(2, Types.VARCHAR); } else { insertStatement.setString(2, ssp); } if (uri == null) { insertStatement.setNull(3, Types.VARCHAR); } else { insertStatement.setString(3, uri); } if (path == null) { insertStatement.setNull(4, Types.VARCHAR); } else { insertStatement.setString(4, path); } if (query == null) { insertStatement.setNull(5, Types.VARCHAR); } else { insertStatement.setString(5, query); } if (authority == null) { insertStatement.setNull(6, Types.VARCHAR); } else { insertStatement.setString(6, authority); } if (insertStatement.executeUpdate() == 0) { return NOT_FOUND; } return findAutoIncrement(); } }
2,352
30.797297
90
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/UriTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class UriTable extends TwoIntTable { UriTable() { super("Uris", "exit_id", "data"); } @Override public int forceInsert(Integer exitPointId, Integer data) throws SQLException { return super.forceInsert(exitPointId, data); } }
1,052
30.909091
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/db/UsesPermissionTable.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.db; import java.sql.SQLException; public class UsesPermissionTable extends TwoIntTable { UsesPermissionTable() { super("UsesPermissions", "app_id", "uses_permission"); } public int insert(int appId, int usesPermission) throws SQLException { return super.insert(appId, usesPermission); } public int find(int appId, int usesPermission) throws SQLException { return super.find(appId, usesPermission); } }
1,195
32.222222
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/manifest/ManifestComponent.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.manifest; import java.util.HashSet; import java.util.Set; import soot.SootMethod; import soot.Unit; public class ManifestComponent { private final String name; private boolean exported; private final boolean foundExported; private final String type; private Set<ManifestIntentFilter> intentFilters = null; private final String permission; // Target activity. private final String target; private final Integer missingIntentFilters; private final SootMethod registrationMethod; private final Unit registrationUnit; public ManifestComponent(String type, String name, boolean exported, boolean foundExported, String permission, String target, Integer missingIntentFilters, SootMethod registrationMethod, Unit registrationUnit) { this.type = type; this.exported = exported; this.foundExported = foundExported; this.name = name; this.permission = permission; this.target = target; this.missingIntentFilters = missingIntentFilters; this.registrationMethod = registrationMethod; this.registrationUnit = registrationUnit; } /** * @return the name */ public String getName() { return name; } /** * @return the exported */ public boolean isExported() { return exported; } /** * @return the type */ public String getType() { return type; } /** * @return the intentFilters */ public Set<ManifestIntentFilter> getIntentFilters() { return intentFilters; } public SootMethod getRegistrationMethod() { return registrationMethod; } public Unit getRegistrationUnit() { return registrationUnit; } /** * @param intentFilters the intentFilters to set */ public void setIntentFilters(Set<ManifestIntentFilter> intentFilters) { this.intentFilters = intentFilters; } public void addIntentFilters(Set<ManifestIntentFilter> intentFilters) { if (intentFilters != null) { if (this.intentFilters == null) { this.intentFilters = new HashSet<>(); } this.intentFilters.addAll(intentFilters); } } /** * Sets the intent filter and sets the exported flag accordingly. * * @param intentFilters The intent filters to set. */ public void setIntentFiltersAndExported(Set<ManifestIntentFilter> intentFilters) { this.intentFilters = intentFilters; if (!foundExported) { exported = (intentFilters != null && intentFilters.size() > 0); } } /** * @return the foundExported */ public boolean isFoundExported() { return foundExported; } /** * @return the permission */ public String getPermission() { return permission; } /** * @return the target */ public String getTarget() { return target; } /** * @return the missingIntentFilters */ public Integer missingIntentFilters() { return missingIntentFilters; } }
3,656
23.877551
93
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/manifest/ManifestData.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.manifest; public class ManifestData { private String scheme; private String host; private String port; private String path; private String mimeType; public ManifestData() { } public ManifestData(String scheme, String host, String port, String path, String mimeType) { this.scheme = scheme; this.host = host; this.port = port; this.path = path; this.mimeType = mimeType; } /** * @param scheme the scheme to set */ public void setScheme(String scheme) { this.scheme = scheme; } /** * @param host the host to set */ public void setHost(String host) { this.host = host; } /** * @param port the port to set */ public void setPort(String port) { this.port = port; } /** * @param path the path to set */ public void setPath(String path) { this.path = path; } /** * @param mimeType the mimeType to set */ public void setMimeType(String mimeType) { this.mimeType = mimeType; } /** * @return the scheme */ public String getScheme() { return scheme; } /** * @return the host */ public String getHost() { return host; } /** * @return the port */ public String getPort() { return port; } /** * @return the path */ public String getPath() { return path; } /** * @return the mimeType */ public String getMimeType() { return mimeType; } public String toString(String indent) { StringBuilder result = new StringBuilder(); result.append(indent + " scheme=" + scheme + ", host=" + host + ", port" + port + ", path" + path + ", MIME type=" + mimeType); return result.toString(); } @Override public String toString() { return toString(""); } }
2,536
19.966942
95
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/manifest/ManifestIntentFilter.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.manifest; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ManifestIntentFilter { private static final String ACTION_MAIN = "android.intent.action.MAIN"; // private static final String CATEGORY_LAUNCHER = "android.intent.category.LAUNCHER"; private final boolean alias; private final Integer priority; private Set<String> actions = null; private Set<String> categories = null; private List<ManifestData> data = null; public ManifestIntentFilter(boolean alias, Integer priority) { this.alias = alias; this.priority = priority; } public ManifestIntentFilter(Set<String> actions, Set<String> categories, boolean alias, List<ManifestData> data, Integer priority) { this.alias = alias; this.actions = actions; this.categories = categories; this.data = data; this.priority = priority; } /** * @return the alias */ public boolean isAlias() { return alias; } /** * @return the priority */ public Integer getPriority() { return priority; } /** * @return the actions */ public Set<String> getActions() { return actions; } /** * @param action the action to add */ public void addAction(String action) { if (this.actions == null) { this.actions = new HashSet<String>(); } this.actions.add(action); } /** * @return the categories */ public Set<String> getCategories() { return categories; } /** * @param categories the category to add */ public void addCategory(String category) { if (this.categories == null) { this.categories = new HashSet<String>(); } this.categories.add(category); } /** * @return the data */ public List<ManifestData> getData() { return this.data; } /** * @return the data */ public void addData(ManifestData manifestData) { if (this.data == null) { this.data = new ArrayList<>(); } this.data.add(manifestData); } /** * Specifies whether an intent filter corresponds to an activity which can be used as an app's * entry point. We do not necessarily consider applications which appear in the launcher. * * @return True if the intent filter describes an activity which can be used as an entry point. */ public boolean isEntryPoint() { return actions.contains(ACTION_MAIN)/* && categories.contains(CATEGORY_LAUNCHER) */; } public String toString(String indent) { StringBuilder result = new StringBuilder(indent); result.append("Intent filter:\n"); if (actions != null && actions.size() != 0) { result.append(indent); result.append(" Actions: "); result.append(actions); result.append("\n"); } if (categories != null && categories.size() != 0) { result.append(indent); result.append(" Categories: "); result.append(categories); result.append("\n"); } if (data != null && data.size() != 0) { result.append(indent); result.append(" Data: \n"); for (ManifestData manifestData : data) { result.append(manifestData.toString(indent + " ") + "\n"); } } return result.toString(); } @Override public String toString() { return toString(""); } }
4,071
25.270968
97
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/manifest/ManifestProviderComponent.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.manifest; import java.util.Set; public class ManifestProviderComponent extends ManifestComponent { private final String readPermission; private final String writePermission; private final Set<String> authorities; private final boolean grantUriPermissions; ManifestProviderComponent(String type, String name, boolean exported, boolean foundExported, String readPermission, String writePermission, Set<String> authorities, boolean grantUriPermissions) { super(type, name, exported, foundExported, "", null, null, null, null); this.readPermission = readPermission; this.writePermission = writePermission; this.authorities = authorities; this.grantUriPermissions = grantUriPermissions; } public String getReadPermission() { return readPermission; } public String getWritePermission() { return writePermission; } public Set<String> getAuthorities() { return authorities; } public boolean getGrantUriPermissions() { return grantUriPermissions; } }
1,792
30.45614
94
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/manifest/ManifestPullParser.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.manifest; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import edu.psu.cse.siis.ic3.Ic3Data; import edu.psu.cse.siis.ic3.Ic3Data.Application.Builder; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component.ComponentKind; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component.IntentFilter; import edu.psu.cse.siis.ic3.Ic3Data.Attribute; import edu.psu.cse.siis.ic3.Ic3Data.AttributeKind; import edu.psu.cse.siis.ic3.db.Constants; import edu.psu.cse.siis.ic3.db.SQLConnection; import edu.psu.cse.siis.ic3.manifest.binary.AXmlResourceParser; public class ManifestPullParser { private static final String MANIFEST = "manifest"; private static final String MANIFEST_FILE_NAME = "AndroidManifest.xml"; private static final String ACTIVITY = "activity"; private static final String ACTIVITY_ALIAS = "activity-alias"; private static final String SERVICE = "service"; private static final String PROVIDER = "provider"; private static final String AUTHORITIES = "authorities"; private static final String READ_PERMISSION = "readPermissions"; private static final String WRITE_PERMISSION = "writePermission"; private static final String RECEIVER = "receiver"; private static final String APPLICATION = "application"; private static final String NAMESPACE = "http://schemas.android.com/apk/res/android"; // private static final String ENABLED = "android:enabled"; private static final String NAME = "name"; private static final String INTENT_FILTER = "intent-filter"; private static final String ACTION = "action"; private static final String CATEGORY = "category"; private static final String MIME_TYPE = "mimeType"; private static final String PACKAGE = "package"; private static final String DATA = "data"; private static final String FALSE = "false"; private static final String VERSION = "versionCode"; private static final String PERMISSION = "permission"; private static final String EXPORTED = "exported"; private static final String TRUE = "true"; private static final String USES_PERMISSION = "uses-permission"; private static final String PROTECTION_LEVEL = "protectionLevel"; private static final String TARGET_ACTIVITY = "targetActivity"; private static final String SCHEME = "scheme"; private static final String HOST = "host"; private static final String PORT = "port"; private static final String PATH = "path"; private static final String PATH_PATTERN = "pathPattern"; private static final String PATH_PREFIX = "pathPrefix"; private static final String GRANT_URI_PERMISSIONS = "grantUriPermissions"; private static final String PRIORITY = "priority"; private static final String NORMAL = "normal"; private static final String DANGEROUS = "dangerous"; private static final String SIGNATURE = "signature"; private static final String SIGNATURE_OR_SYSTEM = "signatureOrSytem"; private String applicationName; private String packageName; private static final String[] levelValueToShortString = { Constants.PermissionLevel.NORMAL_SHORT, Constants.PermissionLevel.DANGEROUS_SHORT, Constants.PermissionLevel.SIGNATURE_SHORT, Constants.PermissionLevel.SIGNATURE_OR_SYSTEM_SHORT }; private static Map<String, Integer> tagDepthMap = null; // map a content provider to one or more authorities // private final Map<String, Set<String>> providersAuthorities = new HashMap<String, // Set<String>>(); // private final Map<String, Set<String>> providersRPermission = new HashMap<String, // Set<String>>(); // private final Map<String, Set<String>> providersWPermission = new HashMap<String, // Set<String>>(); private final List<ManifestComponent> activities = new ArrayList<ManifestComponent>(); private final List<ManifestComponent> activityAliases = new ArrayList<ManifestComponent>(); private final List<ManifestComponent> services = new ArrayList<ManifestComponent>(); private final List<ManifestComponent> receivers = new ArrayList<ManifestComponent>(); private final List<ManifestComponent> providers = new ArrayList<ManifestComponent>(); private int version = -1; private ManifestComponent currentComponent = null; private Set<ManifestIntentFilter> currentIntentFilters = null; private ManifestIntentFilter currentIntentFilter = null; private String skipToEndTag = null; private String applicationPermission = null; private final Set<String> usesPermissions = new HashSet<>(); private Map<String, String> permissions = new HashMap<String, String>(); private final Set<String> entryPointClasses = new HashSet<>(); public List<ManifestComponent> getActivities() { return activities; } public List<ManifestComponent> getActivityAliases() { return activityAliases; } public List<ManifestComponent> getServices() { return services; } public List<ManifestComponent> getReceivers() { return receivers; } public List<ManifestComponent> getProviders() { return providers; } public List<String> getComponents() { List<String> componentNames = new ArrayList<>(); addComponentNamesToList(activities, componentNames); addComponentNamesToList(services, componentNames); addComponentNamesToList(receivers, componentNames); addComponentNamesToList(providers, componentNames); return componentNames; } private void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getApplicationName() { return applicationName; } private void setPackageName(String packageName) { this.packageName = packageName; } public String getPackageName() { return packageName; } public Set<String> getEntryPointClasses() { return entryPointClasses; } private void addComponentNamesToList(List<ManifestComponent> components, List<String> output) { for (ManifestComponent manifestComponent : components) { output.add(manifestComponent.getName()); } } public void loadManifestFile(String manifest) { try { if (manifest.endsWith(".xml")) { loadClassesFromTextManifest(new FileInputStream(manifest)); } else { handleBinaryManifestFile(manifest); } } catch (FileNotFoundException e) { e.printStackTrace(); } } private void handleBinaryManifestFile(String apk) { try { ZipFile archive = new ZipFile(apk); ZipEntry manifestEntry = archive.getEntry(MANIFEST_FILE_NAME); if (manifestEntry == null) { archive.close(); throw new RuntimeException("No manifest file found in apk"); } loadClassesFromBinaryManifest(archive.getInputStream(manifestEntry)); archive.close(); } catch (IOException e) { throw new RuntimeException("Error while processing apk " + apk + ": " + e); } } protected void loadClassesFromBinaryManifest(InputStream manifestIS) { AXmlResourceParser aXmlResourceParser = new AXmlResourceParser(); aXmlResourceParser.open(manifestIS); try { parse(aXmlResourceParser); } catch (XmlPullParserException | IOException e) { e.printStackTrace(); throw new RuntimeException("Could not parse manifest file."); } } protected void loadClassesFromTextManifest(InputStream manifestIS) { try { XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory.newInstance(); xmlPullParserFactory.setNamespaceAware(true); XmlPullParser parser = xmlPullParserFactory.newPullParser(); parser.setInput(manifestIS, null); parse(parser); } catch (XmlPullParserException | IOException e) { e.printStackTrace(); throw new RuntimeException("Could not parse manifest file."); } } /** * Parse the manifest file. * * @param reader Input if text XML. * @param is Input if binary XML. * @throws IOException * @throws XmlPullParserException */ public void parse(XmlPullParser parser) throws XmlPullParserException, IOException { initializeTagDepthMap(); int depth = 0; int eventType = 0; eventType = parser.next(); boolean okayToContinue = true; while (okayToContinue && eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: okayToContinue = handleStartTag(parser, depth); ++depth; break; case XmlPullParser.END_TAG: okayToContinue = handleEndTag(parser); --depth; break; } eventType = parser.next(); } } public Map<String, Integer> writeToDb(boolean skipEntryPoints) { Map<String, Integer> componentIds = new HashMap<String, Integer>(); componentIds.putAll(SQLConnection.insert(getPackageName(), version, activities, usesPermissions, permissions, skipEntryPoints)); componentIds.putAll(SQLConnection.insert(getPackageName(), version, activityAliases, null, null, skipEntryPoints)); componentIds.putAll(SQLConnection.insert(getPackageName(), version, services, null, null, skipEntryPoints)); componentIds.putAll(SQLConnection.insert(getPackageName(), version, receivers, null, null, skipEntryPoints)); componentIds.putAll(SQLConnection.insert(getPackageName(), version, providers, null, null, skipEntryPoints)); return componentIds; } public boolean isComponent(String name) { return entryPointClasses.contains(name); } public Map<String, Ic3Data.Application.Component.Builder> populateProtobuf(Builder ic3Builder) { ic3Builder.setName(getPackageName()); ic3Builder.setVersion(version); for (Map.Entry<String, String> permission : permissions.entrySet()) { Ic3Data.Application.Permission protobufPermission = Ic3Data.Application.Permission.newBuilder().setName(permission.getKey()) .setLevel(stringToLevel(permission.getValue())).build(); ic3Builder.addPermissions(protobufPermission); } ic3Builder.addAllUsedPermissions(usesPermissions); Map<String, Ic3Data.Application.Component.Builder> componentNameToBuilderMap = new HashMap<>(); componentNameToBuilderMap.putAll(populateProtobufComponentBuilders(activities, ComponentKind.ACTIVITY)); componentNameToBuilderMap.putAll(populateProtobufComponentBuilders(services, ComponentKind.SERVICE)); componentNameToBuilderMap.putAll(populateProtobufComponentBuilders(receivers, ComponentKind.RECEIVER)); componentNameToBuilderMap.putAll(populateProtobufComponentBuilders(providers, ComponentKind.PROVIDER)); return componentNameToBuilderMap; } private Map<String, Component.Builder> populateProtobufComponentBuilders( List<ManifestComponent> components, ComponentKind componentKind) { Map<String, Component.Builder> componentNameToBuilderMap = new HashMap<>(); for (ManifestComponent manifestComponent : components) { componentNameToBuilderMap.put(manifestComponent.getName(), makeProtobufComponentBuilder(manifestComponent, componentKind)); } return componentNameToBuilderMap; } public static Component.Builder makeProtobufComponentBuilder(ManifestComponent manifestComponent, ComponentKind componentKind) { Component.Builder componentBuilder = Component.newBuilder(); componentBuilder.setName(manifestComponent.getName()); componentBuilder.setKind(componentKind); componentBuilder.setExported(manifestComponent.isExported()); if (manifestComponent.getPermission() != null) { componentBuilder.setPermission(manifestComponent.getPermission()); } if (manifestComponent.missingIntentFilters() != null) { componentBuilder.setMissing(manifestComponent.missingIntentFilters()); } if (manifestComponent.getIntentFilters() != null) { for (ManifestIntentFilter filter : manifestComponent.getIntentFilters()) { IntentFilter.Builder filterBuilder = IntentFilter.newBuilder(); if (filter.getPriority() != null) { filterBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.PRIORITY) .addIntValue(filter.getPriority())); } Set<String> value = filter.getActions(); if (value != null) { if (value.contains(null)) { value.remove(null); value.add(edu.psu.cse.siis.coal.Constants.NULL_STRING); } filterBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.ACTION) .addAllValue(value)); } value = filter.getCategories(); if (value != null) { if (value.contains(null)) { value.remove(null); value.add(edu.psu.cse.siis.coal.Constants.NULL_STRING); } filterBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.CATEGORY) .addAllValue(value)); } if (filter.getData() != null) { for (ManifestData data : filter.getData()) { if (data.getHost() != null) { filterBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.HOST) .addValue(data.getHost())); } if (data.getMimeType() != null) { // String[] typeParts = data.getMimeType().split("/"); // String type; // String subtype; // if (typeParts.length == 2) { // type = typeParts[0]; // subtype = typeParts[1]; // } else { // type = Constants.ANY_STRING; // subtype = Constants.ANY_STRING; // } filterBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.TYPE) .addValue(data.getMimeType())); // filterBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.SUBTYPE) // .addValue(subtype)); } if (data.getPath() != null) { filterBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.PATH) .addValue(data.getPath())); } if (data.getPort() != null) { filterBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.PORT) .addValue(data.getPort())); } if (data.getScheme() != null) { filterBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.SCHEME) .addValue(data.getScheme())); } } } componentBuilder.addIntentFilters(filterBuilder); } } return componentBuilder; } private Ic3Data.Application.Permission.Level stringToLevel(String levelString) { if (levelString.equalsIgnoreCase(Constants.PermissionLevel.NORMAL_SHORT)) { return Ic3Data.Application.Permission.Level.NORMAL; } else if (levelString.equalsIgnoreCase(Constants.PermissionLevel.DANGEROUS_SHORT)) { return Ic3Data.Application.Permission.Level.DANGEROUS; } else if (levelString.equalsIgnoreCase(Constants.PermissionLevel.SIGNATURE_SHORT)) { return Ic3Data.Application.Permission.Level.SIGNATURE; } else if (levelString.equalsIgnoreCase(Constants.PermissionLevel.SIGNATURE_OR_SYSTEM_SHORT)) { return Ic3Data.Application.Permission.Level.SIGNATURE_OR_SYSTEM; } else { throw new RuntimeException("Unknown permission level: " + levelString); } } @Override public String toString() { StringBuilder result = new StringBuilder("Manifest file for "); result.append(getPackageName()); if (version != -1) { result.append(" version ").append(version); } result.append("\n Activities:\n"); componentMapToString(activities, result); result.append("\n Activity Aliases:\n"); componentMapToString(activityAliases, result); result.append(" Services:\n"); componentMapToString(services, result); result.append(" Receivers:\n"); componentMapToString(receivers, result); result.append(" Providers:\n"); componentMapToString(providers, result); return result.toString(); } private void componentMapToString(List<ManifestComponent> components, StringBuilder out) { for (ManifestComponent component : components) { out.append(" ").append(component.getName()).append("\n"); if (component.getIntentFilters() != null) { for (ManifestIntentFilter manifestIntentFilter : component.getIntentFilters()) { out.append(manifestIntentFilter.toString(" ")); } } if (component instanceof ManifestProviderComponent) { ManifestProviderComponent provider = (ManifestProviderComponent) component; for (String authority : provider.getAuthorities()) { out.append(" authority: " + authority + "\n"); } String readPermission = provider.getReadPermission(); String writePermission = provider.getWritePermission(); if (readPermission != null && !readPermission.equals("")) { out.append(" read permission: " + readPermission + "\n"); } if (writePermission != null && !writePermission.equals("")) { out.append(" write permission: " + writePermission + "\n"); } } } } private boolean handleEndTag(XmlPullParser parser) { String tagName = parser.getName(); if (skipToEndTag != null) { if (skipToEndTag.equals(tagName)) { skipToEndTag = null; } return true; } if (tagName.equals(ACTIVITY)) { return handleActivityEnd(parser); } if (tagName.equals(ACTIVITY_ALIAS)) { return handleActivityAliasEnd(parser); } if (tagName.equals(SERVICE)) { return handleServiceEnd(parser); } if (tagName.equals(RECEIVER)) { return handleReceiverEnd(parser); } if (tagName.equals(INTENT_FILTER)) { return handleIntentFilterEnd(parser); } if (tagName.equals(PROVIDER)) { return handleProviderEnd(parser); } return true; } private void initializeTagDepthMap() { if (tagDepthMap == null) { tagDepthMap = new HashMap<String, Integer>(); tagDepthMap.put(MANIFEST, 0); tagDepthMap.put(USES_PERMISSION, 1); tagDepthMap.put(PERMISSION, 1); tagDepthMap.put(APPLICATION, 1); tagDepthMap.put(ACTIVITY, 2); tagDepthMap.put(SERVICE, 2); tagDepthMap.put(RECEIVER, 2); tagDepthMap.put(INTENT_FILTER, 3); tagDepthMap.put(ACTION, 4); tagDepthMap.put(CATEGORY, 4); tagDepthMap.put(DATA, 4); tagDepthMap = Collections.unmodifiableMap(tagDepthMap); } } private boolean handleStartTag(XmlPullParser parser, int depth) { if (skipToEndTag != null) { return true; } String tagName = parser.getName(); if (!checkDepth(tagName, depth)) { return true; } if (tagName.equals(ACTIVITY)) { return handleActivityStart(parser); } if (tagName.equals(ACTIVITY_ALIAS)) { return handleActivityAliasStart(parser); } if (tagName.equals(SERVICE)) { return handleServiceStart(parser); } if (tagName.equals(RECEIVER)) { return handleReceiverStart(parser); } if (tagName.equals(INTENT_FILTER)) { return handleIntentFilterStart(parser); } if (tagName.equals(ACTION)) { return handleActionStart(parser); } if (tagName.equals(CATEGORY)) { return handleCategoryStart(parser); } if (tagName.equals(MANIFEST)) { return handleManifestStart(parser); } if (tagName.equals(APPLICATION)) { return handleApplicationStart(parser); } if (tagName.equals(USES_PERMISSION)) { return handleUsesPermissionStart(parser); } if (tagName.equals(PERMISSION)) { return handlePermissionStart(parser); } if (tagName.equals(DATA)) { return handleDataStart(parser); } if (tagName.equals(PROVIDER)) { return handleProviderStart(parser); } return true; } private boolean handleIntentFilterStart(XmlPullParser parser) { Integer priority = null; String priorityString = parser.getAttributeValue(NAMESPACE, PRIORITY); if (priorityString != null && priorityString.length() != 0) { try { priority = Integer.valueOf(priorityString); } catch (NumberFormatException exception) { System.err.println("Bad priority: " + priorityString); } } currentIntentFilter = new ManifestIntentFilter(false, priority); return true; } private boolean handleIntentFilterEnd(XmlPullParser parser) { if (currentIntentFilters == null) { currentIntentFilters = new HashSet<ManifestIntentFilter>(); } currentIntentFilters.add(currentIntentFilter); currentIntentFilter = null; return true; } private boolean handleActivityStart(XmlPullParser parser) { return handleComponentStart(parser, ACTIVITY, Constants.ComponentShortType.ACTIVITY); } private boolean handleActivityEnd(XmlPullParser parser) { return handleComponentEnd(parser, activities); } private boolean handleActivityAliasStart(XmlPullParser parser) { return handleComponentStart(parser, ACTIVITY_ALIAS, Constants.ComponentShortType.ACTIVITY); } private boolean handleActivityAliasEnd(XmlPullParser parser) { return handleComponentEnd(parser, activityAliases); } private boolean handleServiceStart(XmlPullParser parser) { return handleComponentStart(parser, SERVICE, Constants.ComponentShortType.SERVICE); } private boolean handleServiceEnd(XmlPullParser parser) { return handleComponentEnd(parser, services); } private boolean handleReceiverStart(XmlPullParser parser) { return handleComponentStart(parser, RECEIVER, Constants.ComponentShortType.RECEIVER); } private boolean handleReceiverEnd(XmlPullParser parser) { return handleComponentEnd(parser, receivers); } private boolean handleComponentStart(XmlPullParser parser, String endTag, String componentType) { String name = null; String targetActivity = null; boolean isExported = false; boolean foundExported = false; String permission = null; for (int i = 0; i < parser.getAttributeCount(); ++i) { if (!parser.getAttributeNamespace(i).equals(NAMESPACE)) { continue; } String attributeName = parser.getAttributeName(i); if (attributeName.equals(NAME)) { name = parser.getAttributeValue(i); } else if (attributeName.equals(EXPORTED)) { String value = parser.getAttributeValue(i); if (value.equals(TRUE)) { isExported = true; foundExported = true; } else if (value.equals(FALSE)) { foundExported = true; } } else if (attributeName.equals(PERMISSION)) { permission = parser.getAttributeValue(i); } else if (attributeName.equals(TARGET_ACTIVITY)) { targetActivity = parser.getAttributeValue(i); } } if (name == null || (targetActivity != null && !entryPointClasses .contains(canonicalizeComponentName(targetActivity)))) { skipToEndTag = endTag; return true; } if (permission == null) { permission = applicationPermission; } currentComponent = new ManifestComponent(componentType, canonicalizeComponentName(name), isExported, foundExported, permission, targetActivity, null, null, null); return true; } private boolean handleComponentEnd(XmlPullParser parser, List<ManifestComponent> componentSet) { currentComponent.setIntentFiltersAndExported(currentIntentFilters); entryPointClasses.add(currentComponent.getName()); componentSet.add(currentComponent); currentComponent = null; currentIntentFilters = null; return true; } private boolean handleApplicationStart(XmlPullParser parser) { for (int i = 0; i < parser.getAttributeCount(); ++i) { if (!parser.getAttributeNamespace(i).equals(NAMESPACE)) { continue; } // The enabled setting can be changed in the code using the PackageManager class. if (parser.getAttributeName(i).equals(NAME)) { setApplicationName(parser.getAttributeValue(i)); } else if (parser.getAttributeName(i).equals(PERMISSION)) { applicationPermission = parser.getAttributeValue(i); } } return true; } private boolean handleUsesPermissionStart(XmlPullParser parser) { String permission = parser.getAttributeValue(NAMESPACE, NAME); if (permission != null) { usesPermissions.add(permission); } return true; } private boolean handlePermissionStart(XmlPullParser parser) { String permission = parser.getAttributeValue(NAMESPACE, NAME); String protectionLevel = parser.getAttributeValue(NAMESPACE, PROTECTION_LEVEL); protectionLevel = transformProtectionLevel(protectionLevel); if (permission != null) { if (permissions == null) { permissions = new HashMap<String, String>(); } permissions.put(permission, protectionLevel); } return true; } /** * Transform the protection level to something appropriate for the database. * * The protection level is stored in two different ways. In a binary manifest, it is an integer. * In a text manifest, it is the string designation of the protection level. * * @param protectionLevel The protection level found in the manifest. * @return A string representation for the protection level appropriate for the database. */ private String transformProtectionLevel(String protectionLevel) { if (protectionLevel == null || protectionLevel.equals("") || NORMAL.equalsIgnoreCase(protectionLevel)) { return Constants.PermissionLevel.NORMAL_SHORT; } else if (DANGEROUS.equalsIgnoreCase(protectionLevel)) { return Constants.PermissionLevel.DANGEROUS_SHORT; } else if (SIGNATURE.equalsIgnoreCase(protectionLevel)) { return Constants.PermissionLevel.SIGNATURE_SHORT; } else if (SIGNATURE_OR_SYSTEM.equalsIgnoreCase(protectionLevel)) { return Constants.PermissionLevel.SIGNATURE_OR_SYSTEM_SHORT; } else { // We are dealing with a binary manifest file. if (protectionLevel.startsWith("0x")) { // Even if hexadecimal, we still don't care about the radix, since these only go up // to 3. protectionLevel = protectionLevel.substring(2); } int level = Integer.parseInt(protectionLevel); return levelValueToShortString[level]; } } private boolean handleActionStart(XmlPullParser parser) { if (currentIntentFilter != null) { currentIntentFilter.addAction(parser.getAttributeValue(NAMESPACE, NAME)); } return true; } private boolean handleCategoryStart(XmlPullParser parser) { if (currentIntentFilter != null) { currentIntentFilter.addCategory(parser.getAttributeValue(NAMESPACE, NAME)); } return true; } private boolean handleDataStart(XmlPullParser parser) { if (currentIntentFilter != null) { ManifestData manifestData = new ManifestData(); for (int i = 0; i < parser.getAttributeCount(); ++i) { if (!parser.getAttributeNamespace(i).equals(NAMESPACE)) { continue; } String attributeName = parser.getAttributeName(i); String attributeValue = parser.getAttributeValue(i); if (attributeName.equals(MIME_TYPE)) { manifestData.setMimeType(attributeValue); } else if (attributeName.equals(SCHEME)) { manifestData.setScheme(attributeValue); } else if (attributeName.equals(HOST)) { manifestData.setHost(attributeValue); } else if (attributeName.equals(PORT)) { manifestData.setPort(attributeValue); } else if (attributeName.equals(PATH)) { manifestData.setPath(attributeValue); } else if (attributeName.equals(PATH_PATTERN)) { manifestData.setPath(attributeValue); } else if (attributeName.equals(PATH_PREFIX)) { manifestData.setPath(String.format("%s(.*)", attributeValue)); } } currentIntentFilter.addData(manifestData); } return true; } private String canonicalizeComponentName(String name) { if (name.length() == 0) { throw new RuntimeException("Component should have non-empty name."); } else if (!name.contains(".")) { // The non-official rule is that we also prefix the name with the package when // the component name does not contain any dot. // (http://stackoverflow.com/questions/3608017/activity-name-in-androidmanifest-xml) name = getPackageName() + "." + name; } else if (name.charAt(0) == '.') { // The official rule is to prefix the name with the package when the component // name starts with a dot. // (http://developer.android.com/guide/topics/manifest/activity-element.html#nm) name = getPackageName() + name; } // Found a case where there was a '/' instead of a '.'. return name.replace('/', '.'); } private boolean handleManifestStart(XmlPullParser parser) { for (int i = 0; i < parser.getAttributeCount(); ++i) { String attributeName = parser.getAttributeName(i); if (attributeName.equals(PACKAGE)) { // No namespace requirement. setPackageName(parser.getAttributeValue(i)); } else if (parser.getAttributeNamespace(i).equals(NAMESPACE) && attributeName.equals(VERSION)) { version = Integer.parseInt(parser.getAttributeValue(i)); } } if (getPackageName() != null) { return true; } else { return false; } } private boolean handleProviderStart(XmlPullParser parser) { boolean r = handleComponentStart(parser, PROVIDER, Constants.ComponentShortType.PROVIDER); String readPermission = currentComponent.getPermission(); String writePermission = currentComponent.getPermission(); Set<String> authorities = new HashSet<String>(); boolean grantUriPermissions = false; for (int i = 0; i < parser.getAttributeCount(); ++i) { if (!parser.getAttributeNamespace(i).equals(NAMESPACE)) { continue; } String attributeName = parser.getAttributeName(i); // permissions // Note: readPermission and writePermission attributes take precedence over // permission attribute // (http://developer.android.com/guide/topics/manifest/provider-element.html). if (attributeName.equals(READ_PERMISSION)) { readPermission = parser.getAttributeValue(i); } else if (attributeName.equals(WRITE_PERMISSION)) { writePermission = parser.getAttributeValue(i); } else if (attributeName.equals(AUTHORITIES)) { // the "AUTHORITIES" attribute contains a list of authorities separated by semicolons. String s = parser.getAttributeValue(i); for (String a : s.split(";")) { authorities.add(a); } } else if (attributeName.equals(GRANT_URI_PERMISSIONS)) { grantUriPermissions = !parser.getAttributeValue(i).equals("false"); } } currentComponent = new ManifestProviderComponent(currentComponent.getType(), currentComponent.getName(), currentComponent.isExported(), currentComponent.isFoundExported(), readPermission, writePermission, authorities, grantUriPermissions); return r; } private boolean handleProviderEnd(XmlPullParser parser) { return handleComponentEnd(parser, providers); } private boolean checkDepth(String tagName, int depth) { Integer expectedDepth = tagDepthMap.get(tagName); if (expectedDepth != null && expectedDepth != depth) { skipToEndTag = tagName; System.err.println("Warning: malformed Manifest file: " + tagName + " at depth " + depth); } return true; } }
33,123
36.428249
102
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/manifest/binary/AXmlResourceParser.java
/** * Copyright 2011 Ryszard Wi??????????????????niewski <brut.alll@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.manifest.binary; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; /** * @author Ryszard Wi??????????????????niewski <brut.alll@gmail.com> * @author Dmitry Skiba * * Binary xml files parser. * * Parser has only two states: (1) Operational state, which parser obtains after first * successful call to next() and retains until open(), close(), or failed call to next(). * (2) Closed state, which parser obtains after open(), close(), or failed call to next(). * In this state methods return invalid values or throw exceptions. * * TODO: * check all methods in closed state * */ public class AXmlResourceParser implements XmlPullParser { public AXmlResourceParser() { resetEventInfo(); } public AXmlResourceParser(InputStream stream) { this(); open(stream); } // public AndrolibException getFirstError() { // return mFirstError; // } // public ResAttrDecoder getAttrDecoder() { // return mAttrDecoder; // } // public void setAttrDecoder(ResAttrDecoder attrDecoder) { // mAttrDecoder = attrDecoder; // } public void open(InputStream stream) { close(); if (stream != null) { m_reader = new ExtDataInput(new LEDataInputStream(stream)); } } public void close() { if (!m_operational) { return; } m_operational = false; // m_reader.close(); m_reader = null; m_strings = null; m_resourceIDs = null; m_namespaces.reset(); resetEventInfo(); } // ///////////////////////////////// iteration @Override public int next() throws XmlPullParserException, IOException { if (m_reader == null) { throw new XmlPullParserException("Parser is not opened.", this, null); } try { doNext(); return m_event; } catch (IOException e) { close(); throw e; } } @Override public int nextToken() throws XmlPullParserException, IOException { return next(); } @Override public int nextTag() throws XmlPullParserException, IOException { int eventType = next(); if (eventType == TEXT && isWhitespace()) { eventType = next(); } if (eventType != START_TAG && eventType != END_TAG) { throw new XmlPullParserException("Expected start or end tag.", this, null); } return eventType; } @Override public String nextText() throws XmlPullParserException, IOException { if (getEventType() != START_TAG) { throw new XmlPullParserException("Parser must be on START_TAG to read next text.", this, null); } int eventType = next(); if (eventType == TEXT) { String result = getText(); eventType = next(); if (eventType != END_TAG) { throw new XmlPullParserException("Event TEXT must be immediately followed by END_TAG.", this, null); } return result; } else if (eventType == END_TAG) { return ""; } else { throw new XmlPullParserException("Parser must be on START_TAG or TEXT to read text.", this, null); } } @Override public void require(int type, String namespace, String name) throws XmlPullParserException, IOException { if (type != getEventType() || (namespace != null && !namespace.equals(getNamespace())) || (name != null && !name.equals(getName()))) { throw new XmlPullParserException(TYPES[type] + " is expected.", this, null); } } @Override public int getDepth() { return m_namespaces.getDepth() - 1; } @Override public int getEventType() throws XmlPullParserException { return m_event; } @Override public int getLineNumber() { return m_lineNumber; } @Override public String getName() { if (m_name == -1 || (m_event != START_TAG && m_event != END_TAG)) { return null; } return m_strings.getString(m_name); } @Override public String getText() { if (m_name == -1 || m_event != TEXT) { return null; } return m_strings.getString(m_name); } @Override public char[] getTextCharacters(int[] holderForStartAndLength) { String text = getText(); if (text == null) { return null; } holderForStartAndLength[0] = 0; holderForStartAndLength[1] = text.length(); char[] chars = new char[text.length()]; text.getChars(0, text.length(), chars, 0); return chars; } @Override public String getNamespace() { return m_strings.getString(m_namespaceUri); } @Override public String getPrefix() { int prefix = m_namespaces.findPrefix(m_namespaceUri); return m_strings.getString(prefix); } @Override public String getPositionDescription() { return "XML line #" + getLineNumber(); } @Override public int getNamespaceCount(int depth) throws XmlPullParserException { return m_namespaces.getAccumulatedCount(depth); } @Override public String getNamespacePrefix(int pos) throws XmlPullParserException { int prefix = m_namespaces.getPrefix(pos); return m_strings.getString(prefix); } @Override public String getNamespaceUri(int pos) throws XmlPullParserException { int uri = m_namespaces.getUri(pos); return m_strings.getString(uri); } // ///////////////////////////////// attributes public String getClassAttribute() { if (m_classAttribute == -1) { return null; } int offset = getAttributeOffset(m_classAttribute); int value = m_attributes[offset + ATTRIBUTE_IX_VALUE_STRING]; return m_strings.getString(value); } public String getIdAttribute() { if (m_idAttribute == -1) { return null; } int offset = getAttributeOffset(m_idAttribute); int value = m_attributes[offset + ATTRIBUTE_IX_VALUE_STRING]; return m_strings.getString(value); } public int getIdAttributeResourceValue(int defaultValue) { if (m_idAttribute == -1) { return defaultValue; } int offset = getAttributeOffset(m_idAttribute); int valueType = m_attributes[offset + ATTRIBUTE_IX_VALUE_TYPE]; if (valueType != TypedValue.TYPE_REFERENCE) { return defaultValue; } return m_attributes[offset + ATTRIBUTE_IX_VALUE_DATA]; } public int getStyleAttribute() { if (m_styleAttribute == -1) { return 0; } int offset = getAttributeOffset(m_styleAttribute); return m_attributes[offset + ATTRIBUTE_IX_VALUE_DATA]; } @Override public int getAttributeCount() { if (m_event != START_TAG) { return -1; } return m_attributes.length / ATTRIBUTE_LENGHT; } @Override public String getAttributeNamespace(int index) { int offset = getAttributeOffset(index); int namespace = m_attributes[offset + ATTRIBUTE_IX_NAMESPACE_URI]; if (namespace == -1) { return ""; } return m_strings.getString(namespace); } @Override public String getAttributePrefix(int index) { int offset = getAttributeOffset(index); int uri = m_attributes[offset + ATTRIBUTE_IX_NAMESPACE_URI]; int prefix = m_namespaces.findPrefix(uri); if (prefix == -1) { return ""; } return m_strings.getString(prefix); } @Override public String getAttributeName(int index) { int offset = getAttributeOffset(index); int name = m_attributes[offset + ATTRIBUTE_IX_NAME]; if (name == -1) { return ""; } return m_strings.getString(name); } public int getAttributeNameResource(int index) { int offset = getAttributeOffset(index); int name = m_attributes[offset + ATTRIBUTE_IX_NAME]; if (m_resourceIDs == null || name < 0 || name >= m_resourceIDs.length) { return 0; } return m_resourceIDs[name]; } // @Override public int getAttributeValueType(int index) { int offset = getAttributeOffset(index); return m_attributes[offset + ATTRIBUTE_IX_VALUE_TYPE]; } // @Override public int getAttributeValueData(int index) { int offset = getAttributeOffset(index); return m_attributes[offset + ATTRIBUTE_IX_VALUE_DATA]; } @Override public String getAttributeValue(int index) { int offset = getAttributeOffset(index); int valueType = m_attributes[offset + ATTRIBUTE_IX_VALUE_TYPE]; int valueData = m_attributes[offset + ATTRIBUTE_IX_VALUE_DATA]; int valueRaw = m_attributes[offset + ATTRIBUTE_IX_VALUE_STRING]; // if (mAttrDecoder != null) { // try { // return mAttrDecoder.decode( // valueType, // valueData, // valueRaw == -1 ? null : ResXmlEncoders // .escapeXmlChars(m_strings.getString(valueRaw)), // getAttributeNameResource(index)); // } catch (AndrolibException ex) { // setFirstError(ex); // LOGGER.log(Level.WARNING, String.format( // "Could not decode attr value, using undecoded value " // + "instead: ns=%s, name=%s, value=0x%08x", // getAttributePrefix(index), getAttributeName(index), // valueData), ex); // } // } else { if (valueType == TypedValue.TYPE_STRING) { return ResXmlEncoders.escapeXmlChars(m_strings.getString(valueRaw)); } // } return TypedValue.coerceToString(valueType, valueData); } public boolean getAttributeBooleanValue(int index, boolean defaultValue) { return getAttributeIntValue(index, defaultValue ? 1 : 0) != 0; } public float getAttributeFloatValue(int index, float defaultValue) { int offset = getAttributeOffset(index); int valueType = m_attributes[offset + ATTRIBUTE_IX_VALUE_TYPE]; if (valueType == TypedValue.TYPE_FLOAT) { int valueData = m_attributes[offset + ATTRIBUTE_IX_VALUE_DATA]; return Float.intBitsToFloat(valueData); } return defaultValue; } public int getAttributeIntValue(int index, int defaultValue) { int offset = getAttributeOffset(index); int valueType = m_attributes[offset + ATTRIBUTE_IX_VALUE_TYPE]; if (valueType >= TypedValue.TYPE_FIRST_INT && valueType <= TypedValue.TYPE_LAST_INT) { return m_attributes[offset + ATTRIBUTE_IX_VALUE_DATA]; } return defaultValue; } public int getAttributeUnsignedIntValue(int index, int defaultValue) { return getAttributeIntValue(index, defaultValue); } public int getAttributeResourceValue(int index, int defaultValue) { int offset = getAttributeOffset(index); int valueType = m_attributes[offset + ATTRIBUTE_IX_VALUE_TYPE]; if (valueType == TypedValue.TYPE_REFERENCE) { return m_attributes[offset + ATTRIBUTE_IX_VALUE_DATA]; } return defaultValue; } @Override public String getAttributeValue(String namespace, String attribute) { int index = findAttribute(namespace, attribute); if (index == -1) { return ""; } return getAttributeValue(index); } public boolean getAttributeBooleanValue(String namespace, String attribute, boolean defaultValue) { int index = findAttribute(namespace, attribute); if (index == -1) { return defaultValue; } return getAttributeBooleanValue(index, defaultValue); } public float getAttributeFloatValue(String namespace, String attribute, float defaultValue) { int index = findAttribute(namespace, attribute); if (index == -1) { return defaultValue; } return getAttributeFloatValue(index, defaultValue); } public int getAttributeIntValue(String namespace, String attribute, int defaultValue) { int index = findAttribute(namespace, attribute); if (index == -1) { return defaultValue; } return getAttributeIntValue(index, defaultValue); } public int getAttributeUnsignedIntValue(String namespace, String attribute, int defaultValue) { int index = findAttribute(namespace, attribute); if (index == -1) { return defaultValue; } return getAttributeUnsignedIntValue(index, defaultValue); } public int getAttributeResourceValue(String namespace, String attribute, int defaultValue) { int index = findAttribute(namespace, attribute); if (index == -1) { return defaultValue; } return getAttributeResourceValue(index, defaultValue); } public int getAttributeListValue(int index, String[] options, int defaultValue) { // TODO implement return 0; } public int getAttributeListValue(String namespace, String attribute, String[] options, int defaultValue) { // TODO implement return 0; } @Override public String getAttributeType(int index) { return "CDATA"; } @Override public boolean isAttributeDefault(int index) { return false; } // ///////////////////////////////// dummies @Override public void setInput(InputStream stream, String inputEncoding) throws XmlPullParserException { open(stream); } @Override public void setInput(Reader reader) throws XmlPullParserException { throw new XmlPullParserException(E_NOT_SUPPORTED); } @Override public String getInputEncoding() { return null; } @Override public int getColumnNumber() { return -1; } @Override public boolean isEmptyElementTag() throws XmlPullParserException { return false; } @Override public boolean isWhitespace() throws XmlPullParserException { return false; } @Override public void defineEntityReplacementText(String entityName, String replacementText) throws XmlPullParserException { throw new XmlPullParserException(E_NOT_SUPPORTED); } @Override public String getNamespace(String prefix) { throw new RuntimeException(E_NOT_SUPPORTED); } @Override public Object getProperty(String name) { return null; } @Override public void setProperty(String name, Object value) throws XmlPullParserException { throw new XmlPullParserException(E_NOT_SUPPORTED); } @Override public boolean getFeature(String feature) { return false; } @Override public void setFeature(String name, boolean value) throws XmlPullParserException { throw new XmlPullParserException(E_NOT_SUPPORTED); } // /////////////////////////////////////////// implementation /** * Namespace stack, holds prefix+uri pairs, as well as depth information. All information is * stored in one int[] array. Array consists of depth frames: Data=DepthFrame*; * DepthFrame=Count+[Prefix+Uri]*+Count; Count='count of Prefix+Uri pairs'; Yes, count is stored * twice, to enable bottom-up traversal. increaseDepth adds depth frame, decreaseDepth removes it. * push/pop operations operate only in current depth frame. decreaseDepth removes any remaining * (not pop'ed) namespace pairs. findXXX methods search all depth frames starting from the last * namespace pair of current depth frame. All functions that operate with int, use -1 as 'invalid * value'. * * !! functions expect 'prefix'+'uri' pairs, not 'uri'+'prefix' !! * */ private static final class NamespaceStack { public NamespaceStack() { m_data = new int[32]; } public final void reset() { m_dataLength = 0; m_depth = 0; } public final int getCurrentCount() { if (m_dataLength == 0) { return 0; } int offset = m_dataLength - 1; return m_data[offset]; } public final int getAccumulatedCount(int depth) { if (m_dataLength == 0 || depth < 0) { return 0; } if (depth > m_depth) { depth = m_depth; } int accumulatedCount = 0; int offset = 0; for (; depth != 0; --depth) { int count = m_data[offset]; accumulatedCount += count; offset += (2 + count * 2); } return accumulatedCount; } public final void push(int prefix, int uri) { if (m_depth == 0) { increaseDepth(); } ensureDataCapacity(2); int offset = m_dataLength - 1; int count = m_data[offset]; m_data[offset - 1 - count * 2] = count + 1; m_data[offset] = prefix; m_data[offset + 1] = uri; m_data[offset + 2] = count + 1; m_dataLength += 2; } public final boolean pop() { if (m_dataLength == 0) { return false; } int offset = m_dataLength - 1; int count = m_data[offset]; if (count == 0) { return false; } count -= 1; offset -= 2; m_data[offset] = count; offset -= (1 + count * 2); m_data[offset] = count; m_dataLength -= 2; return true; } public final int getPrefix(int index) { return get(index, true); } public final int getUri(int index) { return get(index, false); } public final int findPrefix(int uri) { return find(uri, false); } public final int getDepth() { return m_depth; } public final void increaseDepth() { ensureDataCapacity(2); int offset = m_dataLength; m_data[offset] = 0; m_data[offset + 1] = 0; m_dataLength += 2; m_depth += 1; } public final void decreaseDepth() { if (m_dataLength == 0) { return; } int offset = m_dataLength - 1; int count = m_data[offset]; if ((offset - 1 - count * 2) == 0) { return; } m_dataLength -= 2 + count * 2; m_depth -= 1; } private void ensureDataCapacity(int capacity) { int available = (m_data.length - m_dataLength); if (available > capacity) { return; } int newLength = (m_data.length + available) * 2; int[] newData = new int[newLength]; System.arraycopy(m_data, 0, newData, 0, m_dataLength); m_data = newData; } private final int find(int prefixOrUri, boolean prefix) { if (m_dataLength == 0) { return -1; } int offset = m_dataLength - 1; for (int i = m_depth; i != 0; --i) { int count = m_data[offset]; offset -= 2; for (; count != 0; --count) { if (prefix) { if (m_data[offset] == prefixOrUri) { return m_data[offset + 1]; } } else { if (m_data[offset + 1] == prefixOrUri) { return m_data[offset]; } } offset -= 2; } } return -1; } private final int get(int index, boolean prefix) { if (m_dataLength == 0 || index < 0) { return -1; } int offset = 0; for (int i = m_depth; i != 0; --i) { int count = m_data[offset]; if (index >= count) { index -= count; offset += (2 + count * 2); continue; } offset += (1 + index * 2); if (!prefix) { offset += 1; } return m_data[offset]; } return -1; } private int[] m_data; private int m_dataLength; private int m_depth; } // ///////////////////////////////// package-visible // final void fetchAttributes(int[] styleableIDs,TypedArray result) { // result.resetIndices(); // if (m_attributes==null || m_resourceIDs==null) { // return; // } // boolean needStrings=false; // for (int i=0,e=styleableIDs.length;i!=e;++i) { // int id=styleableIDs[i]; // for (int o=0;o!=m_attributes.length;o+=ATTRIBUTE_LENGHT) { // int name=m_attributes[o+ATTRIBUTE_IX_NAME]; // if (name>=m_resourceIDs.length || // m_resourceIDs[name]!=id) // { // continue; // } // int valueType=m_attributes[o+ATTRIBUTE_IX_VALUE_TYPE]; // int valueData; // int assetCookie; // if (valueType==TypedValue.TYPE_STRING) { // valueData=m_attributes[o+ATTRIBUTE_IX_VALUE_STRING]; // assetCookie=-1; // needStrings=true; // } else { // valueData=m_attributes[o+ATTRIBUTE_IX_VALUE_DATA]; // assetCookie=0; // } // result.addValue(i,valueType,valueData,assetCookie,id,0); // } // } // if (needStrings) { // result.setStrings(m_strings); // } // } final StringBlock getStrings() { return m_strings; } // ///////////////////////////////// private final int getAttributeOffset(int index) { if (m_event != START_TAG) { throw new IndexOutOfBoundsException("Current event is not START_TAG."); } int offset = index * ATTRIBUTE_LENGHT; if (offset >= m_attributes.length) { throw new IndexOutOfBoundsException("Invalid attribute index (" + index + ")."); } return offset; } private final int findAttribute(String namespace, String attribute) { if (m_strings == null || attribute == null) { return -1; } int name = m_strings.find(attribute); if (name == -1) { return -1; } int uri = (namespace != null) ? m_strings.find(namespace) : -1; for (int o = 0; o != m_attributes.length; o += ATTRIBUTE_LENGHT) { if (name == m_attributes[o + ATTRIBUTE_IX_NAME] && (uri == -1 || uri == m_attributes[o + ATTRIBUTE_IX_NAMESPACE_URI])) { return o / ATTRIBUTE_LENGHT; } } return -1; } private final void resetEventInfo() { m_event = -1; m_lineNumber = -1; m_name = -1; m_namespaceUri = -1; m_attributes = null; m_idAttribute = -1; m_classAttribute = -1; m_styleAttribute = -1; } private final void doNext() throws IOException { // Delayed initialization. if (m_strings == null) { m_reader.skipCheckInt(CHUNK_AXML_FILE); /* * chunkSize */m_reader.skipInt(); m_strings = StringBlock.read(m_reader); m_namespaces.increaseDepth(); m_operational = true; } if (m_event == END_DOCUMENT) { return; } int event = m_event; resetEventInfo(); while (true) { if (m_decreaseDepth) { m_decreaseDepth = false; m_namespaces.decreaseDepth(); } // Fake END_DOCUMENT event. if (event == END_TAG && m_namespaces.getDepth() == 1 && m_namespaces.getCurrentCount() == 0) { m_event = END_DOCUMENT; break; } int chunkType; if (event == START_DOCUMENT) { // Fake event, see CHUNK_XML_START_TAG handler. chunkType = CHUNK_XML_START_TAG; } else { chunkType = m_reader.readInt(); } if (chunkType == CHUNK_RESOURCEIDS) { int chunkSize = m_reader.readInt(); if (chunkSize < 8 || (chunkSize % 4) != 0) { throw new IOException("Invalid resource ids size (" + chunkSize + ")."); } m_resourceIDs = m_reader.readIntArray(chunkSize / 4 - 2); continue; } if (chunkType < CHUNK_XML_FIRST || chunkType > CHUNK_XML_LAST) { throw new IOException("Invalid chunk type (" + chunkType + ")."); } // Fake START_DOCUMENT event. if (chunkType == CHUNK_XML_START_TAG && event == -1) { m_event = START_DOCUMENT; break; } // Common header. /* chunkSize */m_reader.skipInt(); int lineNumber = m_reader.readInt(); /* 0xFFFFFFFF */m_reader.skipInt(); if (chunkType == CHUNK_XML_START_NAMESPACE || chunkType == CHUNK_XML_END_NAMESPACE) { if (chunkType == CHUNK_XML_START_NAMESPACE) { int prefix = m_reader.readInt(); int uri = m_reader.readInt(); m_namespaces.push(prefix, uri); } else { /* prefix */m_reader.skipInt(); /* uri */m_reader.skipInt(); m_namespaces.pop(); } continue; } m_lineNumber = lineNumber; if (chunkType == CHUNK_XML_START_TAG) { m_namespaceUri = m_reader.readInt(); m_name = m_reader.readInt(); /* flags? */m_reader.skipInt(); int attributeCount = m_reader.readInt(); m_idAttribute = (attributeCount >>> 16) - 1; attributeCount &= 0xFFFF; m_classAttribute = m_reader.readInt(); m_styleAttribute = (m_classAttribute >>> 16) - 1; m_classAttribute = (m_classAttribute & 0xFFFF) - 1; m_attributes = m_reader.readIntArray(attributeCount * ATTRIBUTE_LENGHT); for (int i = ATTRIBUTE_IX_VALUE_TYPE; i < m_attributes.length;) { m_attributes[i] = (m_attributes[i] >>> 24); i += ATTRIBUTE_LENGHT; } m_namespaces.increaseDepth(); m_event = START_TAG; break; } if (chunkType == CHUNK_XML_END_TAG) { m_namespaceUri = m_reader.readInt(); m_name = m_reader.readInt(); m_event = END_TAG; m_decreaseDepth = true; break; } if (chunkType == CHUNK_XML_TEXT) { m_name = m_reader.readInt(); /* ? */m_reader.skipInt(); /* ? */m_reader.skipInt(); m_event = TEXT; break; } } } // ///////////////////////////////// data /* * All values are essentially indices, e.g. m_name is an index of name in m_strings. */ private ExtDataInput m_reader; // private ResAttrDecoder mAttrDecoder; // private AndrolibException mFirstError; private boolean m_operational = false; private StringBlock m_strings; private int[] m_resourceIDs; private NamespaceStack m_namespaces = new NamespaceStack(); private boolean m_decreaseDepth; private int m_event; private int m_lineNumber; private int m_name; private int m_namespaceUri; private int[] m_attributes; private int m_idAttribute; private int m_classAttribute; private int m_styleAttribute; private static final String E_NOT_SUPPORTED = "Method is not supported."; private static final int ATTRIBUTE_IX_NAMESPACE_URI = 0, ATTRIBUTE_IX_NAME = 1, ATTRIBUTE_IX_VALUE_STRING = 2, ATTRIBUTE_IX_VALUE_TYPE = 3, ATTRIBUTE_IX_VALUE_DATA = 4, ATTRIBUTE_LENGHT = 5; private static final int CHUNK_AXML_FILE = 0x00080003, CHUNK_RESOURCEIDS = 0x00080180, CHUNK_XML_FIRST = 0x00100100, CHUNK_XML_START_NAMESPACE = 0x00100100, CHUNK_XML_END_NAMESPACE = 0x00100101, CHUNK_XML_START_TAG = 0x00100102, CHUNK_XML_END_TAG = 0x00100103, CHUNK_XML_TEXT = 0x00100104, CHUNK_XML_LAST = 0x00100104; }
26,606
27.671336
101
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/manifest/binary/DataInputDelegate.java
/** * Copyright 2010 Ryszard Wi??????niewski <brut.alll@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.manifest.binary; import java.io.DataInput; import java.io.IOException; /** * @author Ryszard Wi??????niewski <brut.alll@gmail.com> */ abstract public class DataInputDelegate implements DataInput { protected final DataInput mDelegate; public DataInputDelegate(DataInput delegate) { this.mDelegate = delegate; } public int skipBytes(int n) throws IOException { return mDelegate.skipBytes(n); } public int readUnsignedShort() throws IOException { return mDelegate.readUnsignedShort(); } public int readUnsignedByte() throws IOException { return mDelegate.readUnsignedByte(); } public String readUTF() throws IOException { return mDelegate.readUTF(); } public short readShort() throws IOException { return mDelegate.readShort(); } public long readLong() throws IOException { return mDelegate.readLong(); } public String readLine() throws IOException { return mDelegate.readLine(); } public int readInt() throws IOException { return mDelegate.readInt(); } public void readFully(byte[] b, int off, int len) throws IOException { mDelegate.readFully(b, off, len); } public void readFully(byte[] b) throws IOException { mDelegate.readFully(b); } public float readFloat() throws IOException { return mDelegate.readFloat(); } public double readDouble() throws IOException { return mDelegate.readDouble(); } public char readChar() throws IOException { return mDelegate.readChar(); } public byte readByte() throws IOException { return mDelegate.readByte(); } public boolean readBoolean() throws IOException { return mDelegate.readBoolean(); } }
2,353
24.586957
76
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/manifest/binary/ExtDataInput.java
/** * Copyright 2010 Ryszard Wi??????niewski <brut.alll@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.manifest.binary; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; /** * @author Ryszard Wi??????niewski <brut.alll@gmail.com> */ public class ExtDataInput extends DataInputDelegate { public ExtDataInput(InputStream in) { this((DataInput) new DataInputStream(in)); } public ExtDataInput(DataInput delegate) { super(delegate); } public int[] readIntArray(int length) throws IOException { int[] array = new int[length]; for (int i = 0; i < length; i++) { array[i] = readInt(); } return array; } public void skipInt() throws IOException { skipBytes(4); } public void skipCheckInt(int expected) throws IOException { int got = readInt(); if (got != expected) { throw new IOException(String.format("Expected: 0x%08x, got: 0x%08x", expected, got)); } } public void skipCheckShort(short expected) throws IOException { short got = readShort(); if (got != expected) { throw new IOException(String.format("Expected: 0x%08x, got: 0x%08x", expected, got)); } } public void skipCheckByte(byte expected) throws IOException { byte got = readByte(); if (got != expected) { throw new IOException(String.format("Expected: 0x%08x, got: 0x%08x", expected, got)); } } public String readNulEndedString(int length, boolean fixed) throws IOException { StringBuilder string = new StringBuilder(16); while (length-- != 0) { short ch = readShort(); if (ch == 0) { break; } string.append((char) ch); } if (fixed) { skipBytes(length * 2); } return string.toString(); } }
2,370
26.894118
91
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/manifest/binary/LEDataInputStream.java
/* * @(#)LEDataInputStream.java * * Summary: Little-Endian version of DataInputStream. * * Copyright: (c) 1998-2010 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.1+ * * Created with: IntelliJ IDEA IDE. * * Version History: * 1.8 2007-05-24 */ package edu.psu.cse.siis.ic3.manifest.binary; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; /** * Little-Endian version of DataInputStream. * <p/> * Very similar to DataInputStream except it reads little-endian instead of big-endian binary data. * We can't extend DataInputStream directly since it has only final methods, though DataInputStream * itself is not final. This forces us implement LEDataInputStream with a DataInputStream object, * and use wrapper methods. * * @author Roedy Green, Canadian Mind Products * @version 1.8 2007-05-24 * @since 1998 */ public final class LEDataInputStream implements DataInput { // ------------------------------ CONSTANTS ------------------------------ /** * undisplayed copyright notice. * * @noinspection UnusedDeclaration */ @SuppressWarnings("unused") private static final String EMBEDDED_COPYRIGHT = "copyright (c) 1999-2010 Roedy Green, Canadian Mind Products, http://mindprod.com"; // ------------------------------ FIELDS ------------------------------ /** * to get at the big-Endian methods of a basic DataInputStream * * @noinspection WeakerAccess */ protected final DataInputStream dis; /** * to get at the a basic readBytes method. * * @noinspection WeakerAccess */ protected final InputStream is; /** * work array for buffering input. * * @noinspection WeakerAccess */ protected final byte[] work; // -------------------------- PUBLIC STATIC METHODS // -------------------------- /** * Note. This is a STATIC method! * * @param in stream to read UTF chars from (endian irrelevant) * * @return string from stream * @throws IOException if read fails. */ public static String readUTF(DataInput in) throws IOException { return DataInputStream.readUTF(in); } // -------------------------- PUBLIC INSTANCE METHODS // -------------------------- /** * constructor. * * @param in binary inputstream of little-endian data. */ public LEDataInputStream(InputStream in) { this.is = in; this.dis = new DataInputStream(in); work = new byte[8]; } /** * close. * * @throws IOException if close fails. */ public final void close() throws IOException { dis.close(); } /** * Read bytes. Watch out, read may return fewer bytes than requested. * * @param ba where the bytes go. * @param off offset in buffer, not offset in file. * @param len count of bytes to read. * * @return how many bytes read. * @throws IOException if read fails. */ public final int read(byte ba[], int off, int len) throws IOException { // For efficiency, we avoid one layer of wrapper return is.read(ba, off, len); } /** * read only a one-byte boolean. * * @return true or false. * @throws IOException if read fails. * @see java.io.DataInput#readBoolean() */ @Override public final boolean readBoolean() throws IOException { return dis.readBoolean(); } /** * read byte. * * @return the byte read. * @throws IOException if read fails. * @see java.io.DataInput#readByte() */ @Override public final byte readByte() throws IOException { return dis.readByte(); } /** * Read on char. like DataInputStream.readChar except little endian. * * @return little endian 16-bit unicode char from the stream. * @throws IOException if read fails. */ @Override public final char readChar() throws IOException { dis.readFully(work, 0, 2); return (char) ((work[1] & 0xff) << 8 | (work[0] & 0xff)); } /** * Read a double. like DataInputStream.readDouble except little endian. * * @return little endian IEEE double from the datastream. * @throws IOException */ @Override public final double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } /** * Read one float. Like DataInputStream.readFloat except little endian. * * @return little endian IEEE float from the datastream. * @throws IOException if read fails. */ @Override public final float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } /** * Read bytes until the array is filled. * * @see java.io.DataInput#readFully(byte[]) */ @Override public final void readFully(byte ba[]) throws IOException { dis.readFully(ba, 0, ba.length); } /** * Read bytes until the count is satisfied. * * @throws IOException if read fails. * @see java.io.DataInput#readFully(byte[],int,int) */ @Override public final void readFully(byte ba[], int off, int len) throws IOException { dis.readFully(ba, off, len); } /** * Read an int, 32-bits. Like DataInputStream.readInt except little endian. * * @return little-endian binary int from the datastream * @throws IOException if read fails. */ @Override public final int readInt() throws IOException { dis.readFully(work, 0, 4); return (work[3]) << 24 | (work[2] & 0xff) << 16 | (work[1] & 0xff) << 8 | (work[0] & 0xff); } /** * Read a line. * * @return a rough approximation of the 8-bit stream as a 16-bit unicode string * @throws IOException * @noinspection deprecation * @deprecated This method does not properly convert bytes to characters. Use a Reader instead * with a little-endian encoding. */ @Deprecated @Override public final String readLine() throws IOException { return dis.readLine(); } /** * read a long, 64-bits. Like DataInputStream.readLong except little endian. * * @return little-endian binary long from the datastream. * @throws IOException */ @Override public final long readLong() throws IOException { dis.readFully(work, 0, 8); return (long) (work[7]) << 56 | /* long cast needed or shift done modulo 32 */ (long) (work[6] & 0xff) << 48 | (long) (work[5] & 0xff) << 40 | (long) (work[4] & 0xff) << 32 | (long) (work[3] & 0xff) << 24 | (long) (work[2] & 0xff) << 16 | (long) (work[1] & 0xff) << 8 | work[0] & 0xff; } /** * Read short, 16-bits. Like DataInputStream.readShort except little endian. * * @return little endian binary short from stream. * @throws IOException if read fails. */ @Override public final short readShort() throws IOException { dis.readFully(work, 0, 2); return (short) ((work[1] & 0xff) << 8 | (work[0] & 0xff)); } /** * Read UTF counted string. * * @return String read. */ @Override public final String readUTF() throws IOException { return dis.readUTF(); } /** * Read an unsigned byte. Note: returns an int, even though says Byte (non-Javadoc) * * @throws IOException if read fails. * @see java.io.DataInput#readUnsignedByte() */ @Override public final int readUnsignedByte() throws IOException { return dis.readUnsignedByte(); } /** * Read an unsigned short, 16 bits. Like DataInputStream.readUnsignedShort except little endian. * Note, returns int even though it reads a short. * * @return little-endian int from the stream. * @throws IOException if read fails. */ @Override public final int readUnsignedShort() throws IOException { dis.readFully(work, 0, 2); return ((work[1] & 0xff) << 8 | (work[0] & 0xff)); } /** * Skip over bytes in the stream. See the general contract of the <code>skipBytes</code> method of * <code>DataInput</code>. * <p/> * Bytes for this operation are read from the contained input stream. * * @param n the number of bytes to be skipped. * * @return the actual number of bytes skipped. * @throws IOException if an I/O error occurs. */ @Override public final int skipBytes(int n) throws IOException { return dis.skipBytes(n); } }
8,390
26.243506
100
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/manifest/binary/ResXmlEncoders.java
/** * Copyright 2011 Ryszard Wi??????niewski <brut.alll@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.manifest.binary; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.List; /** * @author Ryszard Wi??????niewski <brut.alll@gmail.com> */ public final class ResXmlEncoders { public static String escapeXmlChars(String str) { return str.replace("&", "&amp;").replace("<", "&lt;"); } public static String encodeAsResXmlAttr(String str) { if (str.isEmpty()) { return str; } char[] chars = str.toCharArray(); StringBuilder out = new StringBuilder(str.length() + 10); switch (chars[0]) { case '#': case '@': case '?': out.append('\\'); } for (char c : chars) { switch (c) { case '\\': out.append('\\'); break; case '"': out.append("&quot;"); continue; case '\n': out.append("\\n"); continue; default: if (!isPrintableChar(c)) { out.append(String.format("\\u%04x", (int) c)); continue; } } out.append(c); } return out.toString(); } public static String encodeAsXmlValue(String str) { if (str.isEmpty()) { return str; } char[] chars = str.toCharArray(); StringBuilder out = new StringBuilder(str.length() + 10); switch (chars[0]) { case '#': case '@': case '?': out.append('\\'); } boolean isInStyleTag = false; int startPos = 0; boolean enclose = false; boolean wasSpace = true; for (char c : chars) { if (isInStyleTag) { if (c == '>') { isInStyleTag = false; startPos = out.length() + 1; enclose = false; } } else if (c == ' ') { if (wasSpace) { enclose = true; } wasSpace = true; } else { wasSpace = false; switch (c) { case '\\': out.append('\\'); break; case '\'': case '\n': enclose = true; break; case '"': out.append('\\'); break; case '<': isInStyleTag = true; if (enclose) { out.insert(startPos, '"').append('"'); } break; default: if (!isPrintableChar(c)) { out.append(String.format("\\u%04x", (int) c)); continue; } } } out.append(c); } if (enclose || wasSpace) { out.insert(startPos, '"').append('"'); } return out.toString(); } public static boolean hasMultipleNonPositionalSubstitutions(String str) { return findNonPositionalSubstitutions(str, 2).size() > 1; } public static String enumerateNonPositionalSubstitutions(String str) { List<Integer> subs = findNonPositionalSubstitutions(str, -1); if (subs.size() < 2) { return str; } StringBuilder out = new StringBuilder(); int pos = 0; int count = 0; for (Integer sub : subs) { out.append(str.substring(pos, ++sub)).append(++count).append('$'); pos = sub; } out.append(str.substring(pos)); return out.toString(); } /** * It searches for "%", but not "%%" nor "%(\d)+\$" */ private static List<Integer> findNonPositionalSubstitutions(String str, int max) { int pos = 0; int pos2 = 0; int count = 0; int length = str.length(); List<Integer> ret = new ArrayList<Integer>(); while ((pos2 = (pos = str.indexOf('%', pos2)) + 1) != 0) { if (pos2 == length) { break; } char c = str.charAt(pos2++); if (c == '%') { continue; } if (c >= '0' && c <= '9' && pos2 < length) { do { c = str.charAt(pos2++); } while (c >= '0' && c <= '9' && pos2 < length); if (c == '$') { continue; } } ret.add(pos); if (max != -1 && ++count >= max) { break; } } return ret; } private static boolean isPrintableChar(char c) { Character.UnicodeBlock block = Character.UnicodeBlock.of(c); return !Character.isISOControl(c) && c != KeyEvent.CHAR_UNDEFINED && block != null && block != Character.UnicodeBlock.SPECIALS; } }
4,949
23.75
86
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/manifest/binary/StringBlock.java
/** * Copyright 2011 Ryszard Wi??????????????????niewski <brut.alll@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.manifest.binary; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Ryszard Wi??????????????????niewski <brut.alll@gmail.com> * @author Dmitry Skiba * * Block of strings, used in binary xml and arsc. * * TODO: - implement get() * */ public class StringBlock { /** * Reads whole (including chunk type) string block from stream. Stream must be at the chunk type. */ public static StringBlock read(ExtDataInput reader) throws IOException { reader.skipCheckInt(CHUNK_TYPE); int chunkSize = reader.readInt(); int stringCount = reader.readInt(); int styleOffsetCount = reader.readInt(); int flags = reader.readInt(); int stringsOffset = reader.readInt(); int stylesOffset = reader.readInt(); StringBlock block = new StringBlock(); block.m_isUTF8 = (flags & UTF8_FLAG) != 0; block.m_stringOffsets = reader.readIntArray(stringCount); block.m_stringOwns = new int[stringCount]; for (int i = 0; i < stringCount; i++) { block.m_stringOwns[i] = -1; } if (styleOffsetCount != 0) { block.m_styleOffsets = reader.readIntArray(styleOffsetCount); } { int size = ((stylesOffset == 0) ? chunkSize : stylesOffset) - stringsOffset; if ((size % 4) != 0) { throw new IOException("String data size is not multiple of 4 (" + size + ")."); } block.m_strings = new byte[size]; reader.readFully(block.m_strings); } if (stylesOffset != 0) { int size = (chunkSize - stylesOffset); if ((size % 4) != 0) { throw new IOException("Style data size is not multiple of 4 (" + size + ")."); } block.m_styles = reader.readIntArray(size / 4); } return block; } /** * Returns number of strings in block. */ public int getCount() { return m_stringOffsets != null ? m_stringOffsets.length : 0; } /** * Returns raw string (without any styling information) at specified index. */ public String getString(int index) { if (index < 0 || m_stringOffsets == null || index >= m_stringOffsets.length) { return null; } int offset = m_stringOffsets[index]; int length; if (!m_isUTF8) { length = getShort(m_strings, offset) * 2; offset += 2; } else { offset += getVarint(m_strings, offset)[1]; int[] varint = getVarint(m_strings, offset); offset += varint[1]; length = varint[0]; } return decodeString(offset, length); } /** * Not yet implemented. * * Returns string with style information (if any). */ public CharSequence get(int index) { return getString(index); } /** * Returns string with style tags (html-like). */ public String getHTML(int index) { String raw = getString(index); if (raw == null) { return raw; } int[] style = getStyle(index); if (style == null) { return ResXmlEncoders.escapeXmlChars(raw); } StringBuilder html = new StringBuilder(raw.length() + 32); int[] opened = new int[style.length / 3]; int offset = 0, depth = 0; while (true) { int i = -1, j; for (j = 0; j != style.length; j += 3) { if (style[j + 1] == -1) { continue; } if (i == -1 || style[i + 1] > style[j + 1]) { i = j; } } int start = ((i != -1) ? style[i + 1] : raw.length()); for (j = depth - 1; j >= 0; j--) { int last = opened[j]; int end = style[last + 2]; if (end >= start) { break; } if (offset <= end) { html.append(ResXmlEncoders.escapeXmlChars(raw.substring(offset, end + 1))); offset = end + 1; } outputStyleTag(getString(style[last]), html, true); } depth = j + 1; if (offset < start) { html.append(ResXmlEncoders.escapeXmlChars(raw.substring(offset, start))); offset = start; } if (i == -1) { break; } outputStyleTag(getString(style[i]), html, false); style[i + 1] = -1; opened[depth++] = i; } return html.toString(); } private void outputStyleTag(String tag, StringBuilder builder, boolean close) { builder.append('<'); if (close) { builder.append('/'); } int pos = tag.indexOf(';'); if (pos == -1) { builder.append(tag); } else { builder.append(tag.substring(0, pos)); if (!close) { boolean loop = true; while (loop) { int pos2 = tag.indexOf('=', pos + 1); builder.append(' ').append(tag.substring(pos + 1, pos2)).append("=\""); pos = tag.indexOf(';', pos2 + 1); String val; if (pos != -1) { val = tag.substring(pos2 + 1, pos); } else { loop = false; val = tag.substring(pos2 + 1); } builder.append(ResXmlEncoders.escapeXmlChars(val)).append('"'); } } } builder.append('>'); } /** * Finds index of the string. Returns -1 if the string was not found. */ public int find(String string) { if (string == null) { return -1; } for (int i = 0; i != m_stringOffsets.length; ++i) { int offset = m_stringOffsets[i]; int length = getShort(m_strings, offset); if (length != string.length()) { continue; } int j = 0; for (; j != length; ++j) { offset += 2; if (string.charAt(j) != getShort(m_strings, offset)) { break; } } if (j == length) { return i; } } return -1; } // /////////////////////////////////////////// implementation private StringBlock() { } /** * Returns style information - array of int triplets, where in each triplet: * first int is index * of tag name ('b','i', etc.) * second int is tag start index in string * third int is tag end * index in string */ private int[] getStyle(int index) { if (m_styleOffsets == null || m_styles == null || index >= m_styleOffsets.length) { return null; } int offset = m_styleOffsets[index] / 4; int style[]; { int count = 0; for (int i = offset; i < m_styles.length; ++i) { if (m_styles[i] == -1) { break; } count += 1; } if (count == 0 || (count % 3) != 0) { return null; } style = new int[count]; } for (int i = offset, j = 0; i < m_styles.length;) { if (m_styles[i] == -1) { break; } style[j++] = m_styles[i++]; } return style; } private String decodeString(int offset, int length) { try { return (m_isUTF8 ? UTF8_DECODER : UTF16LE_DECODER).decode( ByteBuffer.wrap(m_strings, offset, length)).toString(); } catch (CharacterCodingException ex) { LOGGER.log(Level.WARNING, null, ex); return null; } } private static final int getShort(byte[] array, int offset) { return (array[offset + 1] & 0xff) << 8 | array[offset] & 0xff; } private static final int[] getVarint(byte[] array, int offset) { int val = array[offset]; boolean more = (val & 0x80) != 0; val &= 0x7f; if (!more) { return new int[] { val, 1 }; } else { return new int[] { val << 8 | array[offset + 1] & 0xff, 2 }; } } public boolean touch(int index, int own) { if (index < 0 || m_stringOwns == null || index >= m_stringOwns.length) { return false; } if (m_stringOwns[index] == -1) { m_stringOwns[index] = own; return true; } else if (m_stringOwns[index] == own) { return true; } else { return false; } } private int[] m_stringOffsets; private byte[] m_strings; private int[] m_styleOffsets; private int[] m_styles; private boolean m_isUTF8; private int[] m_stringOwns; private static final CharsetDecoder UTF16LE_DECODER = Charset.forName("UTF-16LE").newDecoder(); private static final CharsetDecoder UTF8_DECODER = Charset.forName("UTF-8").newDecoder(); private static final Logger LOGGER = Logger.getLogger(StringBlock.class.getName()); private static final int CHUNK_TYPE = 0x001C0001; private static final int UTF8_FLAG = 0x00000100; }
9,139
27.652038
99
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/manifest/binary/TypedValue.java
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3.manifest.binary; /** * Container for a dynamically typed data value. Primarily used with * {@link android.content.res.Resources} for holding resource values. */ public class TypedValue { /** The value contains no data. */ public static final int TYPE_NULL = 0x00; /** The <var>data</var> field holds a resource identifier. */ public static final int TYPE_REFERENCE = 0x01; /** * The <var>data</var> field holds an attribute resource identifier (referencing an attribute in * the current theme style, not a resource entry). */ public static final int TYPE_ATTRIBUTE = 0x02; /** * The <var>string</var> field holds string data. In addition, if <var>data</var> is non-zero then * it is the string block index of the string and <var>assetCookie</var> is the set of assets the * string came from. */ public static final int TYPE_STRING = 0x03; /** The <var>data</var> field holds an IEEE 754 floating point number. */ public static final int TYPE_FLOAT = 0x04; /** * The <var>data</var> field holds a complex number encoding a dimension value. */ public static final int TYPE_DIMENSION = 0x05; /** * The <var>data</var> field holds a complex number encoding a fraction of a container. */ public static final int TYPE_FRACTION = 0x06; /** * Identifies the start of plain integer values. Any type value from this to * {@link #TYPE_LAST_INT} means the <var>data</var> field holds a generic integer value. */ public static final int TYPE_FIRST_INT = 0x10; /** * The <var>data</var> field holds a number that was originally specified in decimal. */ public static final int TYPE_INT_DEC = 0x10; /** * The <var>data</var> field holds a number that was originally specified in hexadecimal (0xn). */ public static final int TYPE_INT_HEX = 0x11; /** * The <var>data</var> field holds 0 or 1 that was originally specified as "false" or "true". */ public static final int TYPE_INT_BOOLEAN = 0x12; /** * Identifies the start of integer values that were specified as color constants (starting with * '#'). */ public static final int TYPE_FIRST_COLOR_INT = 0x1c; /** * The <var>data</var> field holds a color that was originally specified as #aarrggbb. */ public static final int TYPE_INT_COLOR_ARGB8 = 0x1c; /** * The <var>data</var> field holds a color that was originally specified as #rrggbb. */ public static final int TYPE_INT_COLOR_RGB8 = 0x1d; /** * The <var>data</var> field holds a color that was originally specified as #argb. */ public static final int TYPE_INT_COLOR_ARGB4 = 0x1e; /** * The <var>data</var> field holds a color that was originally specified as #rgb. */ public static final int TYPE_INT_COLOR_RGB4 = 0x1f; /** * Identifies the end of integer values that were specified as color constants. */ public static final int TYPE_LAST_COLOR_INT = 0x1f; /** Identifies the end of plain integer values. */ public static final int TYPE_LAST_INT = 0x1f; /* ------------------------------------------------------------ */ /** Complex data: bit location of unit information. */ public static final int COMPLEX_UNIT_SHIFT = 0; /** * Complex data: mask to extract unit information (after shifting by {@link #COMPLEX_UNIT_SHIFT}). * This gives us 16 possible types, as defined below. */ public static final int COMPLEX_UNIT_MASK = 0xf; /** {@link #TYPE_DIMENSION} complex unit: Value is raw pixels. */ public static final int COMPLEX_UNIT_PX = 0; /** * {@link #TYPE_DIMENSION} complex unit: Value is Device Independent Pixels. */ public static final int COMPLEX_UNIT_DIP = 1; /** {@link #TYPE_DIMENSION} complex unit: Value is a scaled pixel. */ public static final int COMPLEX_UNIT_SP = 2; /** {@link #TYPE_DIMENSION} complex unit: Value is in points. */ public static final int COMPLEX_UNIT_PT = 3; /** {@link #TYPE_DIMENSION} complex unit: Value is in inches. */ public static final int COMPLEX_UNIT_IN = 4; /** {@link #TYPE_DIMENSION} complex unit: Value is in millimeters. */ public static final int COMPLEX_UNIT_MM = 5; /** * {@link #TYPE_FRACTION} complex unit: A basic fraction of the overall size. */ public static final int COMPLEX_UNIT_FRACTION = 0; /** {@link #TYPE_FRACTION} complex unit: A fraction of the parent size. */ public static final int COMPLEX_UNIT_FRACTION_PARENT = 1; /** * Complex data: where the radix information is, telling where the decimal place appears in the * mantissa. */ public static final int COMPLEX_RADIX_SHIFT = 4; /** * Complex data: mask to extract radix information (after shifting by {@link #COMPLEX_RADIX_SHIFT} * ). This give us 4 possible fixed point representations as defined below. */ public static final int COMPLEX_RADIX_MASK = 0x3; /** Complex data: the mantissa is an integral number -- i.e., 0xnnnnnn.0 */ public static final int COMPLEX_RADIX_23p0 = 0; /** Complex data: the mantissa magnitude is 16 bits -- i.e, 0xnnnn.nn */ public static final int COMPLEX_RADIX_16p7 = 1; /** Complex data: the mantissa magnitude is 8 bits -- i.e, 0xnn.nnnn */ public static final int COMPLEX_RADIX_8p15 = 2; /** Complex data: the mantissa magnitude is 0 bits -- i.e, 0x0.nnnnnn */ public static final int COMPLEX_RADIX_0p23 = 3; /** Complex data: bit location of mantissa information. */ public static final int COMPLEX_MANTISSA_SHIFT = 8; /** * Complex data: mask to extract mantissa information (after shifting by * {@link #COMPLEX_MANTISSA_SHIFT}). This gives us 23 bits of precision; the top bit is the sign. */ public static final int COMPLEX_MANTISSA_MASK = 0xffffff; /* ------------------------------------------------------------ */ /** * If {@link #density} is equal to this value, then the density should be treated as the system's * default density value: {@link DisplayMetrics#DENSITY_DEFAULT}. */ public static final int DENSITY_DEFAULT = 0; /** * If {@link #density} is equal to this value, then there is no density associated with the * resource and it should not be scaled. */ public static final int DENSITY_NONE = 0xffff; /* ------------------------------------------------------------ */ /** * The type held by this value, as defined by the constants here. This tells you how to interpret * the other fields in the object. */ public int type; private static final float MANTISSA_MULT = 1.0f / (1 << TypedValue.COMPLEX_MANTISSA_SHIFT); private static final float[] RADIX_MULTS = new float[] { 1.0f * MANTISSA_MULT, 1.0f / (1 << 7) * MANTISSA_MULT, 1.0f / (1 << 15) * MANTISSA_MULT, 1.0f / (1 << 23) * MANTISSA_MULT }; /** * Retrieve the base value from a complex data integer. This uses the * {@link #COMPLEX_MANTISSA_MASK} and {@link #COMPLEX_RADIX_MASK} fields of the data to compute a * floating point representation of the number they describe. The units are ignored. * * @param complex A complex data value. * * @return A floating point value corresponding to the complex data. */ public static float complexToFloat(int complex) { return (complex & (TypedValue.COMPLEX_MANTISSA_MASK << TypedValue.COMPLEX_MANTISSA_SHIFT)) * RADIX_MULTS[(complex >> TypedValue.COMPLEX_RADIX_SHIFT) & TypedValue.COMPLEX_RADIX_MASK]; } private static final String[] DIMENSION_UNIT_STRS = new String[] { "px", "dip", "sp", "pt", "in", "mm" }; private static final String[] FRACTION_UNIT_STRS = new String[] { "%", "%p" }; /** * Perform type conversion as per {@link #coerceToString()} on an explicitly supplied type and * data. * * @param type The data type identifier. * @param data The data value. * * @return String The coerced string value. If the value is null or the type is not known, null is * returned. */ public static final String coerceToString(int type, int data) { switch (type) { case TYPE_NULL: return null; case TYPE_REFERENCE: return "@" + data; case TYPE_ATTRIBUTE: return "?" + data; case TYPE_FLOAT: return Float.toString(Float.intBitsToFloat(data)); case TYPE_DIMENSION: return Float.toString(complexToFloat(data)) + DIMENSION_UNIT_STRS[(data >> COMPLEX_UNIT_SHIFT) & COMPLEX_UNIT_MASK]; case TYPE_FRACTION: return Float.toString(complexToFloat(data) * 100) + FRACTION_UNIT_STRS[(data >> COMPLEX_UNIT_SHIFT) & COMPLEX_UNIT_MASK]; case TYPE_INT_HEX: return "0x" + Integer.toHexString(data); case TYPE_INT_BOOLEAN: return data != 0 ? "true" : "false"; } if (type >= TYPE_FIRST_COLOR_INT && type <= TYPE_LAST_COLOR_INT) { String res = String.format("%08x", data); char[] vals = res.toCharArray(); switch (type) { default: case TYPE_INT_COLOR_ARGB8:// #AaRrGgBb break; case TYPE_INT_COLOR_RGB8:// #FFRrGgBb->#RrGgBb res = res.substring(2); break; case TYPE_INT_COLOR_ARGB4:// #AARRGGBB->#ARGB res = new StringBuffer().append(vals[0]).append(vals[2]).append(vals[4]).append(vals[6]) .toString(); break; case TYPE_INT_COLOR_RGB4:// #FFRRGGBB->#RGB res = new StringBuffer().append(vals[2]).append(vals[4]).append(vals[6]).toString(); break; } return "#" + res; } else if (type >= TYPE_FIRST_INT && type <= TYPE_LAST_INT) { String res; switch (type) { default: case TYPE_INT_DEC: res = Integer.toString(data); break; // defined before /* * case TYPE_INT_HEX: res = "0x" + Integer.toHexString(data); break; case TYPE_INT_BOOLEAN: * res = (data != 0) ? "true":"false"; break; */ } return res; } return null; } };
10,615
37.18705
100
java
code-critters
code-critters-master/src/main/java/de/grubermi/code_critters/application/scheduledTasks/DeleteOldResults.java
package de.grubermi.code_critters.application.scheduledTasks; /*- * #%L * Code Critters * %% * Copyright (C) 2019 - 2020 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.codecritters.code_critters.persistence.repository.ResultRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Calendar; import java.util.Date; @Component public class DeleteOldResults { private final ResultRepository resultRepository; @Autowired public DeleteOldResults(ResultRepository resultRepository) { this.resultRepository = resultRepository; } /** * Deletes results older then one day automatically from the database. * Executed at 00:00 and 12:00 every day. */ @Scheduled(cron="0 0 */12 * * *") public void deleteOldResults() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); Date date = cal.getTime(); resultRepository.deleteAll(resultRepository.getAllByUpdatedBeforeAndUserIsNull(date)); } }
1,794
31.053571
94
java
code-critters
code-critters-master/src/main/java/de/grubermi/code_critters/persistence/customDataTypes/LevelResultType.java
package de.grubermi.code_critters.persistence.customDataTypes; /*- * #%L * Code Critters * %% * Copyright (C) 2019 - 2020 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ public interface LevelResultType { String getName(); Integer getScore(); Integer getStars(); }
931
29.064516
71
java
code-critters
code-critters-master/src/main/java/de/grubermi/code_critters/persistence/entities/Row.java
package de.grubermi.code_critters.persistence.entities; /*- * #%L * Code Critters * %% * Copyright (C) 2019 - 2020 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.hibernate.annotations.GenericGenerator; import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Row { @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") private String id; @NotEmpty @Column(unique = true) private String name; private int position; public Row(String name, int position) { this.name = name; this.position = position; } public Row() { } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
1,841
22.922078
71
java
code-critters
code-critters-master/src/main/java/de/grubermi/code_critters/persistence/repository/RowRepository.java
package de.grubermi.code_critters.persistence.repository; /*- * #%L * Code Critters * %% * Copyright (C) 2019 - 2020 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import de.grubermi.code_critters.persistence.entities.Row; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.List; @Repository public interface RowRepository extends CrudRepository<Row, String> { @Query("SELECT r FROM Row as r ORDER BY r.position ASC") Collection<Row> getRows(); }
1,270
31.589744
71
java
code-critters
code-critters-master/src/main/java/de/grubermi/code_critters/spring/HtmlResponseWrapper.java
package de.grubermi.code_critters.spring; /*- * #%L * Code Critters * %% * Copyright (C) 2019 - 2020 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import javax.servlet.ServletOutputStream; import javax.servlet.WriteListener; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class HtmlResponseWrapper extends HttpServletResponseWrapper { private final ByteArrayOutputStream capture; private ServletOutputStream output; private PrintWriter writer; public HtmlResponseWrapper(HttpServletResponse response) { super(response); capture = new ByteArrayOutputStream(response.getBufferSize()); } @Override public ServletOutputStream getOutputStream() { if (writer != null) { throw new IllegalStateException( "getWriter() has already been called on this response."); } if (output == null) { output = new ServletOutputStream() { @Override public void write(int b) throws IOException { capture.write(b); } @Override public void flush() throws IOException { capture.flush(); } @Override public void close() throws IOException { capture.close(); } @Override public boolean isReady() { return false; } @Override public void setWriteListener(WriteListener arg0) { } }; } return output; } @Override public PrintWriter getWriter() throws IOException { if (output != null) { throw new IllegalStateException( "getOutputStream() has already been called on this response."); } if (writer == null) { writer = new PrintWriter(new OutputStreamWriter(capture, getCharacterEncoding())); } return writer; } @Override public void flushBuffer() throws IOException { super.flushBuffer(); if (writer != null) { writer.flush(); } else if (output != null) { output.flush(); } } public byte[] getCaptureAsBytes() throws IOException { if (writer != null) { writer.close(); } else if (output != null) { output.close(); } return capture.toByteArray(); } public String getCaptureAsString() throws IOException { return new String(getCaptureAsBytes(), getCharacterEncoding()); } }
3,530
27.475806
83
java
code-critters
code-critters-master/src/main/java/de/grubermi/code_critters/spring/PolymerResourceCacheFilter.java
package de.grubermi.code_critters.spring; /*- * #%L * Code Critters * %% * Copyright (C) 2019 - 2020 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.apache.commons.io.IOUtils; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; @Component public class PolymerResourceCacheFilter implements Filter { private static String TEMPDIR = "./temp"; @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; // only /lib files needs to be modified if (httpRequest.getRequestURI().startsWith("/lib/")) { File file = new File(TEMPDIR + httpRequest.getRequestURI()); if (file.exists() && !file.isDirectory()) { //check age of the file RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); if (file.lastModified() >= bean.getStartTime()) { //If younger then runtime use existing one InputStream is = new FileInputStream(file); response.setContentLength((int) file.length()); response.setContentType("application/javascript;charset=ISO-8859-1"); IOUtils.copy(is, response.getOutputStream()); is.close(); } else { //Create new cached file String responseContent = cacheFile(request, response, chain, file); response.setContentLength(responseContent.length()); response.getWriter().write(responseContent); } } else { //Create new cached file String responseContent = cacheFile(request, response, chain, file); response.setContentLength(responseContent.length()); response.getWriter().write(responseContent); } } else { //Do nothing and handle as normal request chain.doFilter(request, response); } } /** * Caches the files addressed by /lib/* and changes their content so that the * browser can resolve the paths * * @param request Request coming from the browser * @param response Response to send back to the browser * @param chain Filterchain doing some more filters and executes the reques * @param f The file to write the data in * @return the responses string content * @throws IOException if an error occurs during writing the file * @throws ServletException comes from the filter chain */ private String cacheFile(ServletRequest request, ServletResponse response, FilterChain chain, File f) throws IOException, ServletException { HtmlResponseWrapper capturingResponseWrapper = new HtmlResponseWrapper( (HttpServletResponse) response); chain.doFilter(request, capturingResponseWrapper); //add "/lib/" in import paths in the file where "@polymer" or "@webcombonent" is String pattern = "(?<=(import\\s.{0,100}))(?=(@.{3,20}/))"; String[] componentsArray = capturingResponseWrapper.getCaptureAsString().split(pattern); String responseContent = componentsArray[0]; for (int i = 1; i < componentsArray.length; ++i) { responseContent += "/lib/" + componentsArray[i]; } //create directory and file f.getParentFile().mkdirs(); f.createNewFile(); FileWriter writer = new FileWriter(f); writer.write(responseContent); writer.close(); return responseContent; } @Override public void destroy() { } }
4,743
39.547009
144
java
code-critters
code-critters-master/src/main/java/org/codecritters/code_critters/Code_CrittersServiceApplication.java
package org.codecritters.code_critters; /*- * #%L * Code Critters * %% * Copyright (C) 2019 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.PropertySource; import org.springframework.scheduling.annotation.EnableScheduling; /** * Einstiegspunkt in die Applikation */ //@PropertySource("file:./resources/application.properties") @SpringBootApplication @EnableScheduling public class Code_CrittersServiceApplication { /** * Startet die Application * * @param args Benoetigte Argumente */ public static void main(String[] args) { SpringApplication.run(Code_CrittersServiceApplication.class, args); } }
1,462
29.479167
75
java
code-critters
code-critters-master/src/main/java/org/codecritters/code_critters/application/exception/AlreadyExistsException.java
package org.codecritters.code_critters.application.exception; /*- * #%L * Code Critters * %% * Copyright (C) 2019 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.CONFLICT) public class AlreadyExistsException extends ApplicationException { public AlreadyExistsException(String message, Throwable cause) { super(message, cause); } public AlreadyExistsException(String message, String msg_key) { super(message, msg_key); } public AlreadyExistsException(String message) { super(message); } }
1,327
29.883721
71
java
code-critters
code-critters-master/src/main/java/org/codecritters/code_critters/application/exception/ApplicationException.java
package org.codecritters.code_critters.application.exception; /*- * #%L * Code Critters * %% * Copyright (C) 2019 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ public class ApplicationException extends RuntimeException { private String msg_key; public ApplicationException(String message, String msg_key) { super(message); this.msg_key = msg_key; } public ApplicationException(String message) { super(message); } public ApplicationException(String message, Throwable cause) { super(message, cause); } public ApplicationException(String message, Throwable cause, String msg_key) { super(message, cause); this.msg_key = msg_key; } public String getMsg_key() { return msg_key; } public void setMsg_key(String msg_key) { this.msg_key = msg_key; } }
1,524
26.232143
82
java
code-critters
code-critters-master/src/main/java/org/codecritters/code_critters/application/exception/IllegalActionException.java
package org.codecritters.code_critters.application.exception; /*- * #%L * Code Critters * %% * Copyright (C) 2019 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.BAD_REQUEST) public class IllegalActionException extends ApplicationException { public IllegalActionException(String message, String msg_key) { super(message, msg_key); } }
1,140
31.6
71
java
code-critters
code-critters-master/src/main/java/org/codecritters/code_critters/application/exception/IncompleteDataException.java
package org.codecritters.code_critters.application.exception; /*- * #%L * Code Critters * %% * Copyright (C) 2019 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.BAD_REQUEST) public class IncompleteDataException extends ApplicationException { public IncompleteDataException(String message) { super(message); } public IncompleteDataException(String message, Throwable cause) { super(message, cause); } }
1,225
30.435897
71
java
code-critters
code-critters-master/src/main/java/org/codecritters/code_critters/application/exception/NotFoundException.java
package org.codecritters.code_critters.application.exception; /*- * #%L * Code Critters * %% * Copyright (C) 2019 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** * Fehlermeldung, falls ein Element nicht gefunden werden kann */ @ResponseStatus(HttpStatus.NOT_FOUND) public class NotFoundException extends ApplicationException { public NotFoundException(String message) { super(message); } public NotFoundException(String message, String msgKey) { super(message, msgKey); } }
1,278
27.422222
71
java
code-critters
code-critters-master/src/main/java/org/codecritters/code_critters/application/init/UserInitialization.java
package org.codecritters.code_critters.application.init; /*- * #%L * Code Critters * %% * Copyright (C) 2019 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.codecritters.code_critters.application.service.PasswordService; import org.codecritters.code_critters.persistence.entities.User; import org.codecritters.code_critters.persistence.repository.UserRepositiory; import org.codecritters.code_critters.web.enums.Language; import org.codecritters.code_critters.web.enums.Role; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.List; @Component public class UserInitialization { private UserRepositiory userRepositiory; private PasswordService passwordService; private final Logger logger = LogManager.getLogger(UserInitialization.class); @Autowired public UserInitialization(UserRepositiory userRepositiory, PasswordService passwordService) { this.userRepositiory = userRepositiory; this.passwordService = passwordService; } @PostConstruct public void init() { List<User> users = userRepositiory.findAllByRole(Role.admin); if (users == null || users.isEmpty()) { User user = new User(); user.setActive(true); user.setEmail("admin@admin.de"); user.setUsername("admin"); user.setRole(Role.admin); user.setLanguage(Language.en); user = passwordService.hashPassword("admin", user); userRepositiory.save(user); logger.info("User admin:admin was added to the database"); } } }
2,427
34.188406
97
java
code-critters
code-critters-master/src/main/java/org/codecritters/code_critters/application/scheduledTasks/DeleteOldResults.java
package org.codecritters.code_critters.application.scheduledTasks; /*- * #%L * Code Critters * %% * Copyright (C) 2019 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.codecritters.code_critters.persistence.repository.ResultRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Calendar; import java.util.Date; @Component public class DeleteOldResults { private final ResultRepository resultRepository; @Autowired public DeleteOldResults(ResultRepository resultRepository) { this.resultRepository = resultRepository; } /** * Deletes results older then one day automatically from the database. * Executed at 00:00 and 12:00 every day. */ @Scheduled(cron = "0 0 */12 * * *") public void deleteOldResults() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); Date date = cal.getTime(); resultRepository.deleteAll(resultRepository.getAllByUpdatedBeforeAndUserIsNull(date)); } }
1,794
31.053571
94
java
code-critters
code-critters-master/src/main/java/org/codecritters/code_critters/application/service/GameService.java
package org.codecritters.code_critters.application.service; /*- * #%L * Code Critters * %% * Copyright (C) 2019 - 2021 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.codecritters.code_critters.application.exception.IncompleteDataException; import org.codecritters.code_critters.application.exception.NotFoundException; import org.codecritters.code_critters.persistence.entities.Game; import org.codecritters.code_critters.persistence.entities.Level; import org.codecritters.code_critters.persistence.entities.User; import org.codecritters.code_critters.persistence.repository.GameRepository; import org.codecritters.code_critters.persistence.repository.LevelRepository; import org.codecritters.code_critters.persistence.repository.UserRepositiory; import org.codecritters.code_critters.web.dto.GameDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDateTime; @Service public class GameService { private final LevelRepository levelRepository; private final UserRepositiory userRepositiory; private final GameRepository gameRepository; @Autowired public GameService(LevelRepository levelRepository, UserRepositiory userRepositiory, GameRepository gameRepository) { this.levelRepository = levelRepository; this.userRepositiory = userRepositiory; this.gameRepository = gameRepository; } /** * Inserts a new game data set into the database with the values passed in the game dto for the user with the given * cookie, if registered. * @param dto The game dto containing the initial data. * @param cookie The cookie for the current user. * @return A game dto containing the inserted data including its new id. */ public GameDTO createGame(GameDTO dto, String cookie) { Level level = levelRepository.findByName(dto.getName()); User user = userRepositiory.findByCookie(cookie); Game game; if (level == null) { throw new NotFoundException("Could not find level with name " + dto.getName()); } if (user != null) { game = new Game(level, LocalDateTime.now(), user.getId()); } else { game = new Game(level, LocalDateTime.now()); } game = gameRepository.save(game); if (game.getId() == null) { throw new IllegalStateException("Problem saving game!"); } return createGameDTO(game); } /** * Updates the game data for an existing game with the given values passed in the dto. * @param dto The dto containing the updated game data. */ public void saveGame(GameDTO dto) { dto.setEnd(LocalDateTime.now()); Level level = levelRepository.findByName(dto.getName()); Game game; if (level == null) { throw new NotFoundException("Could not find level with name " + dto.getName()); } if (dto.getId() == null) { throw new IncompleteDataException("Cannot save a game dto with ID null!"); } dto.setLevel(level); game = createGame(dto); gameRepository.save(game); } private GameDTO createGameDTO(Game game) { GameDTO dto = new GameDTO(); if (game.getId() != null) { dto.setId(game.getId()); } if (game.getLevel() != null) { dto.setLevel(game.getLevel()); } if (game.getStart() != null) { dto.setStart(game.getStart()); } if(game.getEnd() != null) { dto.setEnd(game.getEnd()); } if(game.getUserID() != null) { dto.setUserID(game.getUserID()); } return dto; } private Game createGame(GameDTO dto) { Game game = new Game(); if (dto.getId() != null) { game.setId(dto.getId()); } if (dto.getLevel() != null) { game.setLevel(dto.getLevel()); } if (dto.getStart() != null) { game.setStart(dto.getStart()); } if (dto.getEnd() != null) { game.setEnd(dto.getEnd()); } if (dto.getUserID() != null) { game.setUserID(dto.getUserID()); } game.setScore(dto.getScore()); game.setMutantsKilled(dto.getMutantsKilled()); game.setHumansFinished(dto.getHumansFinished()); game.setGameTime(dto.getGameTime()); return game; } }
5,192
32.720779
119
java
code-critters
code-critters-master/src/main/java/org/codecritters/code_critters/application/service/LevelService.java
package org.codecritters.code_critters.application.service; /*- * #%L * Code Critters * %% * Copyright (C) 2019 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.codecritters.code_critters.application.exception.AlreadyExistsException; import org.codecritters.code_critters.application.exception.NotFoundException; import org.codecritters.code_critters.persistence.entities.Level; import org.codecritters.code_critters.persistence.entities.CritterRow; import org.codecritters.code_critters.persistence.entities.User; import org.codecritters.code_critters.persistence.repository.LevelRepository; import org.codecritters.code_critters.persistence.repository.MutantRepository; import org.codecritters.code_critters.persistence.repository.ResultRepository; import org.codecritters.code_critters.persistence.repository.RowRepository; import org.codecritters.code_critters.persistence.repository.UserRepositiory; import org.codecritters.code_critters.web.dto.LevelDTO; import org.codecritters.code_critters.web.dto.MutantDTO; import org.codecritters.code_critters.web.dto.RowDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.validation.ConstraintViolationException; import java.io.File; import java.io.IOException; import java.util.*; @Service public class LevelService { private final LevelRepository levelRepository; private final MutantRepository mutantRepository; private final RowRepository rowRepository; private final UserRepositiory userRepositiory; private final ResultRepository resultRepository; @Autowired public LevelService(LevelRepository levelRepository, MutantRepository mutantRepository, RowRepository rowRepository, UserRepositiory userRepositiory, ResultRepository resultRepository) { this.levelRepository = levelRepository; this.mutantRepository = mutantRepository; this.rowRepository = rowRepository; this.userRepositiory = userRepositiory; this.resultRepository = resultRepository; } public void createLevel(LevelDTO dto) { if (levelRepository.findByName(dto.getName()) != null) { throw new AlreadyExistsException("Tried to insert a level name that already exists"); } try { levelRepository.save(createLevelDAO(dto)); } catch (ConstraintViolationException e) { throw new AlreadyExistsException("Tried to insert a level that already exists", e); } } public void deleteLevel(String name) { Level level = levelRepository.findByName(name); if (level == null) { throw new NotFoundException("There's no level with name: " + name); } else { levelRepository.deleteById(level.getId()); } } public void updateLevel(LevelDTO dto) { try { levelRepository.save(createLevelDAO(dto)); } catch (ConstraintViolationException e) { throw new AlreadyExistsException("Failed to update the level", e); } } public LevelDTO getLevel(String name) { Level level = levelRepository.findByName(name); if (level == null) { throw new NotFoundException("There's no level with name: " + name); } return createDto(level); } public String getTest(String name) { String test = levelRepository.getTestByName(name); if (test == null) { throw new NotFoundException("There's no level with name: " + name); } return test; } public String getCUT(String name) { String cut = levelRepository.getCUTByName(name); if (cut == null) { throw new NotFoundException("There's no level with name: " + name); } return cut; } public CritterRow getRow(String id) { CritterRow row = rowRepository.findCritterRowById(id); if (row == null) { throw new NotFoundException("There's no row with id: " + id); } return row; } public boolean existsLevel(String name) { return levelRepository.findByName(name) != null; } private LevelDTO createDto(Level level) { LevelDTO dto = new LevelDTO(); dto.setId(level.getId()); dto.setName(level.getName()); dto.setLevel(level.getLevel()); dto.setCUT(level.getCUT()); dto.setTest(level.getTest()); dto.setSpawn(level.getSpawn()); dto.setInit(level.getInit()); dto.setXml(level.getXml()); dto.setTower(level.getTower()); dto.setNumberOfCritters(level.getNumberOfCritters()); dto.setNumberOfHumans(level.getNumberOfHumans()); dto.setRow(level.getRow().getName()); dto.setFreeMines(level.getFreeMines()); return dto; } private Level createLevelDAO(LevelDTO dto) { Level level = new Level(); if (dto.getId() != null) { level.setId(dto.getId()); } if (dto.getName() != null) { level.setName(dto.getName()); } if (dto.getLevel() != null) { level.setLevel(dto.getLevel()); } if (dto.getCUT() != null) { level.setCUT(dto.getCUT()); } if (dto.getInit() != null) { level.setInit(dto.getInit()); } if (dto.getXml() != null) { level.setXml(dto.getXml()); } if (dto.getTest() != null) { level.setTest(dto.getTest()); } if (dto.getTower() != null) { level.setTower(dto.getTower()); } if (dto.getSpawn() != null) { level.setSpawn(dto.getSpawn()); } if (dto.getRow() != null) { level.setRow(getRow(dto.getRow())); } level.setNumberOfCritters(dto.getNumberOfCritters()); level.setNumberOfHumans(dto.getNumberOfHumans()); level.setFreeMines(dto.getFreeMines()); return level; } public List<String> getLevelNames() { List<String> list = levelRepository.getLevelNames(); Collections.sort(list, (o1, o2) -> { if(o1.startsWith("level_") && o2.startsWith("level_"));{ if(Integer.valueOf(o1.substring(6)) < Integer.valueOf(o2.substring(6))){ return -1; } else if(Integer.valueOf(o1.substring(6)) > Integer.valueOf(o2.substring(6))){ return 1; } } return 0; }); return list; } public List<MutantDTO> getMutants(String name) { String id = levelRepository.getIdByName(name); if (id == null) { throw new NotFoundException("No such level"); } Level level = new Level(id); List<String[]> mutants = mutantRepository.getCodeByLevel(level); if (mutants == null || mutants.size() == 0) { throw new NotFoundException("No mutants could be found"); } List<MutantDTO> mutantsDto = new LinkedList<MutantDTO>(); for (Object[] mutant : mutants) { MutantDTO dto = new MutantDTO((String) mutant[0], (String) mutant[1], (String) mutant[2], (String) mutant[3]); mutantsDto.add(dto); } return mutantsDto; } public String getInit(String name) { String init = levelRepository.getInitByName(name); if (init == null) { throw new NotFoundException("There's no level with name: " + name); } return init; } public List getLevelsGrouped(String cookie) { List groupedLevels = new LinkedList(); Collection<CritterRow> rows = rowRepository.getRows(); if(userRepositiory.existsByCookie(cookie)){ User user = userRepositiory.findByCookie(cookie); for (CritterRow row : rows) { HashMap map = new HashMap<String, Object>(); map.put("name", row.getName()); map.put("id", row.getId()); map.put("position", row.getPosition()); map.put("levels", levelRepository.getLevelNamesAndResultByGroup(row, user)); groupedLevels.add(map); } } else { for (CritterRow row : rows) { HashMap map = new HashMap<String, Object>(); map.put("name", row.getName()); map.put("id", row.getId()); map.put("position", row.getPosition()); map.put("levels", levelRepository.getLevelNamesAndResultByGroup(row, cookie)); groupedLevels.add(map); } } return groupedLevels; } public void storeImage(MultipartFile image) { String name = image.getOriginalFilename(); File file = new File("./images/" + name); try { file.getParentFile().mkdirs(); file.createNewFile(); image.transferTo(file.getAbsoluteFile()); } catch (IOException e) { e.printStackTrace(); } } public List<RowDTO> getRows() { Collection<CritterRow> rows = rowRepository.getRows(); List<RowDTO> rowDTOS = new LinkedList<>(); for (CritterRow row : rows) { rowDTOS.add(new RowDTO(row.getId(), row.getName(), row.getPosition())); } return rowDTOS; } }
10,139
34.704225
122
java
code-critters
code-critters-master/src/main/java/org/codecritters/code_critters/application/service/MailService.java
package org.codecritters.code_critters.application.service; /*- * #%L * Code Critters * %% * Copyright (C) 2019 Michael Gruber * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.codecritters.code_critters.web.enums.Language; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; import java.io.IOException; import java.util.Map; @Service public class MailService { @Value("${spring.mail.address}") private String email; @Value("${spring.mail.personal}") private String personal; private JavaMailSender emailSender; private final Logger logger = LogManager.getLogger(MailService.class); private static String MAILDIR = "./mail/"; @Autowired public MailService(JavaMailSender emailSender) { this.emailSender = emailSender; } private void sendMessage(MimeMessage message) { try { emailSender.send(message); } catch (MailException e) { //TODO store mail in db logger.warn(e.getMessage()); } } public void sendMessageFromTemplate(String templateName, Map<String, String> data, Language language) { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); try { helper.setTo(data.get("receiver")); helper.setSubject(TranslationsService.translate(language, data.get("subject"))); helper.setFrom(email, personal); String template = this.loadTemplate(templateName, language); for (Map.Entry<String, String> entry : data.entrySet()) { template = template.replaceAll("\\{\\{" + entry.getKey() + "\\}\\}", entry.getValue()); } helper.setText(template, true); this.sendMessage(message); } catch (IOException e) { logger.warn(e.getMessage()); } catch (MessagingException e) { //TODO store mail in db logger.warn(e.getMessage()); } } private String loadTemplate(String templateName, Language language) throws IOException { File file = new File(MAILDIR + language.toString() + "/" + templateName + ".html"); return FileUtils.readFileToString(file, "utf-8"); } }
3,411
32.45098
107
java