code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package annas.graph.io;
/**
* Gets a label for the supplied vertex.
*
* @author Sam Wilson
*
* @param <V>
*/
public interface VertexLabeller<V> {
public String getLabel(V v);
}
| Java |
package annas.graph.io;
import java.io.InputStream;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
public interface GraphImporter<V, E extends EdgeInterface<V>> {
public GraphInterface<V, E> importGraph(InputStream input,
GraphInterface<V, E> graph);
public GraphInterface<V, E> importGraph(String filename,
GraphInterface<V, E> graph);
}
| Java |
package annas.graph.io;
import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
/**
* Imports a graph from xml, as exported by XmlExporter
*
* @author Sam Wilson
*
* @param <V>
* Vertex type
* @param <E>
* Edge type
*/
public class XmlImporter<V, E extends EdgeInterface<V>> implements
GraphImporter<V, E> {
@SuppressWarnings("unchecked")
@Override
public GraphInterface<V, E> importGraph(InputStream input,
GraphInterface<V, E> graph) {
// TODO Auto-generated method stub
XMLDecoder d = new XMLDecoder(input);
Object result = d.readObject();
d.close();
graph = (GraphInterface<V, E>) result;
return graph;
}
@Override
public GraphInterface<V, E> importGraph(String filename,
GraphInterface<V, E> graph) {
try {
return this.importGraph(new BufferedInputStream(
new FileInputStream(filename)), graph);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
}
| Java |
package annas.graph.io;
import java.io.OutputStream;
import java.io.PrintWriter;
import annas.graph.DirectedGraph;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
import annas.graph.UndirectedGraph;
/**
* Export graph to the standard .DOT format @see <a
* href="http://en.wikipedia.org/wiki/DOT_language"> shown here </a>
*
* @author Sam Wilson
*
* @param <V>
* Vertex type
* @param <E>
* Edge type
*/
public class DOTExporter<V, E extends EdgeInterface<V>> implements
GraphExporter<V, E> {
/**
* Vertex labeler
*/
private VertexLabeller<V> labeller = new DefaultVertexLabeller<V>();
private boolean simple = true;
/**
* Connector
*/
private String connector = " ";
public DOTExporter(VertexLabeller<V> labeller) {
super();
this.labeller = labeller;
}
public DOTExporter() {
super();
}
/**
* {@inheritDoc}
*/
@Override
public void exportGraph(OutputStream ops, GraphInterface<V, E> graph) {
PrintWriter pw = new PrintWriter(ops);
assert (pw != null);
String indent = " ";
if (graph instanceof DirectedGraph<?, ?>) {
pw.println("digraph G { ");
this.connector = "->";
}
if (graph instanceof UndirectedGraph<?, ?>) {
pw.println("graph G { ");
this.connector = "--";
}
/*pw.println("node [ fontname = \"Arial\" \n " + "label = \"\" \n "
+ "shape = \"circle\" \n" + " width = \"0.1\" \n"
+ "height = \"0.1\" \n" + "color = \"black\" ] \n \n"
+ "edge [ color = \"black\" \n" + "weight = \"1\"]");
*/
for (V n : graph.getVertices()) {
pw.println(indent + this.labeller.getLabel(n) + ";");
}
for (V n : graph.getVertices()) {
for (E edge : graph.getEdges(n)) {
if (this.simple
&& this.labeller.getLabel(n).equals(
this.labeller.getLabel(edge.getHead()))) {
} else {
pw.println(indent + indent + this.labeller.getLabel(n)
+ " " + this.connector + " "
+ this.labeller.getLabel(edge.getHead()) + ";");
}
}
}
pw.println("}");
pw.flush();
}
/**
* {@inheritDoc}
*/
@Override
public void exportGraph(GraphInterface<V, E> graph) {
this.exportGraph(System.out, graph);
}
public String getConnector() {
return connector;
}
public void setConnector(String connector) {
this.connector = connector;
}
}
| Java |
package annas.graph.io;
import java.io.OutputStream;
import java.io.PrintWriter;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
import annas.misc.Graph6;
public class Graph6Exporter<V, E extends EdgeInterface<V>> implements
GraphExporter<V, E> {
@Override
public void exportGraph(OutputStream writer, GraphInterface<V, E> graph) {
new PrintWriter(writer, true).println(Graph6.encodeGraph(graph));
}
@Override
public void exportGraph(GraphInterface<V, E> graph) {
System.out.println(Graph6.encodeGraph(graph));
}
}
| Java |
package annas.graph.io;
import java.io.OutputStream;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
/**
* Interface for all Exporters. Exporters provide an alternative representation
* of a graph from use outside of the annas package.
*
* @author Sam Wilson
*
* @param <V>
* Vertex type
* @param <E>
* Edge type
*/
public interface GraphExporter<V, E extends EdgeInterface<V>> {
/**
* Exports the provided graph.
*
* @param writer
* Stream to output the graph to
* @param graph
* Graph to export
*/
public void exportGraph(OutputStream writer, GraphInterface<V, E> graph);
/**
* Exports the provided graph to std.
*
* @param graph
* Graph to export
*/
public void exportGraph(GraphInterface<V, E> graph);
}
| Java |
package annas.graph.io;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import annas.graph.DefaultEdge;
import annas.graph.GraphInterface;
/**
* A very rough implementation, it should be rewritten to provide sensible error
* messages.
*
* @author Sam Wilson
*
*/
public class TGFImporter implements GraphImporter<String,DefaultEdge> {
@Override
public GraphInterface<String, DefaultEdge> importGraph(InputStream input,
GraphInterface<String, DefaultEdge> graph) {
BufferedReader in = new BufferedReader(new InputStreamReader(input));
String line = null;
ArrayList<String> vertices = new ArrayList<String>();
boolean edges = false;
try {
while ((line = in.readLine()) != null) {
if (line.charAt(0) == '#') {
edges = true;
continue;
}
if (!edges) {
String str = line.substring(line.indexOf(" ")).trim();
vertices.add(str);
graph.addVertex(str);
} else {
String first = line.split(" ")[0].trim();
String second = line.split(" ")[1].trim();
graph.addEdge(vertices.get(Integer.parseInt(first) - 1),
vertices.get(Integer.parseInt(second) - 1));
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IndexOutOfBoundsException e) {
System.err.println("Incorrectly formatted tgf file");
e.printStackTrace();
}
return graph;
}
@Override
public GraphInterface<String, DefaultEdge> importGraph(String filename,
GraphInterface<String, DefaultEdge> graph) {
try {
return this.importGraph(new FileInputStream(filename), graph);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return graph;
}
}
| Java |
package annas.graph.io;
import java.beans.XMLEncoder;
import java.io.OutputStream;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
/**
* Exports the graph to xml
*
* @author Sam Wilson
*
* @param <V>
* Vertex type
* @param <E>
* Edge type
*/
public class XmlExporter<V, E extends EdgeInterface<V>> implements
GraphExporter<V, E> {
/**
* Stream to output to
*/
private OutputStream ops;
public XmlExporter() {
super();
this.ops = System.out;
}
public XmlExporter(OutputStream ops) {
super();
this.ops = ops;
}
/**
* {@inheritDoc}
*/
@Override
public void exportGraph(OutputStream pw, GraphInterface<V, E> graph) {
if (pw != null) {
this.ops = pw;
this.exportGraph(graph);
}
}
/**
* {@inheritDoc}
*/
@Override
public void exportGraph(GraphInterface<V, E> graph) {
if (this.ops != null) {
XMLEncoder encoder;
encoder = new XMLEncoder(this.ops);
encoder.writeObject(graph);
encoder.close();
}
}
}
| Java |
package annas.graph.io;
public class DefaultVertexLabeller<V> implements VertexLabeller<V> {
@Override
public String getLabel(V v) {
return v.toString();
}
}
| Java |
package annas.graph.io;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Hashtable;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
public class TGFExporter<V, E extends EdgeInterface<V>> implements
GraphExporter<V, E> {
/**
* Vertex labeller
*/
private VertexLabeller<V> labeller = new DefaultVertexLabeller<V>();
public TGFExporter(VertexLabeller<V> labeller) {
super();
this.labeller = labeller;
}
public TGFExporter() {
super();
}
/**
* {@inheritDoc}
*/
@Override
public void exportGraph(OutputStream ops, GraphInterface<V, E> graph) {
Writer writer = new PrintWriter(ops);
Hashtable<V, Integer> map = new Hashtable<V, Integer>(graph.getOrder());
int i = 1;
try {
for (V v : graph.getVertices()) {
map.put(v, i);
writer.write(i + " " + labeller.getLabel(v) + "\n");
i++;
}
writer.write("#\n");
for (E e : graph.getEdges()) {
writer.write(map.get(e.getTail()) + " " + map.get(e.getHead())
+ "\n");
}
writer.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
/**
* {@inheritDoc}
*/
@Override
public void exportGraph(GraphInterface<V, E> graph) {
this.exportGraph(System.out, graph);
}
}
| Java |
package annas.graph.io;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import annas.graph.GraphInterface;
import annas.graph.IntegerEdge;
import annas.math.Matrix;
public class Graph6Importer implements GraphImporter<Integer, IntegerEdge> {
@Override
public GraphInterface<Integer, IntegerEdge> importGraph(InputStream input,
GraphInterface<Integer, IntegerEdge> graph) {
BufferedReader in = new BufferedReader(new InputStreamReader(input));
try {
String line = in.readLine();
int[] r = StringToIntArray(line);
Matrix m = decodeGraph(r);
for (int h = 0; h < m.getMatrix().length; h++) {
graph.addVertex(h);
}
for (int i = 0; i < m.getMatrix().length; i++) {
for (int j = 0; j < i; j++) {
if (m.getMatrix()[i][j] != 0) {
graph.addEdge(i, j);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return graph;
}
@Override
public GraphInterface<Integer, IntegerEdge> importGraph(String filename,
GraphInterface<Integer, IntegerEdge> graph) {
try {
return this.importGraph(new FileInputStream(filename), graph);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return graph;
}
private Matrix decodeGraph(int[] i) {
long nuNodes = decodeN(i);
String a = "";
if (nuNodes <= 62) {
a = decodeR(Arrays.copyOfRange(i, 1, i.length));
} else if (nuNodes > 62 && nuNodes <= 258047) {
a = decodeR(Arrays.copyOfRange(i, 4, i.length));
} else {
a = decodeR(Arrays.copyOfRange(i, 8, i.length));
}
int[][] adj = new int[(int) nuNodes][(int) nuNodes];
int q = 0;
for (int w = 0; w < nuNodes; w++) {
for (int e = 0; e < w; e++) {
adj[w][e] = Integer.parseInt((a.charAt(q)) + "");
q++;
}
}
return new Matrix(adj);
}
private String decodeR(int[] bytes) {
String retval = "";
for (int i = 0; i < bytes.length; i++) {
retval += padL(Integer.toBinaryString(bytes[i] - 63), 6);
}
return retval;
}
private long decodeN(int i[]) {
if (i.length > 2 && i[0] == 126 && i[1] == 126) {
return Long.parseLong(decodeR(new int[] { i[2], i[3], i[4], i[5],
i[6], i[7] }), 2);
} else if (i.length > 1 && i[0] == 126) {
return Long.parseLong(decodeR(new int[] { i[1], i[2], i[3] }), 2);
} else {
return i[0] - 63;
}
}
private int[] StringToIntArray(String str) {
int[] v = new int[str.length()];
for (int l = 0; l < str.length(); l++) {
v[l] = str.charAt(l);
}
return v;
}
private String padL(String str, int h) {
String retval = "";
for (int i = 0; i < h - str.length(); i++) {
retval += "0";
}
return retval + str;
}
}
| Java |
package annas.graph;
import java.io.Serializable;
/**
* Interface of all edge used in a Graph
*
* @author Sam Wilson
*
* @param <V>
* Vertex type
*/
public interface EdgeInterface<V> extends Serializable {
/**
* Gets the head of the Edge
*
* @return Vertex at the head of the edge
*/
public V getHead();
/**
* Gets the tail of the Edge
*
* @return Vertex at the tail of the edge
*/
public V getTail();
/**
* Set head of the edge
*
* @param vertex
*/
public void setHead(V vertex);
/**
* Set tail of the edge
*
* @param vertex
*/
public void setTail(V vertex);
/**
* Checks if the edge is incident to the given vertex
*
* @param vertex
* @return True if the edge is incident to the vertex, otherwise false
*/
public boolean isIncident(V vertex);
/**
* Retrieves the other end point to the end.
*
* @param vertex
* @return the other end of an edge
*/
public V getOtherEndpoint(V vertex);
}
| Java |
package annas.graph.classifier;
import java.util.Arrays;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
import annas.graph.util.Utilities;
/**
* Recognizes Split graphs from the degree sequence characteristic.
*
* @author Sam Wilson
*
* @param <V>
* @param <E>
*/
public class SplitRecogniser<V, E extends EdgeInterface<V>> implements
Classifier<V, E> {
@Override
public boolean classify(GraphInterface<V, E> graph) {
if (graph.getOrder() == 0) {
return true;
}
long[] ds = Utilities.getDegreeSequence(graph);
Arrays.sort(ds);
reverse(ds);
int m = 0;
for (int i = 1; i <= ds.length; i++) {
if (ds[i - 1] >= i) {
m = i - 1;
} else {
break;
}
}
long sum = sum(ds, 0, m + 1);
long f = m * (m + 1);
long l = sum(ds, m + 1, ds.length);
return sum == f + l;
}
private long sum(long[] d, int start, int end) {
long retval = 0;
for (int i = start; i < end; i++) {
retval += d[i];
}
return retval;
}
private void reverse(long[] d) {
for (int i = 0; i < d.length / 2; i++) {
long tmp = d[i];
d[i] = d[d.length - i - 1];
d[d.length - i - 1] = tmp;
}
}
}
| Java |
package annas.graph.classifier;
import java.util.Hashtable;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
/**
* Detects cycles in a graph, this classes uses a depth first search to discover
* cycles.
*
* @author Sam Wilson
*
* @param <V>
* Vertex type
* @param <E>
* Edge type
*/
public class Acyclic<V, E extends EdgeInterface<V>> implements Classifier<V, E> {
/**
* Graph to detect cycles in
*/
protected GraphInterface<V, E> graph;
private Hashtable<V, Integer> map;
public Acyclic() {
super();
this.map = new Hashtable<V, Integer>();
}
@Override
public boolean classify(GraphInterface<V, E> graph) {
return !containsCycle();
}
/**
* Executes the algorithm
*
* @return true if the algorithm discovers a cycles
*/
private boolean containsCycle() {
for (V node : this.graph.getVertices())
map.put(node, -1);
for (V node : this.graph.getVertices()) {
if (this.map.get(node) == -1) {
if (this.visit(node)) {
return true;
}
}
}
return false;
}
private boolean visit(V node) {
this.map.put(node, 0);
for (E arc : this.graph.getEdges(node)) {
Integer h = this.map.get(arc.getHead());
if (h == 0) {
return true;
} else if (h == -1) {
if (this.visit(arc.getHead())) {
return true;
}
}
}
this.map.put(node, 1);
return false;
}
}
| Java |
package annas.graph.classifier;
import java.util.Collection;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
import annas.graph.util.Utilities;
public class DisjointCliqueRecogniser<V, E extends EdgeInterface<V>> implements
Classifier<V, E> {
/**
* Takes a simple undirected graph and returns true if it is a collection
* of disjoint cliques in linear time.
*/
@Override
public boolean classify(GraphInterface<V, E> graph) {
Collection<Collection<V>> C = Utilities.getConnectedComponents(graph);
for (Collection<V> c : C) {
int d = c.size() - 1;
for (V v : c) {
if (graph.getDegree(v) != d) {
return false;
}
}
}
return true;
}
}
| Java |
package annas.graph.classifier;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
public interface Classifier<V, E extends EdgeInterface<V>> {
/**
* Classifies if the graph has a property.
*
* @param graph
* @return true is the graph has the property.
*/
public boolean classify(GraphInterface<V, E> graph);
}
| Java |
package annas.graph.classifier;
import java.util.Collection;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
import annas.graph.util.Utilities;
import annas.graph.util.traverse.BreadthFirst;
/**
* Recognizes undirected bipartite graphs
* @author scsswi
*
* @param <V>
* @param <E>
*/
public class BipartiteRecogniser<V, E extends EdgeInterface<V>> implements
Classifier<V, E> {
@Override
public boolean classify(GraphInterface<V, E> graph) {
boolean retval = true;
for(Collection<V> c : Utilities.getConnectedComponents(graph)){
retval &= new BreadthFirst<V, E>(graph,c.iterator().next()).isBipartite();
}
return retval;
}
}
| Java |
package annas.graph.classifier;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
import annas.graph.util.Utilities;
import annas.math.Matrix;
/**
*
* @author scsswi
*
* @param <V>
* @param <E>
*/
public class TriangleFreeRecogniser<V, E extends EdgeInterface<V>> implements
Classifier<V, E> {
@Override
public boolean classify(GraphInterface<V, E> graph) {
Matrix m = Utilities.getAdjacencyMatrix(graph);
m = m.pow(3);
if (m.Trace() != 0)
return false;
return true;
}
}
| Java |
package annas.graph.classifier;
import java.util.ArrayList;
import java.util.List;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
import annas.graph.util.traverse.LexBFS;
public class ChordalRecogniser<V, E extends EdgeInterface<V>> implements
Classifier<V, E> {
public boolean check(GraphInterface<V, E> graph) {
LexBFS<V, E> lex = new LexBFS<V, E>(graph);
lex.run();
List<V> out = lex.getOutput();
System.out.println(out);
for (int i = 1; i < out.size(); i++) {
V nearest = getNearestNeighbour(graph, out, out.get(i));
if (nearest != null) {
System.out.println(out.get(i) + " " + nearest);
List<V> v_n = this.neighboursOf(graph, out, out.get(i));
v_n.remove(nearest);
List<V> w_n = this.neighboursOf(graph, out, nearest);
System.out.println("V_n " + v_n);
System.out.println("W_n " + w_n);
if (!w_n.containsAll(v_n) && !v_n.isEmpty() && !w_n.isEmpty()) {
System.out.println("FALSE");
return false;
}
}
}
System.out.println("TRUE");
return true;
}
private List<V> neighboursOf(GraphInterface<V, E> graph, List<V> out, V v) {
ArrayList<V> l = new ArrayList<V>();
int i = out.indexOf(v);
for (int j = i - 1; j >= 0; j--) {
V ret = out.get(j);
if (graph.getEdges(v, ret).size() != 0) {
l.add(ret);
}
}
return l;
}
private V getNearestNeighbour(GraphInterface<V, E> graph, List<V> out, V n) {
int i = out.indexOf(n);
for (int j = i; j >= 0; j--) {
V ret = out.get(j);
if (graph.getEdges(n, ret).size() != 0) {
return ret;
}
}
return null;
}
@Override
public boolean classify(GraphInterface<V, E> graph) {
return check(graph);
}
}
| Java |
package annas.graph.classifier;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
public class CompleteRecogniser<V, E extends EdgeInterface<V>> implements
Classifier<V, E> {
@Override
public boolean classify(GraphInterface<V, E> graph) {
for (V v : graph.getVertices()) {
for (V u : graph.getVertices()) {
if (u != v) {
if (graph.getEdges(v, u).isEmpty()) {
return false;
}
}
}
}
return true;
}
}
| Java |
package annas.graph.classifier;
import java.util.Arrays;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
import annas.graph.util.Utilities;
public class ThresholdRecogniser<V, E extends EdgeInterface<V>> implements
Classifier<V, E> {
@Override
public boolean classify(GraphInterface<V, E> graph) {
long[] ds = Utilities.getDegreeSequence(graph);
Arrays.sort(ds);
while (ds.length > 0) {
if (ds[0] <= 0) {
ds = Arrays.copyOfRange(ds, 1, ds.length);
continue;
}
long n = ds.length;
if (ds[ds.length - 1] != n - 1) {
return false;
} else {
ds = Arrays.copyOfRange(ds, 0, ds.length - 1);
this.decrementBy(ds, 1);
}
}
return true;
}
private void decrementBy(long[] ds, long decrementBy) {
for (int i = 0; i < ds.length; i++) {
ds[i] = ds[i] - decrementBy;
}
}
}
| Java |
package annas.graph.classifier;
import java.util.Collection;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
import annas.graph.util.Utilities;
public class ConnectedRecogniser<V, E extends EdgeInterface<V>> implements
Classifier<V, E> {
@Override
public boolean classify(GraphInterface<V, E> graph) {
Collection<Collection<V>> c = Utilities.getConnectedComponents(graph);
if (c.size() == 1 || graph.getOrder() == 0) {
return true;
}
return false;
}
}
| Java |
package annas.graph.classifier;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
/**
* Classifies if a graph is Eulerian.
* @author scsswi
*
* @param <V>
* @param <E>
*/
public class Eulerian<V, E extends EdgeInterface<V>> implements
Classifier<V, E> {
@Override
public boolean classify(GraphInterface<V, E> graph) {
boolean eulerian = true;
for (V vertex : graph.getVertices()) {
eulerian &= graph.getEdges(vertex).size() % 2 == 0;
}
return eulerian;
}
}
| Java |
package annas.graph.classifier;
import java.util.ArrayList;
import java.util.List;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
import annas.graph.SimpleUndirectedGraph;
/**
* Implementation of Cai's FPT algorithm for recognizing the parameterized class
* C+kv. Note the class C should have a finite forbidden set, if you wish the
* algorithm to have a "good" running time.
*
* @author Sam Wilson
*
* @param <V>
* @param <E>
*/
public class AlmostC<V, E extends EdgeInterface<V>> implements Classifier<V, E> {
private int k;
/**
* This recognises the base class, the class should have a finite forbidden
* set.
*/
private Classifier<V, E> recogniser;
public AlmostC(Classifier<V, E> recogniser, int k) {
super();
this.k = k;
this.recogniser = recogniser;
}
@Override
public boolean classify(GraphInterface<V, E> graph) {
try {
return this.recognise((SimpleUndirectedGraph<V, E>) graph, this.k);
} catch (ClassCastException e) {
return false;
}
}
private boolean recognise(SimpleUndirectedGraph<V, E> graph, int k) {
if (this.recogniser.classify(graph)) {
return true;
} else if (k == 0) {
return false;
}
SimpleUndirectedGraph<V, E> tmp = this.copyGraph(graph);
SimpleUndirectedGraph<V, E> tmp1;
List<V> Vs = new ArrayList<V>();
/*
* find a minimal forbidden graph contains within the input
*/
for (V v : graph.getVertices()) {
tmp1 = this.copyGraph(tmp);
tmp.removeVertex(v);
if (this.recogniser.classify(tmp)) {
Vs.add(v);
tmp = tmp1;
}
}
for (V u : Vs) {
tmp = this.copyGraph(graph);
tmp.removeVertex(u);
if (this.recognise(tmp, (k - 1))) {
return true;
}
}
return false;
}
/**
* Makes a copy of the graph uses the same vertices and edge objects but
* makes a copy of the structure.
*
* @param graph
* @return a copy of the given graph
*/
private SimpleUndirectedGraph<V, E> copyGraph(
SimpleUndirectedGraph<V, E> graph) {
SimpleUndirectedGraph<V, E> retval = new SimpleUndirectedGraph<V, E>(
graph.getEdgeFactory());
retval.addVertices(graph.getVertices());
for (E e : graph.getEdges()) {
retval.addEdge(e.getTail(), e.getHead());
}
return retval;
}
}
| Java |
package annas.graph.classifier;
import java.util.Collection;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
import annas.graph.util.Utilities;
public class TreeRecogniser<V, E extends EdgeInterface<V>> implements
Classifier<V, E> {
@Override
public boolean classify(GraphInterface<V, E> graph) {
Collection<?> comps = Utilities.getConnectedComponents(graph);
return comps.size() == 1 && new Acyclic<V, E>().classify(graph);
}
}
| Java |
package annas.graph.classifier;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
public class EdgelessRecogniser<V, E extends EdgeInterface<V>> implements
Classifier<V, E> {
@Override
public boolean classify(GraphInterface<V, E> graph) {
return graph.getEdges().isEmpty() ? true : false;
}
}
| Java |
package annas.graph;
@SuppressWarnings("serial")
public class SimpleUndirectedGraph<V, E extends EdgeInterface<V>> extends
UndirectedGraph<V, E> {
public SimpleUndirectedGraph(Class<E> edgeClass) {
super(edgeClass);
this.allowloops = false;
this.allowparallelEdges = false;
}
public SimpleUndirectedGraph(EdgeFactory<V, E> edgeFactory) {
super(edgeFactory);
this.allowloops = false;
this.allowparallelEdges = false;
}
}
| Java |
package annas.math.combinatorics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
*
*
* Adapted from <a
* href="http://code.google.com/p/combinatoricslib/">combinatoricslib</a>
*
* @author Dmytro Paukov
* @author Sam Wilson
* @see PermutationIterator
* @param <T>
* Type of the elements in the permutations
*/
public class PermutationGenerator<T> implements Iterable<List<T>> {
/**
* Initial vector
*/
protected final List<T> originalVector;
/**
* Constructor
*
* @param originalVector
* Vector which is used for permutation generation
*/
public PermutationGenerator(Collection<T> originalVector) {
this.originalVector = new ArrayList<T>(originalVector);
}
/**
* Returns core permutation
*
*/
public List<T> getOriginalVector() {
return this.originalVector;
}
/**
* Returns the number of all generated permutations
*
*/
public long getNumberOfGeneratedObjects() {
if (this.originalVector.size() == 0)
return 0;
return CombinatoricUtil.factorial(this.originalVector.size());
}
/**
* Creates an iterator
*
*/
@Override
public Iterator<List<T>> iterator() {
return new PermutationIterator<T>(this);
}
}
| Java |
package annas.math.combinatorics;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
/**
* Iterator for the permutation generator
*
* Adapted from <a
* href="http://code.google.com/p/combinatoricslib/">combinatoricslib</a>
*
* @author Dmytro Paukov
* @author Sam Wilson
* @see PermutationGenerator
* @param <T>
* Type of elements in the permutations
*/
public class PermutationIterator<T> implements Iterator<List<T>> {
/**
* Generator
*/
protected final PermutationGenerator<T> generator;
/**
* Current permutation
*/
protected List<T> currentPermutation;
/**
* Current index of current permutation
*/
protected long currentIndex = 0;
/**
* Number of elements in the permutations
*/
protected final int length;
/**
* Internal data
*/
private int[] pZ = null;
private int[] pP = null;
private int[] pD = null;
private int m = 0;
private int w = 0;
private int pm = 0;
private int dm = 0;
private int zpm = 0;
/**
* Constructor
*
* @param generator
* Permutation generator
*/
public PermutationIterator(PermutationGenerator<T> generator) {
this.generator = generator;
this.length = generator.getOriginalVector().size();
this.currentPermutation = new ArrayList<T>(
generator.getOriginalVector());
this.pZ = new int[length + 2];
this.pP = new int[length + 2];
this.pD = new int[length + 2];
init();
}
/**
* Initialize the iteration process
*/
private void init() {
this.currentIndex = 0;
this.m = 0;
this.w = 0;
this.pm = 0;
this.dm = 0;
this.zpm = 0;
for (int i = 1; i <= this.length; i++) {
this.pP[i] = i;
this.pZ[i] = i;
this.pD[i] = -1;
}
this.pD[1] = 0;
this.pZ[this.length + 1] = m = this.length + 1;
this.pZ[0] = this.pZ[this.length + 1];
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#hasNext()
*/
@Override
public boolean hasNext() {
return this.m != 1;
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#next()
*/
@Override
public List<T> next() {
if (!this.hasNext())
throw new NoSuchElementException();
for (int i = 1; i <= this.length; i++) {
int index = this.pZ[i] - 1;
this.currentPermutation.set(i - 1, this.generator
.getOriginalVector().get(index));
}
this.m = this.length;
while (this.pZ[this.pP[this.m] + this.pD[this.m]] > this.m) {
this.pD[this.m] = -this.pD[this.m];
this.m--;
}
this.pm = this.pP[this.m];
this.dm = this.pm + this.pD[this.m];
this.w = this.pZ[this.pm];
this.pZ[this.pm] = this.pZ[this.dm];
this.pZ[this.dm] = this.w;
this.zpm = this.pZ[this.pm];
this.w = this.pP[this.zpm];
this.pP[this.zpm] = this.pm;
this.pP[this.m] = this.w;
this.currentIndex++;
return new ArrayList<T>(this.currentPermutation);
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#remove()
*/
@Override
public void remove() {
throw new UnsupportedOperationException("Method not supported");
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "PermutationIterator [currentIndex=" + currentIndex
+ ", currentPermutation=" + currentPermutation + "]";
}
}
| Java |
package annas.math.combinatorics;
public class CombinatoricUtil {
public static long gcd(long l, long m) {
if (l == 0)
return m;
if (m == 0)
return l;
if (l == m)
return l;
if (l == 1 | m == 1)
return 1;
if ((l % 2 == 0) & (m % 2 == 0))
return 2 * gcd(l / 2, m / 2);
if ((l % 2 == 0) & (m % 2 != 0))
return gcd(l / 2, m);
if ((l % 2 != 0) & (m % 2 == 0))
return gcd(l, m / 2);
return gcd(m, Math.abs(l - m));
}
public static long lcm(long l, long m) {
return (l * m) / gcd(l, m);
}
public static long nChooseK(long n, long k) {
if (k == 0) {
return 1;
}
if (n == 0) {
return 0;
}
return nChooseK(n - 1, k - 1) + nChooseK(n - 1, k);
/**
* Swap for a more effective way of calculating n choose k. return
* factorial(n) / (factorial(k) * factorial(n - k));
*/
}
public static long permutations(long n, long k) {
return (long) Math.pow(n, k);
}
public static long permutationsNoRepetition(long n, long k) {
return factorial(n) / factorial(n - k);
}
public static long factorial(long n) {
long val = 1;
for (int i = 1; i <= n; i++) {
val *= i;
}
return val;
}
public static long catalan(long n) {
return nChooseK(2 * n, n) - nChooseK(2 * n, n + 1);
// return factorial(2 * n) / (factorial(n + 1) * factorial(n));
}
public static long sterling(long n, long k) {
if (n == 0 && k == 0) {
return 1;
}
if (n == 0 || k == 0) {
return 0;
}
return k * sterling(n - 1, k) + sterling(n - 1, k - 1);
}
/**
* Returns the number of non-crossing partitions of n elements into k parts
*
* @param n
* @param k
* @return number of non-crossing partitions of an n element set into k parts
*/
public static long narayana(long n, long k) {
return CombinatoricUtil.nChooseK(n, k)
* CombinatoricUtil.nChooseK(n, k - 1) / n;
}
}
| Java |
package annas.math.combinatorics;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Iterator of powerset for a ground set.
*
* Order is set by Constructor
*
* For reverse order see ReversePowersetIterator
*
* @author Sam
*
* @param <T>
* Collection type
*/
public final class PowersetIterator<T> implements Iterator<Collection<T>> {
private BigInteger index = BigInteger.ZERO;
private BigInteger numberOfSubsets;
private ArrayList<T> groundSet;
private boolean smallestFirst;
/**
* Creates a new power set iterator starting with the empty set.
* @param input
*/
public PowersetIterator(Collection<T> input) {
super();
this.groundSet = new ArrayList<T>(input.size());
this.groundSet.addAll(input);
this.numberOfSubsets = BigInteger.valueOf((long) Math.pow(2, groundSet
.size()));
this.smallestFirst = true;
}
/**
* Creates a new power set iterator starting with the ground set.
* @param input
* @param reverseOrder
*/
public PowersetIterator(Collection<T> input, boolean reverseOrder) {
super();
this.groundSet = new ArrayList<T>(input.size());
this.groundSet.addAll(input);
this.numberOfSubsets = BigInteger.valueOf((long) Math.pow(2, groundSet
.size()));
this.smallestFirst = !reverseOrder;
}
/*
* (non-Javadoc)
* @see java.util.Iterator#hasNext()
*/
@Override
public boolean hasNext() {
return index.compareTo(numberOfSubsets) < 0;
}
/*
* (non-Javadoc)
* @see java.util.Iterator#next()
*/
@Override
public Collection<T> next() {
if(!hasNext()){
throw new NoSuchElementException();
}
Collection<T> ret = new HashSet<T>();
for (int i = 0; i < groundSet.size(); i++) {
if (this.smallestFirst) {
if (index.testBit(i))
ret.add(groundSet.get(i));
} else {
if (!index.testBit(i))
ret.add(groundSet.get(i));
}
}
index = index.add(BigInteger.ONE);
return ret;
}
/*
* Method not supported
* (non-Javadoc)
* @see java.util.Iterator#remove()
*/
@Override
public void remove() {
throw new UnsupportedOperationException("Method not supported");
}
} | Java |
package annas.math.combinatorics;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Iterator for the simple combination generator
*
* Adapted from <a
* href="http://code.google.com/p/combinatoricslib/">combinatoricslib</a>
*
* @author Dmytro Paukov
* @author Sam Wilson
* @see List
* @see SimpleCombinationGenerator
* @param <T>
* Type of the elements in the combinations
*/
public class SimpleCombinationIterator<T> implements Iterator<List<T>> {
/**
* Generator
*/
protected final SimpleCombinationGenerator<T> generator;
/**
* Current simple combination
*/
protected List<T> currentSimpleCombination = null;
/**
* Index of the current combination
*/
protected long currentIndex = 0;
/**
* Size of the original vector/set
*/
protected final int lengthN;
/**
* Size of the generated combination.
*/
protected final int lengthK;
/**
* Helper array
*/
private int[] bitVector = null;
/**
* Criteria to stop iteration
*/
private int endIndex = 0;
/**
* Constructor
*
* @param generator
* Generator of the simple combinations
*/
public SimpleCombinationIterator(SimpleCombinationGenerator<T> generator) {
this.generator = generator;
this.lengthN = this.generator.getOriginalVector().size();
this.lengthK = this.generator.getCombinationLength();
this.currentSimpleCombination = new ArrayList<T>();
this.bitVector = new int[this.lengthK + 1];
this.init();
}
/**
* Initialization
*/
private void init() {
for (int i = 0; i <= this.lengthK; i++) {
this.bitVector[i] = i;
}
if (this.lengthN > 0) {
this.endIndex = 1;
}
this.currentIndex = 0;
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#hasNext()
*/
@Override
public boolean hasNext() {
return !((this.endIndex == 0) || (this.lengthK > this.lengthN));
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#next()
*/
@Override
public List<T> next() {
this.currentIndex++;
for (int i = 1; i <= this.lengthK; i++) {
final int index = this.bitVector[i] - 1;
if (this.generator.getOriginalVector().size() > 0) {
try {
this.currentSimpleCombination.set(i - 1, this.generator
.getOriginalVector().get(index));
} catch (final IndexOutOfBoundsException ex) {
this.currentSimpleCombination.add(i - 1, this.generator
.getOriginalVector().get(index));
}
}
}
this.endIndex = this.lengthK;
while (this.bitVector[this.endIndex] == ((this.lengthN - this.lengthK) + this.endIndex)) {
this.endIndex--;
if (this.endIndex == 0) {
break;
}
}
this.bitVector[this.endIndex]++;
for (int i = this.endIndex + 1; i <= this.lengthK; i++) {
this.bitVector[i] = this.bitVector[i - 1] + 1;
}
// return the current combination
return new ArrayList<T>(this.currentSimpleCombination);
}
/*
* (non-Javadoc)
*
* @see java.util.Iterator#remove()
*/
@Override
public void remove() {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "SimpleCombinationIterator=[#" + this.currentIndex + ", "
+ this.currentSimpleCombination + "]";
}
}
| Java |
package annas.math.combinatorics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* Adapted from <a
* href="http://code.google.com/p/combinatoricslib/">combinatoricslib</a>
*
* @author Dmytro Paukov
* @author Sam Wilson
* @see SimpleCombinationIterator
* @param <T>
* Type of elements in the combination
*/
public class SimpleCombinationGenerator<T> implements Iterable<List<T>> {
protected final List<T> originalVector;
protected final int combinationLength;
/**
* Constructor
*
* @param originalVector
* Original vector which is used for generating the combination
* @param combinationsLength
* Length of the combinations
*/
public SimpleCombinationGenerator(Collection<T> originalVector,
int combinationsLength) {
this.originalVector = new ArrayList<T>(originalVector);
this.combinationLength = combinationsLength;
}
/**
* Returns the original vector/set
*
* @return Returns the originalVector.
*/
public List<T> getOriginalVector() {
return this.originalVector;
}
/**
* Returns the length of the combinations
*
* @return Returns the combinationLength.
*/
public int getCombinationLength() {
return this.combinationLength;
}
/**
* Returns the number of the generated combinations
*/
public long getNumberOfGeneratedObjects() {
return CombinatoricUtil.nChooseK(this.originalVector.size(),
this.combinationLength);
}
/**
* Creates an iterator of the simple combinations (without repetitions)
*/
@Override
public Iterator<List<T>> iterator() {
return new SimpleCombinationIterator<T>(this);
}
}
| Java |
package annas.math;
/**
* Calculates the optimal parameterisation for matrix chain product. Implements
* the Dynamic programming algorithm outlined in Introduction to algorithms (MIT
* press)
*
* @author Sam Wilson
*/
public class MatrixOrderOptimization {
/**
* Matrices (in order)
*/
private Matrix[] matrices;
/**
* Minimum number of multiplications to multiply each subsequence
*/
private int[][] m;
/**
* How to parenthesis the sequence of matrices.
*/
private int[][] s;
/**
* Finds the optimal solution for multiplying the sequence of matrices.
*
* @param p
*/
public MatrixOrderOptimization(Matrix[] p) {
this.matrices = p;
int[] i = new int[p.length + 1];
i[0] = p[0].getMatrix().length;
for (int j = 0; j < p.length; j++) {
i[j + 1] = p[j].getMatrix()[0].length;
}
matrixChainOrder(i);
}
private void matrixChainOrder(int... p) {
int n = p.length - 1;
m = new int[n][n];
s = new int[n][n];
for (int i = 0; i < n; i++) {
m[i] = new int[n];
m[i][i] = 0;
s[i] = new int[n];
}
for (int ii = 1; ii < n; ii++) {
for (int i = 0; i < n - ii; i++) {
int j = i + ii;
m[i][j] = Integer.MAX_VALUE;
for (int k = i; k < j; k++) {
int q = m[i][k] + m[k + 1][j] + p[i] * p[k + 1] * p[j + 1];
if (q < m[i][j]) {
m[i][j] = q;
s[i][j] = k;
}
}
}
}
System.out.println(toString());
}
/**
* Computes the product of the sequence of matrices.
*
* @return product of the sequence
*/
public Matrix multiplyChain() {
return mmo(s, 0, s.length - 1);
}
private Matrix mmo(int[][] s, int i, int j) {
if (i == j) {
return this.matrices[i];
}
Matrix a = mmo(s, i, s[i][j]);
Matrix b = mmo(s, s[i][j] + 1, j);
try {
return a.MultiplyMatrix(b);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return null;
}
} | Java |
package annas.math;
public class Complex {
/**
* Real part
*/
private double r;
/**
* Imaginary part
*/
private double i;
/**
* Constructs the complex number z = u + i*v
*
* @param u
* @param v
*/
public Complex(double u, double v) {
this.r = u;
this.i = v;
}
/**
* Real part of this Complex number (the x-coordinate in rectangular
* coordinates).
*
* @return real part of the complex number
*/
public double real() {
return this.r;
}
/**
* Imaginary part of this Complex number (the y-coordinate in rectangular
* coordinates).
*
* @return Im[z] where z is this Complex number.
*/
public double imag() {
return this.i;
}
/**
* Modulus of this Complex number (the distance from the origin in polar
* coordinates).
*
* @return |z| where z is this Complex number.
*/
public double mod() {
if (r != 0 || i != 0) {
return Math.sqrt(this.r * this.r + this.i * this.i);
} else {
return 0d;
}
}
/**
* Argument of this Complex number (the angle in radians with the x-axis in
* polar coordinates).
*
* @return arg(z) where z is this Complex number.
*/
public double arg() {
return Math.atan2(this.i, this.r);
}
/**
* Complex conjugate of this Complex number (the conjugate of x+i*y is
* x-i*y).
*
* @return z-bar where z is this Complex number.
*/
public Complex conj() {
return new Complex(this.r, -this.i);
}
/**
* Addition of Complex numbers (doesn't change this Complex number). <br>
* (x+i*y) + (s+i*t) = (x+s)+i*(y+t).
*
* @param w
* is the number to add.
* @return z+w where z is this Complex number.
*/
public Complex add(Complex w) {
return new Complex(this.r + w.real(), this.i + w.imag());
}
/**
* Subtraction of Complex numbers (doesn't change this Complex number). <br>
* (x+i*y) - (s+i*t) = (x-s)+i*(y-t).
*
* @param w
* is the number to subtract.
* @return z-w where z is this Complex number.
*/
public Complex subtract(Complex w) {
return new Complex(this.r - w.real(), this.i - w.imag());
}
/**
* Complex multiplication (doesn't change this Complex number).
*
* @param w
* is the number to multiply by.
* @return z*w where z is this Complex number.
*/
public Complex multiply(Complex w) {
return new Complex(this.r * w.real() - this.i * w.imag(), this.r
* w.imag() + this.i * w.real());
}
/**
* Division of Complex numbers (doesn't change this Complex number). <br>
* (x+i*y)/(s+i*t) = ((x*s+y*t) + i*(y*s-y*t)) / (s^2+t^2)
*
* @param w
* is the number to divide by
* @return new Complex number z/w where z is this Complex number
*/
public Complex divide(Complex w) {
double den = w.real() * w.real() + w.imag() * w.imag();
return new Complex((this.r * w.real() + this.i * w.imag()) / den,
(this.i * w.real() - this.r * w.imag()) / den);
}
/**
* Complex exponential (doesn't change this Complex number).
*
* @return exp(z) where z is this Complex number.
*/
public Complex exp() {
return new Complex(Math.exp(this.r) * Math.cos(this.i),
Math.exp(this.r) * Math.sin(this.i));
}
/**
* Principal branch of the Complex logarithm of this Complex number.
* (doesn't change this Complex number). The principal branch is the branch
* with -pi < arg <= pi.
*
* @return log(z) where z is this Complex number.
*/
public Complex log() {
return new Complex(Math.log(this.mod()), this.arg());
}
/**
* Complex square root (doesn't change this complex number). Computes the
* principal branch of the square root, which is the value with 0 <= arg <
* pi.
*
* @return sqrt(z) where z is this Complex number.
*/
public Complex sqrt() {
double r = Math.sqrt(this.mod());
double theta = this.arg() / 2;
return new Complex(r * Math.cos(theta), r * Math.sin(theta));
}
// Real cosh function (used to compute complex trig functions)
private double cosh(double theta) {
return (Math.exp(theta) + Math.exp(-theta)) / 2;
}
// Real sinh function (used to compute complex trig functions)
private double sinh(double theta) {
return (Math.exp(theta) - Math.exp(-theta)) / 2;
}
/**
* Sine of this Complex number (doesn't change this Complex number). <br>
* sin(z) = (exp(i*z)-exp(-i*z))/(2*i).
*
* @return sin(z) where z is this Complex number.
*/
public Complex sin() {
return new Complex(cosh(this.i) * Math.sin(this.r), sinh(this.i)
* Math.cos(this.r));
}
/**
* Cosine of this Complex number (doesn't change this Complex number). <br>
* cos(z) = (exp(i*z)+exp(-i*z))/ 2.
*
* @return cos(z) where z is this Complex number.
*/
public Complex cos() {
return new Complex(cosh(this.i) * Math.cos(this.r), -sinh(this.i)
* Math.sin(this.r));
}
/**
* Hyperbolic sine of this Complex number (doesn't change this Complex
* number). <br>
* sinh(z) = (exp(z)-exp(-z))/2.
*
* @return sinh(z) where z is this Complex number.
*/
public Complex sinh() {
return new Complex(sinh(this.r) * Math.cos(this.i), cosh(this.r)
* Math.sin(this.i));
}
/**
* Hyperbolic cosine of this Complex number (doesn't change this Complex
* number). <br>
* cosh(z) = (exp(z) + exp(-z)) / 2.
*
* @return cosh(z) where z is this Complex number.
*/
public Complex cosh() {
return new Complex(cosh(this.r) * Math.cos(this.i), sinh(this.r)
* Math.sin(this.i));
}
/**
* Tangent of this Complex number (doesn't change this Complex number). <br>
* tan(z) = sin(z)/cos(z).
*
* @return tan(z) where z is this Complex number.
*/
public Complex tan() {
return (this.sin()).divide(this.cos());
}
/**
* Negative of this complex number (chs stands for change sign). This
* produces a new Complex number and doesn't change this Complex number. <br>
* -(x+i*y) = -x-i*y.
*
* @return -z where z is this Complex number.
*/
public Complex chs() {
return new Complex(-this.r, -this.i);
}
/**
* String representation of this Complex number.
*
* @return x+i*y, x-i*y, x, or i*y as appropriate.
*/
@Override
public String toString() {
if (this.r != 0 && this.i > 0) {
return this.r + "+" + this.i + "i";
}
if (this.r != 0 && this.i < 0) {
return this.r + "-" + (-this.i) + "i";
}
if (this.i == 0) {
return String.valueOf(this.r);
}
if (this.r == 0) {
return this.i + "i";
}
// shouldn't get here (unless Inf or NaN)
return this.r + "+i*" + this.i;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(i);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(r);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Complex other = (Complex) obj;
if (Double.doubleToLongBits(i) != Double.doubleToLongBits(other.i))
return false;
if (Double.doubleToLongBits(r) != Double.doubleToLongBits(other.r))
return false;
return true;
}
}
| Java |
package annas.math;
import java.text.DecimalFormat;
import java.util.concurrent.Semaphore;
public class Matrix {
/**
* Enables debug (prints a lot to stdout)
*/
private final boolean DEBUG = false;
/**
* Enables info (prints to stdout)
*/
private final boolean INFO = false;
private int iDF = 0;
/**
* Representation of matrix
*/
private double[][] matrix;
/**
* Creates a square matrix of size x size.
*
* @param size
* of matrix
*/
public Matrix(int size) {
matrix = new double[size][size];
}
/**
* Creates a matrix of sizeY x sizeX
*
* @param sizeX
* Number of Columns
* @param sizeY
* Number of rows
*/
public Matrix(int sizeX, int sizeY) {
matrix = new double[sizeY][sizeX];
}
/**
* Create a matrix from an array. This constructor copies the values of the
* array.
*
* @param m
*/
public Matrix(double[][] m) {
this.matrix = new double[m.length][m[0].length];
if (m.length == matrix.length && m[0].length == matrix[0].length) {
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
this.matrix[i][j] = m[i][j];
}
}
}
}
/**
* Create a matrix from an array. This constructor copies the values of the
* array.
*
* @param m
*/
public Matrix(int[][] m) {
this.matrix = new double[m.length][m[0].length];
if (m.length == matrix.length && m[0].length == matrix[0].length) {
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
this.matrix[i][j] = m[i][j];
}
}
}
}
/**
* Set the values of the matrix from a double array. This method check the
* size of the array.
*
* @param m
*/
public void SetMatrix(double[][] m) {
if (m.length == matrix.length && m[0].length == matrix[0].length) {
this.matrix = m;
}
}
/**
* Gets the 2 dimensional array representing the matrix.
*
* @return the underlying two dimensional double array.
*/
public double[][] getMatrix() {
return this.matrix;
}
/**
* Creates the identity matrix of size i.
*
* @param i
* Size of matrix.
* @return Identity matrix.
*/
public static Matrix createIdentity(int i) {
double[][] g = new double[i][i];
for (int j = 0; j < i; j++) {
for (int k = 0; k < i; k++) {
if (j == k) {
g[j][k] = 1;
} else {
g[j][k] = 0;
}
}
}
return new Matrix(g);
}
/**
* Pretty prints the matrix to stdout.
*/
public void print() {
for (int i = 0; i < matrix.length; i++) {
System.out.print("{");
for (int j = 0; j < matrix[0].length; j++) {
if (j < matrix[0].length - 1) {
System.out.print(" " + matrix[i][j] + ",");
} else {
System.out.print(" " + matrix[i][j]);
}
}
System.out.println(" }");
}
}
/**
* Pretty print the matrix to stdout.
*
* @param Pattern
* a Formatter for the double value.
*/
public void printformatted(String Pattern) {
DecimalFormat Formatter = new DecimalFormat(Pattern);
for (int i = 0; i < matrix.length; i++) {
System.out.print("{");
for (int j = 0; j < matrix[0].length; j++) {
if (j < matrix[0].length - 1) {
System.out
.print(" " + Formatter.format(matrix[i][j]) + ",");
} else {
System.out.print(" " + Formatter.format(matrix[i][j]));
}
}
System.out.println(" }");
}
}
/**
* Multiplies two matrices.
*
* @param B
* @return The result of this x B
* @throws InterruptedException
* @throws Exception
*/
public Matrix MultiplyMatrix(Matrix B) {
return this.SeqMultiplyMatrix(B);
}
/**
* Raises the matrix to a power, A^3 = A x A x A.
*
* @param power
* @return result of calculation
*/
public Matrix pow(int power) {
Matrix retval = new Matrix(this.matrix);
for (int i = 0; i < power; i++) {
try {
retval = retval.MultiplyMatrix(retval);
} catch (Exception e) {
e.printStackTrace();
}
}
return retval;
}
private Matrix SeqMultiplyMatrix(Matrix Mb) throws IllegalArgumentException {
double[][] b = Mb.getMatrix();
double[][] a = this.matrix;
if (a[0].length != b.length)
throw new IllegalArgumentException(
"Matrices incompatible for multiplication");
double matrix[][] = new double[a.length][b[0].length];
for (int i = 0; i < a.length; i++)
for (int j = 0; j < b[i].length; j++)
matrix[i][j] = 0;
// cycle through answer matrix
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = calculateRowColumnProduct(a, i, b, j);
}
}
return new Matrix(matrix);
}
private double calculateRowColumnProduct(double[][] A, int row,
double[][] B, int col) {
double product = 0;
for (int i = 0; i < A[row].length; i++)
product += A[row][i] * B[i][col];
return product;
}
// --------------------------------------------------------------
/**
* Performs the transposition of the matrix.
*
* @return transpose of the matrix
*/
public Matrix Transpose() {
double[][] a = this.matrix;
if (INFO) {
System.out.println("Performing Transpose...");
}
double m[][] = new double[a[0].length][a.length];
for (int i = 0; i < a.length; i++)
for (int j = 0; j < a[i].length; j++)
m[j][i] = a[i][j];
return new Matrix(m);
}
private double[][] Transpose(double[][] a) {
if (INFO) {
System.out.println("Performing Transpose...");
}
double m[][] = new double[a[0].length][a.length];
for (int i = 0; i < a.length; i++)
for (int j = 0; j < a[i].length; j++)
m[j][i] = a[i][j];
return m;
}
/**
* Computes the inverse of a matrix. Formula used to Calculate Inverse: a
* inv(A) = 1/det(A) * adj(A)
*
* @return inverse of this matrix.
* @throws Exception
*/
public Matrix Inverse() throws Exception {
double[][] a = this.copyfloatArray(this.matrix);
if (INFO) {
System.out.println("Performing Inverse...");
}
int tms = a.length;
double m[][] = new double[tms][tms];
double mm[][] = Adjoint(a);
double det = Determinant(a);
double dd = 0;
if (det == 0) {
if (INFO) {
System.out.println("Determinant Equals 0, Not Invertible.");
}
} else {
dd = 1 / det;
}
for (int i = 0; i < tms; i++)
for (int j = 0; j < tms; j++) {
m[i][j] = dd * mm[i][j];
}
return new Matrix(m);
}
/**
* Computes the adjoint of the matrix. Wikipedia's article of <a
* href="http://en.wikipedia.org/wiki/Adjugate_matrix">adjugate matrix</a>.
*
* @return adjoint of the matrix
* @throws Exception
*/
public Matrix Adjoint() throws Exception {
double[][] a = this.matrix;
if (INFO) {
System.out.println("Performing Adjoint...");
}
int tms = a.length;
double m[][] = new double[tms][tms];
int ii, jj, ia, ja;
double det;
for (int i = 0; i < tms; i++)
for (int j = 0; j < tms; j++) {
ia = ja = 0;
double ap[][] = new double[tms - 1][tms - 1];
for (ii = 0; ii < tms; ii++) {
for (jj = 0; jj < tms; jj++) {
if ((ii != i) && (jj != j)) {
ap[ia][ja] = a[ii][jj];
ja++;
}
}
if ((ii != i) && (jj != j)) {
ia++;
}
ja = 0;
}
det = Determinant(ap);
m[i][j] = Math.pow(-1, i + j) * det;
}
m = Transpose(m);
return new Matrix(m);
}
private double[][] Adjoint(double[][] a) throws Exception {
if (INFO) {
System.out.println("Performing Adjoint...");
}
int tms = a.length;
double m[][] = new double[tms][tms];
int ii, jj, ia, ja;
double det;
for (int i = 0; i < tms; i++)
for (int j = 0; j < tms; j++) {
ia = ja = 0;
double ap[][] = new double[tms - 1][tms - 1];
for (ii = 0; ii < tms; ii++) {
for (jj = 0; jj < tms; jj++) {
if ((ii != i) && (jj != j)) {
ap[ia][ja] = a[ii][jj];
ja++;
}
}
if ((ii != i) && (jj != j)) {
ia++;
}
ja = 0;
}
det = Determinant(ap);
m[i][j] = Math.pow(-1, i + j) * det;
}
m = Transpose(m);
return m;
}
/**
* Computing the UpperTriangle of the matrix.
*
* @return Upper triangle of the matrix
*/
public double[][] UpperTriangle() {
double[][] m = this.matrix;
if (INFO) {
System.out.println("Converting to Upper Triangle...");
}
double f1 = 0;
double temp = 0;
int tms = m.length;
int v = 1;
iDF = 1;
for (int col = 0; col < tms - 1; col++) {
for (int row = col + 1; row < tms; row++) {
v = 1;
outahere: while (m[col][col] == 0) // check if 0 in diagonal
{ // if so switch until not
if (col + v >= tms) // check if switched all rows
{
iDF = 0;
break outahere;
} else {
for (int c = 0; c < tms; c++) {
temp = m[col][c];
m[col][c] = m[col + v][c]; // switch rows
m[col + v][c] = temp;
}
v++; // count row switchs
iDF = iDF * -1; // each switch changes determinant
// factor
}
}
if (m[col][col] != 0) {
if (DEBUG) {
System.out.println("tms = " + tms + " col = " + col
+ " row = " + row);
}
try {
f1 = (-1) * m[row][col] / m[col][col];
for (int i = col; i < tms; i++) {
m[row][i] = f1 * m[col][i] + m[row][i];
}
} catch (Exception e) {
System.out.println("Still Here!!!");
}
}
}
}
return m;
}
private double[][] UpperTriangle(double[][] m) {
if (INFO) {
System.out.println("Converting to Upper Triangle...");
}
double f1 = 0;
double temp = 0;
int tms = m.length; // get This Matrix Size (could be smaller than
// global)
int v = 1;
iDF = 1;
for (int col = 0; col < tms - 1; col++) {
for (int row = col + 1; row < tms; row++) {
v = 1;
outahere: while (m[col][col] == 0) // check if 0 in diagonal
{ // if so switch until not
if (col + v >= tms) // check if switched all rows
{
iDF = 0;
break outahere;
} else {
for (int c = 0; c < tms; c++) {
temp = m[col][c];
m[col][c] = m[col + v][c]; // switch rows
m[col + v][c] = temp;
}
v++; // count row switchs
iDF = iDF * -1; // each switch changes determinant
// factor
}
}
if (m[col][col] != 0) {
if (DEBUG) {
System.out.println("tms = " + tms + " col = " + col
+ " row = " + row);
}
try {
f1 = (-1) * m[row][col] / m[col][col];
for (int i = col; i < tms; i++) {
m[row][i] = f1 * m[col][i] + m[row][i];
}
} catch (Exception e) {
System.out.println("Still Here!!!");
}
}
}
}
return m;
}
/**
* Computes the determinant of the matrix.
*
* @return the determinant
*/
public double Determinant() {
double[][] matrix = this.matrix;
if (INFO) {
System.out.println("Getting Determinant...");
}
int tms = matrix.length;
double det = 1;
matrix = UpperTriangle(matrix);
for (int i = 0; i < tms; i++) {
det = det * matrix[i][i];
} // multiply down diagonal
det = det * iDF; // adjust w/ determinant factor
if (INFO) {
System.out.println("Determinant: " + det);
}
return det;
}
private double Determinant(double[][] matrix) {
if (INFO) {
System.out.println("Getting Determinant...");
}
int tms = matrix.length;
double det = 1;
matrix = UpperTriangle(matrix);
for (int i = 0; i < tms; i++) {
det = det * matrix[i][i];
} // multiply down diagonal
det = det * iDF; // adjust w/ determinant factor
if (INFO) {
System.out.println("Determinant: " + det);
}
return det;
}
/**
* Adds this matrix to matrix m
*
* @param m
* operand
* @return result of adding the given matrix to this matrix
* @throws Exception
*/
public Matrix addMatrix(Matrix m) throws Exception {
if ((m.matrix.length == this.matrix.length)
&& (m.matrix[0].length == this.matrix[0].length)) {
Matrix retval = new Matrix(this.matrix.length);
for (int i = 0; i < this.matrix[0].length; i++) {
for (int j = 0; j < this.matrix.length; j++) {
retval.matrix[i][j] = this.matrix[i][j] + m.matrix[i][j];
}
}
return retval;
} else {
throw new Exception();
}
}
/**
* Subtracts m from this matrix.
*
* @param m
* Operand
* @return result of subtracting the given matrix from this matrix
* @throws Exception
*/
public Matrix subtractMatrix(Matrix m) throws Exception {
if ((m.matrix.length == this.matrix.length)
&& (m.matrix[0].length == this.matrix[0].length)) {
Matrix retval = new Matrix(this.matrix.length);
for (int i = 0; i < this.matrix[0].length; i++) {
for (int j = 0; j < this.matrix.length; j++) {
retval.matrix[i][j] = this.matrix[i][j] - m.matrix[i][j];
}
}
return retval;
} else {
throw new Exception();
}
}
/**
* Computes the trace of the matrix.
*
* @return trace of matrix
*/
public float Trace() {
float retval = 0;
if (this.matrix.length == this.matrix[0].length) {
for (int i = 0; i < this.matrix.length; i++) {
retval += this.matrix[i][i];
}
} else {
throw new RuntimeException("Matrix must be square");
}
return retval;
}
/**
* Pseudo-division. Inverse(this) * j
*
* @param j
* operand
* @return result of pseudo-division
*/
public Matrix divide(Matrix j) {
try {
Matrix mi = this.Inverse();
mi = mi.MultiplyMatrix(j);
return mi;
} catch (Exception e) {
throw new RuntimeException("Invalid Matrix operation.");
}
}
/**
* Performs a deep equals
*
* @param B
* @return true if the matrices are equal with 0 tolerance
*/
public boolean eq(Matrix B) {
return this.eq(B, 0.0);
}
/**
* Performs a deep equals
*
* @param B
* @return true if the matrices are equal up to a tolerance.
*/
public boolean eq(Matrix B, double tolerance) {
Matrix A = this;
if (B.getMatrix().length != getMatrix().length
|| B.getMatrix()[0].length != getMatrix()[0].length)
throw new RuntimeException("Illegal matrix dimensions.");
for (int i = 0; i < this.getMatrix().length; i++)
for (int j = 0; j < this.getMatrix()[0].length; j++)
if (Math.abs(A.getMatrix()[i][j] - B.getMatrix()[i][j]) > tolerance)
return false;
return true;
}
private double[][] copyfloatArray(double[][] nums) {
double[][] copy = new double[nums.length][];
for (int i = 0; i < nums.length; i++) {
copy[i] = new double[nums[i].length];
for (int j = 0; j < nums[i].length; j++) {
copy[i][j] = nums[i][j];
}
}
return copy;
}
/**
* Zero's the diagonal
*/
public void zerodiag() {
if (this.matrix.length == this.matrix[0].length) {
for (int i = 0; i < this.matrix.length; i++) {
this.matrix[i][i] = 0;
}
}
}
/**
* Computes the multiplication of the array of matrices.
*
* @param m
* @return result of computation
*/
public static Matrix multiplyChain(Matrix... m) {
MatrixOrderOptimization moo = new MatrixOrderOptimization(m);
return moo.multiplyChain();
}
@Override
public String toString() {
String retval = "";
for (int i = 0; i < matrix.length; i++) {
retval = retval + "{ ";
for (int j = 0; j < matrix[0].length; j++) {
if (j < matrix[0].length - 1) {
retval = retval + (" " + matrix[i][j] + ",");
} else {
retval = retval + (" " + matrix[i][j]);
}
}
retval = retval + (" }\n");
}
return retval;
}
} | Java |
package annas.util;
/**
* This class provides an equivalent method to the equals method. For use with
* ArraySet.
*
* @author Sam
*
* @param <T>
*/
public interface EqualityChecker<T> {
public boolean check(Object a, Object b);
}
| Java |
package annas.util;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
public class ArraySet<E> extends AbstractList<E> implements Set<E>, Iterable<E> {
/**
* The array buffer into which the elements of the ArraySet are stored. The
* capacity of the ArraySet is the length of this array buffer.
*/
private transient Object[] elementData;
/**
* The size of the ArraySet (the number of elements it contains).
*
* @serial
*/
private int size;
private EqualityChecker<E> checker;
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity
* the initial capacity of the list
* @exception IllegalArgumentException
* if the specified initial capacity is negative
*/
private ArraySet(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "
+ initialCapacity);
this.elementData = new Object[initialCapacity];
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArraySet(EqualityChecker<E> checker) {
this(10);
this.checker = checker;
}
/**
* Trims the capacity of this <tt>ArraySet</tt> instance to be the list's
* current size. An application can use this operation to minimize the
* storage of an <tt>ArraySet</tt> instance.
*/
public void trimToSize() {
modCount++;
int oldCapacity = elementData.length;
if (size < oldCapacity) {
elementData = Arrays.copyOf(elementData, size);
}
}
/**
* Increases the capacity of this <tt>ArraySet</tt> instance, if necessary,
* to ensure that it can hold at least the number of elements specified by
* the minimum capacity argument.
*
* @param minCapacity
* the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
// Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3) / 2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list
*/
@Override
public int size() {
return size;
}
/**
* Returns <tt>true</tt> if this list contains no elements.
*
* @return <tt>true</tt> if this list contains no elements
*/
@Override
public boolean isEmpty() {
return size == 0;
}
/**
* Returns <tt>true</tt> if this list contains the specified element. More
* formally, returns <tt>true</tt> if and only if this list contains at
* least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o
* element whose presence in this list is to be tested
* @return <tt>true</tt> if this list contains the specified element
*/
@Override
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
/**
* Returns the index of the first occurrence of the specified element in
* this list, or -1 if this list does not contain the element. More
* formally, returns the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
@Override
public int indexOf(Object o) {
if (o == null) {
return -1;
} else {
for (int i = 0; i < size; i++)
if (this.checker.check(o, elementData[i]))
return i;
}
return -1;
}
// Positional Access Operations
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
/**
* Returns the element at the specified position in this list.
*
* @param index
* index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException
* {@inheritDoc}
*/
@Override
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
/**
* Appends the specified element to the end of this list.
*
* @param e
* element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
@Override
public boolean add(E e) {
if (e == null || this.contains(e)) {
return false;
}
this.modCount += 1;
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
@Override
public boolean addAll(Collection<? extends E> c) {
boolean successful = true;
for (E o : c) {
successful &= this.add(o);
}
return successful;
}
/**
* Checks if the given index is in range. If not, throws an appropriate
* runtime exception. This method does *not* check if the index is negative:
* It is always used immediately prior to an array access, which throws an
* ArrayIndexOutOfBoundsException if index is negative.
*/
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* A version of rangeCheck used by add and addAll.
*/
protected void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Constructs an IndexOutOfBoundsException detail message. Of the many
* possible refactorings of the error handling code, this "outlining"
* performs best with both server and client VMs.
*/
private String outOfBoundsMsg(int index) {
return "Index: " + index + ", Size: " + size;
}
/**
* Returns an iterator over the elements in this list in proper sequence.
*
* <p>
* The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*
* @return an iterator over the elements in this list in proper sequence
*/
@Override
public Iterator<E> iterator() {
return new Itr();
}
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
private int cursor; // index of next element to return
private int lastRet = -1; // index of last element returned; -1 if no
// such
private int expectedModCount = modCount;
@Override
public boolean hasNext() {
return cursor != size;
}
@Override
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArraySet.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
lastRet = i;
return (E) elementData[lastRet];
}
@Override
public void remove() {
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
} | Java |
package annas.util;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class DisjointSet<V> {
private final HashMap<V,Identifier<V>> objectToSetIdentifiers = new HashMap<V,Identifier<V>>();
public DisjointSet(Set<V> vs){
super();
for(V v : vs){
this.makeSet(v);
}
}
public V findSet(V o) {
DisjointSet.Identifier<V> node = objectToSetIdentifiers.get(o);
if (node == null)
return null;
if (o != node.parent)
node.setParent(findSet(node.parent));
return node.getParent();
}
/**
* Adds a new set to the group of disjoint sets for the given object.
* It is assumed that the object does not yet belong to any set.
* @param o The object to add to the set
*/
public void makeSet(V o) {
objectToSetIdentifiers.put(o, new Identifier<V>(o, 0));
}
/**
* Removes all elements belonging to the set of the given object.
* @param o The object to remove
*/
public void removeSet(V o) {
V set = findSet(o);
if (set == null)
return;
for (Iterator<V> it = objectToSetIdentifiers.keySet().iterator(); it.hasNext();) {
V next = it.next();
//remove the set representative last, otherwise findSet will fail
if (next != set && findSet(next) == set)
it.remove();
}
objectToSetIdentifiers.remove(set);
}
/**
* Unions the set represented by token x with the set represented by
* token y. Has no effect if either x or y is not in the disjoint set, or
* if they already belong to the same set.
* @param x The first set to union
* @param y The second set to union
*/
public void union(V x, V y) {
V setX = findSet(x);
V setY = findSet(y);
if (setX == null || setY == null || setX == setY)
return;
Identifier<V> nodeX = objectToSetIdentifiers.get(setX);
Identifier<V> nodeY = objectToSetIdentifiers.get(setY);
if (nodeX.getRank() > nodeY.getRank()) {
nodeY.setParent(x);
} else {
nodeX.setParent(y);;
if (nodeX.getRank() == nodeY.getRank())
nodeY.setRank(nodeY.getRank()+1);
}
}
/**
* A Identifier in the disjoint set forest. Each tree in the forest is
* a disjoint set, where the root of the tree is the set identifier.
*/
private static class Identifier<V> {
/**
* Used for optimization
*/
private int rank;
/**
* Identifier of the disjoint set
*/
private V parent;
Identifier(V parent, int rank) {
this.parent = parent;
this.rank = rank;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public V getParent() {
return parent;
}
public void setParent(V parent) {
this.parent = parent;
}
}
} | Java |
public class CartesianProduct {
//TODO
}
| Java |
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class MaximumFinder extends RecursiveTask<Integer> {
private static final int SEQUENTIAL_THRESHOLD = 10000;
private final int[] data;
private final int start;
private final int end;
public MaximumFinder(int[] data, int start, int end) {
this.data = data;
this.start = start;
this.end = end;
}
public MaximumFinder(int[] data) {
this(data, 0, data.length);
}
@Override
protected Integer compute() {
final int length = end - start;
if (length < SEQUENTIAL_THRESHOLD) {
return computeDirectly();
}
final int split = length / 2;
final MaximumFinder left = new MaximumFinder(data, start, start + split);
left.fork();
final MaximumFinder right = new MaximumFinder(data, start + split, end);
return Math.max(right.compute(), left.join());
}
private Integer computeDirectly() {
System.out.println(Thread.currentThread() + " computing: " + start
+ " to " + end);
int max = Integer.MIN_VALUE;
for (int i = start; i < end; i++) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
public static void main(String[] args) {
// create a random data set
final int[] data = new int[1000000];
final Random random = new Random();
for (int i = 0; i < data.length; i++) {
data[i] = random.nextInt(100);
}
// submit the task to the pool
final ForkJoinPool pool = new ForkJoinPool(5);
final MaximumFinder finder = new MaximumFinder(data);
System.out.println(pool.invoke(finder));
}
} | Java |
import annas.graph.GraphInterface;
import annas.graph.IntegerEdge;
import annas.graph.SimpleUndirectedGraph;
import annas.graph.classifier.AlmostC;
import annas.graph.classifier.SplitRecogniser;
public class Harness {
/**
* @param args
*/
public static void main(String[] args) {
test_();
}
private static void test_() {
SimpleUndirectedGraph<Integer, IntegerEdge> graph = new SimpleUndirectedGraph<Integer, IntegerEdge>(
IntegerEdge.class);
/* for (int i = 0; i < 8; i++) {
graph.addVertex(i);
}
graph.addEdge(0, 1);
graph.addEdge(2, 3);
graph.addEdge(4, 5);*/
for(int i = 0; i <8; i++){
graph.addVertex(i);
}
graph.addEdge(0, 1);
graph.addEdge(2, 1);
graph.addEdge(2, 3);
graph.addEdge(3, 0);
graph.addEdge(4, 5);
graph.addEdge(6, 7);
AlmostC<Integer, IntegerEdge> c = new AlmostC<Integer, IntegerEdge>(
new SplitRecogniser<Integer, IntegerEdge>(), 3);
System.out.println(c.classify(graph));
findMinimalForbidden<Integer, IntegerEdge> fmf = new findMinimalForbidden<Integer, IntegerEdge>(
c);
GraphInterface<Integer, IntegerEdge> g = fmf.find(graph);
System.out.println(g);
}
public static void test(){
SimpleUndirectedGraph<Integer, IntegerEdge> graph = new SimpleUndirectedGraph<Integer, IntegerEdge>(
IntegerEdge.class);
for(int i = 0; i <4; i++){
graph.addVertex(i);
}
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
AlmostC<Integer, IntegerEdge> c = new AlmostC<Integer, IntegerEdge>(
new SplitRecogniser<Integer, IntegerEdge>(),0);
System.out.println(c.classify(graph));
System.out.println(new SplitRecogniser<Integer, IntegerEdge>().classify(graph));
}
}
| Java |
import java.util.ArrayList;
import java.util.List;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
import annas.graph.SimpleUndirectedGraph;
import annas.graph.classifier.Classifier;
public class findMinimalForbidden<V, E extends EdgeInterface<V>> {
private Classifier recogniser;
public findMinimalForbidden(Classifier<V, E> classifier) {
super();
this.recogniser = classifier;
}
public GraphInterface<V, E> find(SimpleUndirectedGraph<V, E> graph) {
SimpleUndirectedGraph<V, E> tmp = this.copyGraph(graph);
SimpleUndirectedGraph<V, E> tmp1;
List<V> Vs = new ArrayList<V>();
for (V v : graph.getVertices()) {
tmp1 = this.copyGraph(tmp);
tmp.removeVertex(v);
if (this.recogniser.classify(tmp)) {
Vs.add(v);
tmp = tmp1;
}
}
tmp = this.copyGraph(graph);
for(V v : graph.getVertices()){
if(!Vs.contains(v)){
tmp.removeVertex(v);
}
}
return tmp;
}
/**
* Makes a copy of the graph uses the same vertices and edge objects but
* makes a copy of the structure.
*
* @param graph
* @return
*/
private SimpleUndirectedGraph<V, E> copyGraph(
SimpleUndirectedGraph<V, E> graph) {
SimpleUndirectedGraph<V, E> retval = new SimpleUndirectedGraph<V, E>(
graph.getEdgeFactory());
retval.addVertices(graph.getVertices());
for (E e : graph.getEdges()) {
retval.addEdge(e.getTail(), e.getHead());
}
return retval;
}
}
| Java |
import annas.graph.GraphInterface;
import annas.graph.IntegerEdge;
import annas.graph.UndirectedGraph;
import annas.graph.observable.ObservableGraph;
public class DPHarness {
public static void main(String args[]){
GraphInterface graph = new UndirectedGraph<>(IntegerEdge.class);
GraphInterface og = ObservableGraph.getObservableGraph(graph);
og.addVertex(1);
System.out.println(og instanceof UndirectedGraph);
}
}
| Java |
import java.util.ArrayList;
import java.util.List;
import annas.math.combinatorics.SimpleCombinationGenerator;
public class almostk4free {
public static void main(String[] args){
List<String> l = new ArrayList<String>();
l.add("a");
l.add("b");
l.add("c");
l.add("d");
l.add("e");
l.add("f");
SimpleCombinationGenerator<String> scg = new SimpleCombinationGenerator<>(l, 3);
for(List<String> s : scg){
System.out.println(s);
}
}
}
| Java |
import annas.graph.IntegerEdge;
import annas.graph.SimpleUndirectedGraph;
import annas.graph.io.Graph6Exporter;
import annas.graph.io.GraphExporter;
import annas.graph.util.Utilities;
public class Harness111 {
public static void main(String[] args) {
GraphExporter ge = new Graph6Exporter();
SimpleUndirectedGraph<Integer, IntegerEdge> graph = new SimpleUndirectedGraph<Integer, IntegerEdge>(
IntegerEdge.class);
for(int i = 0; i <4; i++){
graph.addVertex(i);
}
graph.addEdge(0, 1);
graph.addEdge(2, 1);
graph.addEdge(2, 3);
graph.addEdge(3, 0);
System.out.println(Utilities.getAdjacencyMatrix(graph));
ge.exportGraph(graph);
}
}
| Java |
import java.util.Collection;
import java.util.Collections;
import java.util.Hashtable;
import annas.graph.GraphInterface;
import annas.graph.IntegerEdge;
import annas.graph.SimpleUndirectedGraph;
import annas.graph.util.Utilities;
public class RootedSubTreeIso {
public static void main(String[] args) {
GraphInterface<Integer, IntegerEdge> S = new SimpleUndirectedGraph<Integer, IntegerEdge>(
IntegerEdge.class);
GraphInterface<Integer, IntegerEdge> T = new SimpleUndirectedGraph<Integer, IntegerEdge>(
IntegerEdge.class);
for (int i = 0; i < 6; i++)
S.addVertex(i);
S.addEdge(0, 1);
S.addEdge(0, 2);
S.addEdge(2, 3);
S.addEdge(2, 4);
S.addEdge(4, 5);
for (int i = 0; i < 9; i++)
T.addVertex(i);
T.addEdge(0, 1);
T.addEdge(0, 2);
T.addEdge(2, 3);
T.addEdge(2, 4);
T.addEdge(2, 5);
T.addEdge(4, 6);
T.addEdge(6, 7);
T.addEdge(6, 8);
rootedSubTreeIso(S, 0, T, 0);
}
public static boolean rootedSubTreeIso(
GraphInterface<Integer, IntegerEdge> S, Integer s,
GraphInterface<Integer, IntegerEdge> T, Integer t) {
Collection<Integer> leafs = Utilities.getVerticesOfDegree(T, 1);
Collection<Integer> l = Utilities.getVerticesOfDegree(S, 1);
Hashtable<Integer, Collection<Integer>> table = new Hashtable<Integer, Collection<Integer>>();
Hashtable<Integer, Integer> depths = processDepth(T, 0);
int max_depth = Collections.max(depths.values());
for (Integer i : leafs) {
table.put(i, l);
}
return table.get(t).contains(s);
}
/**
* Below is stuff for calculating the distance of each vertex from the root
* of the tree
*/
private static Hashtable<Integer, Integer> processDepth(
GraphInterface<Integer, IntegerEdge> g, Integer root) {
Hashtable<Integer, Integer> depths = new Hashtable<Integer, Integer>();
depths.put(0, 0);
rec(g, depths, -1, root, 1);
return depths;
}
private static void rec(GraphInterface<Integer, IntegerEdge> g,
Hashtable<Integer, Integer> depths, int parent, int current,
int depth) {
for (IntegerEdge e : g.getEdges(current)) {
int otherEnd = otherEndPoint(e, current);
if (otherEnd != parent) {
depths.put(otherEnd, depth);
rec(g, depths, current, otherEnd, depth + 1);
}
}
}
private static int otherEndPoint(IntegerEdge e, int h) {
if (e.getHead() == h) {
return e.getTail();
} else {
return e.getHead();
}
}
}
| Java |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import annas.graph.EdgeInterface;
import annas.graph.GraphInterface;
import annas.graph.IntegerEdge;
import annas.graph.SimpleUndirectedGraph;
import annas.graph.classifier.AlmostC;
import annas.graph.classifier.Classifier;
import annas.graph.classifier.DisjointCliqueRecogniser;
import annas.graph.io.DOTExporter;
import annas.graph.io.GraphExporter;
import annas.math.Matrix;
public class GenerateForbiddenSet<V, E extends EdgeInterface<V>> {
public Classifier<V, E> classifier;
public int MaxSize;
public GenerateForbiddenSet(Classifier<V, E> classifier, int MaxSize) {
super();
this.classifier = classifier;
this.MaxSize = MaxSize;
}
/**
* Generates the list of forbidden graphs, will contain duplicates.
*
* @return
* @throws IOException
*/
public List<GraphInterface<V, E>> generate() throws IOException {
List<GraphInterface<V, E>> forb = new ArrayList<GraphInterface<V, E>>();
for (int i = 2; i <= this.MaxSize; i++) {
BufferedReader br = new BufferedReader(new FileReader("graph" + i
+ ".g6"));
String line;
while ((line = br.readLine()) != null) {
GraphInterface<Integer, IntegerEdge> g = Fromg6.fromg6(line);
if (!classifier.classify((GraphInterface<V, E>) g)) {
findMinimalForbidden<Integer, IntegerEdge> fmf = new findMinimalForbidden<Integer, IntegerEdge>(
(Classifier<Integer, IntegerEdge>) classifier);
GraphInterface<Integer, IntegerEdge> tmp = fmf
.find((SimpleUndirectedGraph<Integer, IntegerEdge>) g);
if (g.getOrder() == tmp.getOrder()) {
forb.add((GraphInterface<V, E>) tmp);
}
} else {
}
}
br.close();
}
return forb;
}
public static void main(String[] args) throws IOException {
long t1 = System.currentTimeMillis();
/*
* GenerateForbiddenSet<Integer, IntegerEdge> gfs = new
* GenerateForbiddenSet<Integer, IntegerEdge>( new
* SplitRecogniser<Integer, IntegerEdge>(), 6);
*/
/*
* GenerateForbiddenSet<Integer, IntegerEdge> gfs = new
* GenerateForbiddenSet<Integer, IntegerEdge>( new
* ThresholdRecogniser<Integer, IntegerEdge>(), 6);
*/
Classifier<Integer, IntegerEdge> ap3 = new AlmostC<Integer, IntegerEdge>(
new DisjointCliqueRecogniser<Integer, IntegerEdge>(), 1);
GenerateForbiddenSet<Integer, IntegerEdge> gfs = new GenerateForbiddenSet<Integer, IntegerEdge>(
ap3, 10);
GraphExporter<Integer, IntegerEdge> ge = new DOTExporter<Integer, IntegerEdge>();
for (GraphInterface<Integer, IntegerEdge> g : gfs.generate()) {
//System.out.println(g);
ge.exportGraph(g);
}
long t2 = System.currentTimeMillis();
System.out.println((t2-t1)/100 + " Seconds");
}
private static class Fromg6 {
public static GraphInterface<Integer, IntegerEdge> fromg6(String str) {
Matrix m = decodeGraph(StringToIntArray(str));
GraphInterface<Integer, IntegerEdge> graph = new SimpleUndirectedGraph<Integer, IntegerEdge>(
IntegerEdge.class);
for (int i = 0; i < m.getMatrix().length; i++) {
graph.addVertex(i);
}
double[][] ma = m.getMatrix();
for (int i = 0; i < ma.length; i++) {
for (int j = 0; j < ma.length; j++) {
if (ma[i][j] == 1) {
graph.addEdge(i, j);
}
}
}
return graph;
}
private static Matrix decodeGraph(int[] i) {
long nuNodes = decodeN(i);
String a = "";
if (nuNodes <= 62) {
a = decodeR(Arrays.copyOfRange(i, 1, i.length));
} else if (nuNodes > 62 && nuNodes <= 258047) {
a = decodeR(Arrays.copyOfRange(i, 4, i.length));
} else {
a = decodeR(Arrays.copyOfRange(i, 8, i.length));
}
int[][] adj = new int[(int) nuNodes][(int) nuNodes];
int q = 0;
for (int w = 0; w < nuNodes; w++) {
for (int e = 0; e < w; e++) {
adj[w][e] = Integer.parseInt((a.charAt(q)) + "");
q++;
}
}
return new Matrix(adj);
}
private static long decodeN(int i[]) {
if (i.length > 2 && i[0] == 126 && i[1] == 126) {
return Long.parseLong(decodeR(new int[] { i[2], i[3], i[4],
i[5], i[6], i[7] }), 2);
} else if (i.length > 1 && i[0] == 126) {
return Long.parseLong(decodeR(new int[] { i[1], i[2], i[3] }),
2);
} else {
return i[0] - 63;
}
}
private static String decodeR(int[] bytes) {
String retval = "";
for (int i = 0; i < bytes.length; i++) {
retval += padL(Integer.toBinaryString(bytes[i] - 63), 6);
}
return retval;
}
private static String padL(String str, int h) {
String retval = "";
for (int i = 0; i < h - str.length(); i++) {
retval += "0";
}
return retval + str;
}
private static int[] StringToIntArray(String str) {
int[] v = new int[str.length()];
for (int l = 0; l < str.length(); l++) {
v[l] = str.charAt(l);
}
return v;
}
}
}
| Java |
import test.DefaultWeightedEdge;
import annas.graph.DirectedGraph;
import annas.graph.util.FordFulkerson;
public class Harness1 {
/**
* @param args
*/
public static void main(String[] args) {
DirectedGraph<String, DefaultWeightedEdge> graph = new DirectedGraph<String, DefaultWeightedEdge>(
DefaultWeightedEdge.class);
String a = "A"; // u0
String b = "B";// u1
String c = "C";// u2
String d = "D";// u3
String e = "E";// u4
String f = "F";// u5
graph.addVertex(a);
graph.addVertex(b);
graph.addVertex(c);
graph.addVertex(d);
graph.addVertex(e);
graph.addVertex(f);
DefaultWeightedEdge e1 = null;
e1 = graph.addEdge(a, b);
e1.setWeight(5);
e1 = graph.addEdge(a, c);
e1.setWeight(9);
e1 = graph.addEdge(b, d);
e1.setWeight(4);
e1 = graph.addEdge(d, f);
e1.setWeight(3);
e1 = graph.addEdge(c, d);
e1.setWeight(8);
e1 = graph.addEdge(c, e);
e1.setWeight(3);
e1 = graph.addEdge(c, f);
e1.setWeight(2);
e1 = graph.addEdge(d, e);
e1.setWeight(1);
e1 = graph.addEdge(e, f);
e1.setWeight(9);
FordFulkerson<String, DefaultWeightedEdge> ff = new FordFulkerson<String, DefaultWeightedEdge>(
graph, a, f);
System.out.println(ff.getMaximumFlow());
test();
}
private static void test() {
DirectedGraph<String, DefaultWeightedEdge> graph = new DirectedGraph<String, DefaultWeightedEdge>(
DefaultWeightedEdge.class);
graph.addVertex("s");
graph.addVertex("o");
graph.addVertex("p");
graph.addVertex("q");
graph.addVertex("r");
graph.addVertex("t");
DefaultWeightedEdge e1 = null;
e1 = graph.addEdge("s", "o");
e1.setWeight(3);
e1 = graph.addEdge("s", "p");
e1.setWeight(3);
e1 = graph.addEdge("o", "p");
e1.setWeight(2);
e1 = graph.addEdge("o", "q");
e1.setWeight(3);
e1 = graph.addEdge("p", "r");
e1.setWeight(2);
e1 = graph.addEdge("r", "t");
e1.setWeight(3);
e1 = graph.addEdge("q", "r");
e1.setWeight(4);
e1 = graph.addEdge("q", "t");
e1.setWeight(2);
FordFulkerson<String, DefaultWeightedEdge> ff = new FordFulkerson<String, DefaultWeightedEdge>(
graph, "s", "t");
System.out.println(ff.getMaximumFlow());
}
}
| Java |
import annas.graph.DefaultEdge;
import annas.graph.UndirectedGraph;
import annas.graph.util.BipartiteMatching;
public class Harness11 {
public static void main(String[] args) throws Exception {
final UndirectedGraph<String, DefaultEdge> g = new UndirectedGraph<String, DefaultEdge>(
DefaultEdge.class);
final String a = "A"; // u0
final String b = "B";// u1
final String c = "C";// u2
final String d = "D";// u3
final String e = "E";// u4
final String f = "F";// u5
g.addVertex(a);
g.addVertex(b);
g.addVertex(c);
g.addVertex(d);
g.addVertex(e);
g.addVertex(f);
g.addEdge(a, b);
g.addEdge(b, c);
g.addEdge(c, d);
g.addEdge(d, a);
g.addEdge(e, f);
final BipartiteMatching<String, DefaultEdge> bm = new BipartiteMatching<String, DefaultEdge>(
g);
System.out.println(bm.getMatching());
}
}
| Java |
public class ExtendedEuclideanMethod {
public static long[] ExtendedEuclid(long a, long b) {
long x = 0;
long y = 1;
long lastx = 1;
long lasty = 0;
long q;
long tmpa = a;
long tmpb = b;
while (b != 0) {
q = a / b;
tmpa = b;
tmpb = a % b;
lastx = x;
x = lastx - q * x;
lasty = y;
y = lasty - q * y;
a = tmpa;
b = tmpb;
}
return new long[] { lastx, lasty };
}
public static void main(String[] args) {
long[] l = ExtendedEuclid(240, 46);
System.out.println(l[0]);
System.out.println(l[1]);
}
}
| Java |
import annas.graph.IntegerEdge;
import annas.graph.SimpleUndirectedGraph;
import annas.graph.classifier.DisjointCliqueRecogniser;
public class DisjointCliqueRecogniserHarness {
public static void main(String[] args) {
final SimpleUndirectedGraph<Integer, IntegerEdge> graph = new SimpleUndirectedGraph<Integer, IntegerEdge>(
IntegerEdge.class);
for (int i = 0; i < 10; i++) {
graph.addVertex(i);
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
graph.addEdge(i, j);
}
}
for (int i = 5; i < 7; i++) {
for (int j = 5; j < 7; j++) {
graph.addEdge(i, j);
}
}
for (int i = 7; i < 10; i++) {
for (int j = 7; j < 10; j++) {
graph.addEdge(i, j);
}
}
System.out.println(graph);
final DisjointCliqueRecogniser<Integer, IntegerEdge> dcr = new DisjointCliqueRecogniser<Integer, IntegerEdge>();
System.out.println(dcr.classify(graph));
}
}
| Java |
import annas.graph.DefaultEdge;
import annas.graph.UndirectedGraph;
import annas.graph.classifier.ThresholdRecogniser;
public class ThresholdRecogniserHarness {
public static void main(String[] args){
UndirectedGraph<String, DefaultEdge> graph = new UndirectedGraph<String, DefaultEdge>(DefaultEdge.class);
String a = "A"; // u0
String b = "B";// u1
String c = "C";// u2
String d = "D";// u3
String e = "E";// u4
String f = "F";// u5
String g = "G";
String h = "H";
graph.addVertex(a); // 1
graph.addVertex(b); // 2
graph.addVertex(c); // 3
graph.addVertex(d);// 4
graph.addVertex(e);// 5
graph.addVertex(f);// 6
graph.addVertex(g);// 7
graph.addVertex(h);// 8
graph.addEdge(f, h);
graph.addEdge(g, h);
graph.addEdge(e, h);
graph.addEdge(a, e);
graph.addEdge(a, h);
graph.addEdge(b, e);
graph.addEdge(b, h);
graph.addEdge(c, e);
graph.addEdge(c, h);
graph.addEdge(d, e);
graph.addEdge(d, h);
System.out.println(new ThresholdRecogniser().classify(graph));
}
}
| Java |
import java.util.Arrays;
import annas.graph.GraphInterface;
import annas.graph.IntegerEdge;
import annas.graph.UndirectedGraph;
import annas.math.Matrix;
public class Fromg6 {
public GraphInterface<Integer, IntegerEdge> fromg6(String str) {
Matrix m = decodeGraph(StringToIntArray(str));
GraphInterface<Integer, IntegerEdge> graph = new UndirectedGraph<Integer, IntegerEdge>(
IntegerEdge.class);
for (int i = 0; i < m.getMatrix().length; i++) {
graph.addVertex(i);
}
System.out.println(m);
double[][] ma = m.getMatrix();
for(int i = 0; i <ma.length; i++){
for(int j = 0; j<ma.length; j++){
if(ma[i][j]==1){
graph.addEdge(i, j);
}
}
}
return graph;
}
private Matrix decodeGraph(int[] i) {
long nuNodes = decodeN(i);
String a = "";
if (nuNodes <= 62) {
a = decodeR(Arrays.copyOfRange(i, 1, i.length));
} else if (nuNodes > 62 && nuNodes <= 258047) {
a = decodeR(Arrays.copyOfRange(i, 4, i.length));
} else {
a = decodeR(Arrays.copyOfRange(i, 8, i.length));
}
int[][] adj = new int[(int) nuNodes][(int) nuNodes];
int q = 0;
for (int w = 0; w < nuNodes; w++) {
for (int e = 0; e < w; e++) {
adj[w][e] = Integer.parseInt((a.charAt(q)) + "");
q++;
}
}
return new Matrix(adj);
}
private long decodeN(int i[]) {
if (i.length > 2 && i[0] == 126 && i[1] == 126) {
return Long.parseLong(decodeR(new int[] { i[2], i[3], i[4], i[5],
i[6], i[7] }), 2);
} else if (i.length > 1 && i[0] == 126) {
return Long.parseLong(decodeR(new int[] { i[1], i[2], i[3] }), 2);
} else {
return i[0] - 63;
}
}
private String decodeR(int[] bytes) {
String retval = "";
for (int i = 0; i < bytes.length; i++) {
retval += padL(Integer.toBinaryString(bytes[i] - 63), 6);
}
return retval;
}
private String padL(String str, int h) {
String retval = "";
for (int i = 0; i < h - str.length(); i++) {
retval += "0";
}
return retval + str;
}
private int[] StringToIntArray(String str) {
int[] v = new int[str.length()];
for (int l = 0; l < str.length(); l++) {
v[l] = str.charAt(l);
}
return v;
}
}
| Java |
import java.util.ArrayList;
import java.util.Iterator;
import annas.math.combinatorics.SimpleCombinationGenerator;
public class CombHarness {
public static void main(String[] args) {
final ArrayList<Integer> l = new ArrayList<Integer>(5);
for (int i = 1; i <= 9; i++) {
l.add(i);
}
final SimpleCombinationGenerator<Integer> scg = new SimpleCombinationGenerator<Integer>(
l, 2);
final Iterator it = scg.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
| Java |
import java.sql.SQLException;
import annas.graph.GraphInterface;
import annas.misc.GraphDatabase;
import annas.misc.GraphIterator;
public class SQLiteHarness {
public static void main(String args[]) throws SQLException{
GraphDatabase gdb = new GraphDatabase("sample.db");
GraphIterator gi = gdb.getGraphOfOrder(3);
while(gi.hasNext()){
GraphInterface gg = gi.next();
System.out.println("Order: " + gg.getOrder() + " Size: " + gg.getSize());
}
}
}
| Java |
import annas.graph.DefaultEdge;
import annas.graph.UndirectedGraph;
import annas.graph.io.DOTExporter;
import annas.graph.io.GraphExporter;
public class ChordalRecogniserHarness {
public static void main(String[] args) {
UndirectedGraph<String, DefaultEdge> graph = new UndirectedGraph<String, DefaultEdge>(
DefaultEdge.class);
String a = "A"; // u0
String b = "B";// u1
String c = "C";// u2
String d = "D";// u3
String e = "E";// u4
String f = "F";// u5
graph.addVertex(a);
graph.addVertex(b);
graph.addVertex(c);
graph.addVertex(d);
graph.addVertex(e);
graph.addVertex(f);
/*
* graph.addArc(a, b, new DefaultWeight(1d)); graph.addArc(c, b, new
* DefaultWeight(1d)); graph.addArc(d, c, new DefaultWeight(1d));
* graph.addArc(a, d, new DefaultWeight(1d));
*/
graph.addEdge(a, b);
graph.addEdge(b, c);
graph.addEdge(c, d);
graph.addEdge(d, a);
graph.addEdge(a, c);
graph.addEdge(b, e);
graph.addEdge(c, e);
graph.addEdge(c, f);
graph.addEdge(d, f);
// new ChordalRecogniser().check(graph);
// GraphExporter gh = new TGFExporter();
GraphExporter gh = new DOTExporter();
gh.exportGraph(graph);
}
}
| Java |
import java.util.List;
import annas.graph.DefaultEdge;
import annas.graph.UndirectedGraph;
import annas.graph.isomorphism.IsomorphicInducedSubgraphGenerator;
public class HarnessInducedSubraph {
/**
* @param args
*/
public static void main(String[] args) {
UndirectedGraph<String, DefaultEdge> src = new UndirectedGraph<String, DefaultEdge>(
DefaultEdge.class);
src.addVertex("A");
src.addVertex("B");
src.addVertex("C");
// src.addVertex("D");
src.addEdge("A", "B");
src.addEdge("B", "C");
//src.addEdge("C", "A");
// src.addEdge("D","A");
UndirectedGraph<String, DefaultEdge> target = new UndirectedGraph<String, DefaultEdge>(
DefaultEdge.class);
target.addVertex("A");
target.addVertex("B");
target.addVertex("C");
target.addVertex("D");
target.addVertex("E");
target.addVertex("F");
target.addEdge("A", "B");
target.addEdge("B", "C");
target.addEdge("C", "D");
target.addEdge("D", "E");
target.addEdge("E", "F");
target.addEdge("A", "C");
target.addEdge("D", "B");
IsomorphicInducedSubgraphGenerator<String, DefaultEdge> iisg = new IsomorphicInducedSubgraphGenerator<String, DefaultEdge>(
target, src);
for (List<String> l : iisg) {
System.out.println(l);
}
}
}
| Java |
import annas.graph.IntegerEdge;
import annas.graph.SimpleUndirectedGraph;
import annas.graph.generate.CirculantGraphGenerator;
import annas.graph.generate.DefaultVertexFactory;
public class CirculantHarness {
public static void main(String[] args) {
SimpleUndirectedGraph<Integer, IntegerEdge> g = new SimpleUndirectedGraph<Integer, IntegerEdge>(
IntegerEdge.class);
CirculantGraphGenerator<Integer, IntegerEdge> cg =
new CirculantGraphGenerator<Integer, IntegerEdge>(8,1,2,4);
cg.generateGraph(g, new DefaultVertexFactory(),null);
System.out.println(g.getOrder());
System.out.println(g.getSize());
System.out.println(g.getEdges(0, 3).size());
}
}
| Java |
public class Simple {
public static void main(String[] args) {
int k = 0;
final int j = 0 + k;
final int l = 0 + j;
final int m = 0 + l;
for (int i = 0; i < 10; i++) {
k = k + i;
}
System.out.println(k);
}
}
| Java |
import annas.graph.DefaultEdge;
import annas.graph.IntegerEdge;
import annas.graph.SimpleUndirectedGraph;
import annas.graph.UndirectedGraph;
import annas.graph.classifier.SplitRecogniser;
public class SplitRecogniserHarness {
public static void main(String[] args) {
test();
test_();
}
private static void test_() {
UndirectedGraph<String, DefaultEdge> graph = new UndirectedGraph<String, DefaultEdge>(
DefaultEdge.class);
String a = "A"; // u0
String b = "B";// u1
String c = "C";// u2
String d = "D";// u3
String e = "E";// u4
String f = "F";// u4
String g = "G";
graph.addVertex(a); // 1
graph.addVertex(b); // 2
graph.addVertex(c); // 3
graph.addVertex(d);// 4
graph.addVertex(e);// 5
graph.addVertex(f);// 5
graph.addVertex(g);// 5
graph.addEdge(a, b);
graph.addEdge(b, c);
graph.addEdge(c, a);
graph.addEdge(d, a);
graph.addEdge(d, b);
graph.addEdge(d, c);
graph.addEdge(e, f);
System.out.println(new SplitRecogniser().classify(graph));
}
public static void test() {
SimpleUndirectedGraph<Integer, IntegerEdge> graph = new SimpleUndirectedGraph<Integer, IntegerEdge>(
IntegerEdge.class);
for (int i = 0; i < 4; i++) {
graph.addVertex(i);
}
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
System.out.println(new SplitRecogniser().classify(graph));
}
}
| Java |
import annas.graph.GraphInterface;
import annas.graph.IntegerEdge;
import annas.graph.SimpleUndirectedGraph;
import annas.graph.generate.DefaultVertexFactory;
import annas.graph.generate.RandomGraph;
public class Harness_ {
/**
* @param args
*/
public static void main(String[] args) {
/* List<String> s = new ArrayList<String>();
s.add("red");
s.add("green");
s.add("blue");
//s.add("yellow");
SimpleCombinationGenerator<String> gen = new SimpleCombinationGenerator<String>(s, 2);
for(List<String> sa : gen){
System.out.println(sa);
}
PermutationGenerator<String> gen = new PermutationGenerator<String>(s);
for(List<String> sa : gen){
System.out.println(sa);
}*/
RandomGraph<Integer, IntegerEdge> rg = new RandomGraph<>(5, 2);
GraphInterface<Integer, IntegerEdge> g = new SimpleUndirectedGraph<>(IntegerEdge.class);
rg.generateGraph(g, new DefaultVertexFactory(), null);
System.out.println(g.getOrder());
System.out.println(g.getSize());
}
}
| Java |
public class Graph6 {
public static void main(String[] args) {
System.out.println(annas.misc.Graph6.decodeGraph("CT"));
}
}
| Java |
package test;
import annas.graph.WeightedEdgeInterface;
@SuppressWarnings("serial")
public class DefaultWeightedEdge implements WeightedEdgeInterface<String> {
private String head;
private String tail;
private double weight;
public DefaultWeightedEdge() {
super();
}
@Override
public String toString() {
return "Edge [head=" + head + ", tail=" + tail + "]";
}
@Override
public String getHead() {
return head;
}
@Override
public void setHead(String head) {
this.head = head;
}
@Override
public String getTail() {
return tail;
}
@Override
public void setTail(String tail) {
this.tail = tail;
}
@Override
public double getWeight() {
return this.weight;
}
@Override
public void setWeight(double weight) {
this.weight = weight;
}
@Override
public boolean isIncident(String vertex) {
// TODO Auto-generated method stub
return false;
}
@Override
public String getOtherEndpoint(String vertex) {
if (this.head.equals(vertex)) {
return this.tail;
} else {
return this.head;
}
}
}
| Java |
package test;
public class DataPath {
public static String PATH = "test_data/";
}
| Java |
package de.blinkt.openvpn.api;
import android.os.Parcel;
import android.os.Parcelable;
public class APIVpnProfile implements Parcelable {
public final String mUUID;
public final String mName;
public final boolean mUserEditable;
public APIVpnProfile(Parcel in) {
mUUID = in.readString();
mName = in.readString();
mUserEditable = in.readInt() != 0;
}
public APIVpnProfile(String uuidString, String name, boolean userEditable) {
mUUID=uuidString;
mName = name;
mUserEditable=userEditable;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mUUID);
dest.writeString(mName);
if(mUserEditable)
dest.writeInt(0);
else
dest.writeInt(1);
}
public static final Parcelable.Creator<APIVpnProfile> CREATOR
= new Parcelable.Creator<APIVpnProfile>() {
public APIVpnProfile createFromParcel(Parcel in) {
return new APIVpnProfile(in);
}
public APIVpnProfile[] newArray(int size) {
return new APIVpnProfile[size];
}
};
}
| Java |
package de.blinkt.openvpn.remote;
import android.app.Activity;
import android.app.Fragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import de.blinkt.openvpn.api.APIVpnProfile;
import de.blinkt.openvpn.api.IOpenVPNAPIService;
import de.blinkt.openvpn.api.IOpenVPNStatusCallback;
public class MainFragment extends Fragment implements View.OnClickListener, Handler.Callback {
private TextView mHelloWorld;
private Button mStartVpn;
private TextView mMyIp;
private TextView mStatus;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main, container, false);
v.findViewById(R.id.disconnect).setOnClickListener(this);
v.findViewById(R.id.getMyIP).setOnClickListener(this);
v.findViewById(R.id.startembedded).setOnClickListener(this);
mHelloWorld = (TextView) v.findViewById(R.id.helloworld);
mStartVpn = (Button) v.findViewById(R.id.startVPN);
mStatus = (TextView) v.findViewById(R.id.status);
mMyIp = (TextView) v.findViewById(R.id.MyIpText);
return v;
}
private static final int MSG_UPDATE_STATE = 0;
private static final int MSG_UPDATE_MYIP = 1;
private static final int START_PROFILE_EMBEDDED = 2;
private static final int START_PROFILE_BYUUID = 3;
private static final int ICS_OPENVPN_PERMISSION = 7;
protected IOpenVPNAPIService mService=null;
private Handler mHandler;
private void startEmbeddedProfile()
{
try {
InputStream conf = getActivity().getAssets().open("test.conf");
InputStreamReader isr = new InputStreamReader(conf);
BufferedReader br = new BufferedReader(isr);
String config="";
String line;
while(true) {
line = br.readLine();
if(line == null)
break;
config += line + "\n";
}
br.readLine();
// mService.addVPNProfile("test", config);
mService.startVPN(config);
} catch (IOException e) {
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onStart() {
super.onStart();
mHandler = new Handler(this);
bindService();
}
private IOpenVPNStatusCallback mCallback = new IOpenVPNStatusCallback.Stub() {
/**
* This is called by the remote service regularly to tell us about
* new values. Note that IPC calls are dispatched through a thread
* pool running in each process, so the code executing here will
* NOT be running in our main thread like most other things -- so,
* to update the UI, we need to use a Handler to hop over there.
*/
@Override
public void newStatus(String uuid, String state, String message, String level)
throws RemoteException {
Message msg = Message.obtain(mHandler, MSG_UPDATE_STATE, state + "|" + message);
msg.sendToTarget();
}
};
/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. We are communicating with our
// service through an IDL interface, so get a client-side
// representation of that from the raw service object.
mService = IOpenVPNAPIService.Stub.asInterface(service);
try {
// Request permission to use the API
Intent i = mService.prepare(getActivity().getPackageName());
if (i!=null) {
startActivityForResult(i, ICS_OPENVPN_PERMISSION);
} else {
onActivityResult(ICS_OPENVPN_PERMISSION, Activity.RESULT_OK,null);
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mService = null;
}
};
private String mStartUUID=null;
private void bindService() {
getActivity().bindService(new Intent(IOpenVPNAPIService.class.getName()),
mConnection, Context.BIND_AUTO_CREATE);
}
protected void listVPNs() {
try {
List<APIVpnProfile> list = mService.getProfiles();
String all="List:";
for(APIVpnProfile vp:list) {
all = all + vp.mName + ":" + vp.mUUID + "\n";
}
if(list.size()> 0) {
Button b= mStartVpn;
b.setOnClickListener(this);
b.setVisibility(View.VISIBLE);
b.setText(list.get(0).mName);
mStartUUID = list.get(0).mUUID;
}
mHelloWorld.setText(all);
} catch (RemoteException e) {
// TODO Auto-generated catch block
mHelloWorld.setText(e.getMessage());
}
}
private void unbindService() {
getActivity().unbindService(mConnection);
}
@Override
public void onStop() {
super.onStop();
unbindService();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.startVPN:
try {
prepareStartProfile(START_PROFILE_BYUUID);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
case R.id.disconnect:
try {
mService.disconnect();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.getMyIP:
// Socket handling is not allowed on main thread
new Thread() {
@Override
public void run() {
try {
String myip = getMyOwnIP();
Message msg = Message.obtain(mHandler,MSG_UPDATE_MYIP,myip);
msg.sendToTarget();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
break;
case R.id.startembedded:
try {
prepareStartProfile(START_PROFILE_EMBEDDED);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
default:
break;
}
}
private void prepareStartProfile(int requestCode) throws RemoteException {
Intent requestpermission = mService.prepareVPNService();
if(requestpermission == null) {
onActivityResult(requestCode, Activity.RESULT_OK, null);
} else {
// Have to call an external Activity since services cannot used onActivityResult
startActivityForResult(requestpermission, requestCode);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if(requestCode==START_PROFILE_EMBEDDED)
startEmbeddedProfile();
if(requestCode==START_PROFILE_BYUUID)
try {
mService.startProfile(mStartUUID);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (requestCode == ICS_OPENVPN_PERMISSION) {
listVPNs();
try {
mService.registerStatusCallback(mCallback);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
};
String getMyOwnIP() throws UnknownHostException, IOException, RemoteException,
IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
String resp="";
Socket client = new Socket();
// Setting Keep Alive forces creation of the underlying socket, otherwise getFD returns -1
client.setKeepAlive(true);
client.connect(new InetSocketAddress("v4address.com", 23),20000);
client.shutdownOutput();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
while (true) {
String line = in.readLine();
if( line == null)
return resp;
resp+=line;
}
}
@Override
public boolean handleMessage(Message msg) {
if(msg.what == MSG_UPDATE_STATE) {
mStatus.setText((CharSequence) msg.obj);
} else if (msg.what == MSG_UPDATE_MYIP) {
mMyIp.setText((CharSequence) msg.obj);
}
return true;
}
} | Java |
package de.blinkt.openvpn.remote;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new MainFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| Java |
package de.blinkt.vpndialogxposed;
import android.Manifest;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.*;
import android.os.Bundle;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
/**
* Created by arne on 06.10.13.
*/
public class AllowedVPNsChooser extends ListActivity {
public static final String ALLOWED_APPS = "allowedApps";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Collection<VpnApp> vpnApps = getVpnAppList();
ListAdapter la = new ArrayAdapter<VpnApp>(this, android.R.layout.simple_list_item_multiple_choice, vpnApps.toArray(new VpnApp[vpnApps.size()]));
setListAdapter(la);
setContentView(R.layout.vpnapplayout);
getListView().setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
Collection<String> allowedapps = getAllowedApps();
for(int i=0; i < vpnApps.size(); i++) {
VpnApp va= (VpnApp) getListView().getItemAtPosition(i);
boolean allowed = allowedapps.contains(va.mPkg);
getListView().setItemChecked(i,allowed);
}
}
private Collection<String> getAllowedApps(){
SharedPreferences prefs = getPreferences(MODE_WORLD_READABLE);
HashSet<String> defaultapps = new HashSet<String>();
defaultapps.add("de.blinkt.openvpn");
return prefs.getStringSet(ALLOWED_APPS,defaultapps );
}
private void saveAllowedApps(Set<String> allowedApps)
{
SharedPreferences prefs = getPreferences(MODE_WORLD_READABLE);
prefs.edit().putStringSet(ALLOWED_APPS,allowedApps)
.putInt("random",new Random().nextInt()).apply();
}
@Override
protected void onStop() {
super.onStop();
HashSet<String> allowedPkgs= new HashSet<String>();
for(int i=0;i < getListView().getChildCount();i++) {
if(getListView().getCheckedItemPositions().get(i)) {
allowedPkgs.add(((VpnApp)getListView().getItemAtPosition(i)).mPkg);
}
}
saveAllowedApps(allowedPkgs);
}
private Collection<VpnApp> getVpnAppList() {
PackageManager pm = getPackageManager();
Intent vpnOpen = new Intent();
vpnOpen.setAction("android.net.VpnService");
Vector<VpnApp> vpnApps = new Vector<VpnApp>();
// Hack but should work
for(PackageInfo pkg : pm.getInstalledPackages(PackageManager.GET_SERVICES)) {
if (pkg.services != null) {
for(ServiceInfo serviceInfo:pkg.services) {
if(Manifest.permission.BIND_VPN_SERVICE.equals(serviceInfo.permission))
vpnApps.add(new VpnApp(pkg.applicationInfo.loadLabel(pm), pkg.packageName));
}
}
}
/* public abstract List<ResolveInfo> queryIntentServicesAsUser(Intent intent,
int flags, int userId);
*/
/* This does not work ... */
/*
Class<?>[] queryIntentServicesAsUserSignature = {Intent.class, int.class, int.class};
try {
Method queryIntentServicesAsUser = pm.getClass().getMethod("queryIntentServicesAsUser", queryIntentServicesAsUserSignature);
List<ApplicationInfo> installedApps = pm.getInstalledApplications(0);
for (ApplicationInfo app : installedApps) {
List<ResolveInfo> apps;
if (app.packageName.equals(getPackageName())) {
apps = pm.queryIntentServices(vpnOpen, 0);
} else {
apps = (List<ResolveInfo>) queryIntentServicesAsUser.invoke(pm, vpnOpen, 0, app.uid);
}
for (ResolveInfo ri : apps) {
vpnApps.add(new VpnApp(ri.toString()));
}
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
*/
return vpnApps;
}
static class VpnApp {
private final String mPkg;
private CharSequence mName;
public VpnApp(CharSequence name, String pkg) {
mName = name;
mPkg = pkg;
}
@Override
public String toString() {
return mName.toString();
}
}
}
| Java |
package de.blinkt.vpndialogxposed;
import android.app.Activity;
import android.content.Context;
import android.os.IBinder;
import android.widget.Toast;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.XSharedPreferences;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import de.robv.android.xposed.IXposedHookZygoteInit;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
public class VpnDialogPatcher implements IXposedHookLoadPackage, IXposedHookZygoteInit {
public static final String MY_PACKAGE_NAME = AllowedVPNsChooser.class.getPackage().getName();
private static XSharedPreferences pref;
@Override
public void initZygote(StartupParam startupParam) throws Throwable {
pref = new XSharedPreferences(MY_PACKAGE_NAME, "AllowedVPNsChooser");
}
@Override
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
if (!lpparam.packageName.equals("com.android.vpndialogs"))
return;
XposedBridge.log("Got VPN Dialog");
XposedHelpers.findAndHookMethod("com.android.vpndialogs.ConfirmDialog", lpparam.classLoader,
"onResume", new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
// IConnectivityManager mService = IConnectivityManager.Stub.asInterface(
// ServiceManager.getService(Context.CONNECTIVITY_SERVICE));
try {
/*Class servicemanager = Class.forName("android.os.ServiceManager");
Method getService = servicemanager.getMethod("getService",String.class);
IConnectivityManager mService = IConnectivityManager.Stub.asInterface(
(IBinder) getService.invoke(servicemanager, Context.CONNECTIVITY_SERVICE));
*/
Object mService = XposedHelpers.getObjectField(param.thisObject, "mService");
String mPackage = ((Activity) param.thisObject).getCallingPackage();
// App is already allowed do nothing
/*if (mService.prepareVpn(mPackage, null)) {
return;
}*/
Class<?>[] prepareVPNsignature = {String.class, String.class};
if((Boolean) XposedHelpers.callMethod(mService,"prepareVpn",prepareVPNsignature, mPackage,(String)null))
return;
HashSet<String> blinktapp = new HashSet<String>();
blinktapp.add("de.blinkt.openvpn");
// blinktapp.add("de.blinkt.nothingset");
pref.reload();
Set<String> allowedApps = pref.getStringSet("allowedApps",blinktapp);
//Toast.makeText((Context)param.thisObject, "Allowed apps: " + allowedApps, Toast.LENGTH_LONG).show();
if (allowedApps.contains(mPackage)) {
//mService.prepareVpn(null, mPackage);
XposedHelpers.callMethod(mService,"prepareVpn",prepareVPNsignature, (String)null,mPackage);
((Activity) param.thisObject).setResult(Activity.RESULT_OK);
Toast.makeText((Context)param.thisObject,"Allowed VpnService app: " + mPackage,Toast.LENGTH_LONG).show();
((Activity) param.thisObject).finish();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
| Java |
package org.spongycastle.util.io.pem;
public interface PemObjectGenerator
{
PemObject generate()
throws PemGenerationException;
}
| Java |
package org.spongycastle.util.io.pem;
import java.io.IOException;
@SuppressWarnings("serial")
public class PemGenerationException
extends IOException
{
private Throwable cause;
public PemGenerationException(String message, Throwable cause)
{
super(message);
this.cause = cause;
}
public PemGenerationException(String message)
{
super(message);
}
public Throwable getCause()
{
return cause;
}
}
| Java |
package org.spongycastle.util.io.pem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@SuppressWarnings("all")
public class PemObject
implements PemObjectGenerator
{
private static final List EMPTY_LIST = Collections.unmodifiableList(new ArrayList());
private String type;
private List headers;
private byte[] content;
/**
* Generic constructor for object without headers.
*
* @param type pem object type.
* @param content the binary content of the object.
*/
public PemObject(String type, byte[] content)
{
this(type, EMPTY_LIST, content);
}
/**
* Generic constructor for object with headers.
*
* @param type pem object type.
* @param headers a list of PemHeader objects.
* @param content the binary content of the object.
*/
public PemObject(String type, List headers, byte[] content)
{
this.type = type;
this.headers = Collections.unmodifiableList(headers);
this.content = content;
}
public String getType()
{
return type;
}
public List getHeaders()
{
return headers;
}
public byte[] getContent()
{
return content;
}
public PemObject generate()
throws PemGenerationException
{
return this;
}
}
| Java |
package org.spongycastle.util.io.pem;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import org.spongycastle.util.encoders.Base64;
public class PemReader
extends BufferedReader
{
private static final String BEGIN = "-----BEGIN ";
private static final String END = "-----END ";
public PemReader(Reader reader)
{
super(reader);
}
public PemObject readPemObject()
throws IOException
{
String line = readLine();
while (line != null && !line.startsWith(BEGIN))
{
line = readLine();
}
if (line != null)
{
line = line.substring(BEGIN.length());
int index = line.indexOf('-');
String type = line.substring(0, index);
if (index > 0)
{
return loadObject(type);
}
}
return null;
}
private PemObject loadObject(String type)
throws IOException
{
String line;
String endMarker = END + type;
StringBuffer buf = new StringBuffer();
List headers = new ArrayList();
while ((line = readLine()) != null)
{
if (line.indexOf(":") >= 0)
{
int index = line.indexOf(':');
String hdr = line.substring(0, index);
String value = line.substring(index + 1).trim();
headers.add(new PemHeader(hdr, value));
continue;
}
if (line.indexOf(endMarker) != -1)
{
break;
}
buf.append(line.trim());
}
if (line == null)
{
throw new IOException(endMarker + " not found");
}
return new PemObject(type, headers, Base64.decode(buf.toString()));
}
}
| Java |
package org.spongycastle.util.io.pem;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import org.spongycastle.util.encoders.Base64;
/**
* A generic PEM writer, based on RFC 1421
*/
@SuppressWarnings("all")
public class PemWriter
extends BufferedWriter
{
private static final int LINE_LENGTH = 64;
private final int nlLength;
private char[] buf = new char[LINE_LENGTH];
/**
* Base constructor.
*
* @param out output stream to use.
*/
public PemWriter(Writer out)
{
super(out);
String nl = System.getProperty("line.separator");
if (nl != null)
{
nlLength = nl.length();
}
else
{
nlLength = 2;
}
}
/**
* Return the number of bytes or characters required to contain the
* passed in object if it is PEM encoded.
*
* @param obj pem object to be output
* @return an estimate of the number of bytes
*/
public int getOutputSize(PemObject obj)
{
// BEGIN and END boundaries.
int size = (2 * (obj.getType().length() + 10 + nlLength)) + 6 + 4;
if (!obj.getHeaders().isEmpty())
{
for (Iterator it = obj.getHeaders().iterator(); it.hasNext();)
{
PemHeader hdr = (PemHeader)it.next();
size += hdr.getName().length() + ": ".length() + hdr.getValue().length() + nlLength;
}
size += nlLength;
}
// base64 encoding
int dataLen = ((obj.getContent().length + 2) / 3) * 4;
size += dataLen + (((dataLen + LINE_LENGTH - 1) / LINE_LENGTH) * nlLength);
return size;
}
public void writeObject(PemObjectGenerator objGen)
throws IOException
{
PemObject obj = objGen.generate();
writePreEncapsulationBoundary(obj.getType());
if (!obj.getHeaders().isEmpty())
{
for (Iterator it = obj.getHeaders().iterator(); it.hasNext();)
{
PemHeader hdr = (PemHeader)it.next();
this.write(hdr.getName());
this.write(": ");
this.write(hdr.getValue());
this.newLine();
}
this.newLine();
}
writeEncoded(obj.getContent());
writePostEncapsulationBoundary(obj.getType());
}
private void writeEncoded(byte[] bytes)
throws IOException
{
bytes = Base64.encode(bytes);
for (int i = 0; i < bytes.length; i += buf.length)
{
int index = 0;
while (index != buf.length)
{
if ((i + index) >= bytes.length)
{
break;
}
buf[index] = (char)bytes[i + index];
index++;
}
this.write(buf, 0, index);
this.newLine();
}
}
private void writePreEncapsulationBoundary(
String type)
throws IOException
{
this.write("-----BEGIN " + type + "-----");
this.newLine();
}
private void writePostEncapsulationBoundary(
String type)
throws IOException
{
this.write("-----END " + type + "-----");
this.newLine();
}
}
| Java |
package org.spongycastle.util.io.pem;
public class PemHeader
{
private String name;
private String value;
public PemHeader(String name, String value)
{
this.name = name;
this.value = value;
}
public String getName()
{
return name;
}
public String getValue()
{
return value;
}
public int hashCode()
{
return getHashCode(this.name) + 31 * getHashCode(this.value);
}
public boolean equals(Object o)
{
if (!(o instanceof PemHeader))
{
return false;
}
PemHeader other = (PemHeader)o;
return other == this || (isEqual(this.name, other.name) && isEqual(this.value, other.value));
}
private int getHashCode(String s)
{
if (s == null)
{
return 1;
}
return s.hashCode();
}
private boolean isEqual(String s1, String s2)
{
if (s1 == s2)
{
return true;
}
if (s1 == null || s2 == null)
{
return false;
}
return s1.equals(s2);
}
}
| Java |
package org.spongycastle.util.encoders;
import java.io.IOException;
import java.io.OutputStream;
/**
* Encode and decode byte arrays (typically from binary to 7-bit ASCII
* encodings).
*/
public interface Encoder
{
int encode(byte[] data, int off, int length, OutputStream out) throws IOException;
int decode(byte[] data, int off, int length, OutputStream out) throws IOException;
int decode(String data, OutputStream out) throws IOException;
}
| Java |
package org.spongycastle.util.encoders;
import java.io.IOException;
import java.io.OutputStream;
public class Base64Encoder
implements Encoder
{
protected final byte[] encodingTable =
{
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v',
(byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6',
(byte)'7', (byte)'8', (byte)'9',
(byte)'+', (byte)'/'
};
protected byte padding = (byte)'=';
/*
* set up the decoding table.
*/
protected final byte[] decodingTable = new byte[128];
protected void initialiseDecodingTable()
{
for (int i = 0; i < encodingTable.length; i++)
{
decodingTable[encodingTable[i]] = (byte)i;
}
}
public Base64Encoder()
{
initialiseDecodingTable();
}
/**
* encode the input data producing a base 64 output stream.
*
* @return the number of bytes produced.
*/
public int encode(
byte[] data,
int off,
int length,
OutputStream out)
throws IOException
{
int modulus = length % 3;
int dataLength = (length - modulus);
int a1, a2, a3;
for (int i = off; i < off + dataLength; i += 3)
{
a1 = data[i] & 0xff;
a2 = data[i + 1] & 0xff;
a3 = data[i + 2] & 0xff;
out.write(encodingTable[(a1 >>> 2) & 0x3f]);
out.write(encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f]);
out.write(encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f]);
out.write(encodingTable[a3 & 0x3f]);
}
/*
* process the tail end.
*/
int b1, b2, b3;
int d1, d2;
switch (modulus)
{
case 0: /* nothing left to do */
break;
case 1:
d1 = data[off + dataLength] & 0xff;
b1 = (d1 >>> 2) & 0x3f;
b2 = (d1 << 4) & 0x3f;
out.write(encodingTable[b1]);
out.write(encodingTable[b2]);
out.write(padding);
out.write(padding);
break;
case 2:
d1 = data[off + dataLength] & 0xff;
d2 = data[off + dataLength + 1] & 0xff;
b1 = (d1 >>> 2) & 0x3f;
b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f;
b3 = (d2 << 2) & 0x3f;
out.write(encodingTable[b1]);
out.write(encodingTable[b2]);
out.write(encodingTable[b3]);
out.write(padding);
break;
}
return (dataLength / 3) * 4 + ((modulus == 0) ? 0 : 4);
}
private boolean ignore(
char c)
{
return (c == '\n' || c =='\r' || c == '\t' || c == ' ');
}
/**
* decode the base 64 encoded byte data writing it to the given output stream,
* whitespace characters will be ignored.
*
* @return the number of bytes produced.
*/
public int decode(
byte[] data,
int off,
int length,
OutputStream out)
throws IOException
{
byte b1, b2, b3, b4;
int outLen = 0;
int end = off + length;
while (end > off)
{
if (!ignore((char)data[end - 1]))
{
break;
}
end--;
}
int i = off;
int finish = end - 4;
i = nextI(data, i, finish);
while (i < finish)
{
b1 = decodingTable[data[i++]];
i = nextI(data, i, finish);
b2 = decodingTable[data[i++]];
i = nextI(data, i, finish);
b3 = decodingTable[data[i++]];
i = nextI(data, i, finish);
b4 = decodingTable[data[i++]];
out.write((b1 << 2) | (b2 >> 4));
out.write((b2 << 4) | (b3 >> 2));
out.write((b3 << 6) | b4);
outLen += 3;
i = nextI(data, i, finish);
}
outLen += decodeLastBlock(out, (char)data[end - 4], (char)data[end - 3], (char)data[end - 2], (char)data[end - 1]);
return outLen;
}
private int nextI(byte[] data, int i, int finish)
{
while ((i < finish) && ignore((char)data[i]))
{
i++;
}
return i;
}
/**
* decode the base 64 encoded String data writing it to the given output stream,
* whitespace characters will be ignored.
*
* @return the number of bytes produced.
*/
public int decode(
String data,
OutputStream out)
throws IOException
{
byte b1, b2, b3, b4;
int length = 0;
int end = data.length();
while (end > 0)
{
if (!ignore(data.charAt(end - 1)))
{
break;
}
end--;
}
int i = 0;
int finish = end - 4;
i = nextI(data, i, finish);
while (i < finish)
{
b1 = decodingTable[data.charAt(i++)];
i = nextI(data, i, finish);
b2 = decodingTable[data.charAt(i++)];
i = nextI(data, i, finish);
b3 = decodingTable[data.charAt(i++)];
i = nextI(data, i, finish);
b4 = decodingTable[data.charAt(i++)];
out.write((b1 << 2) | (b2 >> 4));
out.write((b2 << 4) | (b3 >> 2));
out.write((b3 << 6) | b4);
length += 3;
i = nextI(data, i, finish);
}
length += decodeLastBlock(out, data.charAt(end - 4), data.charAt(end - 3), data.charAt(end - 2), data.charAt(end - 1));
return length;
}
private int decodeLastBlock(OutputStream out, char c1, char c2, char c3, char c4)
throws IOException
{
byte b1, b2, b3, b4;
if (c3 == padding)
{
b1 = decodingTable[c1];
b2 = decodingTable[c2];
out.write((b1 << 2) | (b2 >> 4));
return 1;
}
else if (c4 == padding)
{
b1 = decodingTable[c1];
b2 = decodingTable[c2];
b3 = decodingTable[c3];
out.write((b1 << 2) | (b2 >> 4));
out.write((b2 << 4) | (b3 >> 2));
return 2;
}
else
{
b1 = decodingTable[c1];
b2 = decodingTable[c2];
b3 = decodingTable[c3];
b4 = decodingTable[c4];
out.write((b1 << 2) | (b2 >> 4));
out.write((b2 << 4) | (b3 >> 2));
out.write((b3 << 6) | b4);
return 3;
}
}
private int nextI(String data, int i, int finish)
{
while ((i < finish) && ignore(data.charAt(i)))
{
i++;
}
return i;
}
}
| Java |
package org.spongycastle.util.encoders;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Base64
{
private static final Encoder encoder = new Base64Encoder();
/**
* encode the input data producing a base 64 encoded byte array.
*
* @return a byte array containing the base 64 encoded data.
*/
public static byte[] encode(
byte[] data)
{
int len = (data.length + 2) / 3 * 4;
ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
try
{
encoder.encode(data, 0, data.length, bOut);
}
catch (IOException e)
{
throw new RuntimeException("exception encoding base64 string: " + e);
}
return bOut.toByteArray();
}
/**
* Encode the byte data to base 64 writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public static int encode(
byte[] data,
OutputStream out)
throws IOException
{
return encoder.encode(data, 0, data.length, out);
}
/**
* Encode the byte data to base 64 writing it to the given output stream.
*
* @return the number of bytes produced.
*/
public static int encode(
byte[] data,
int off,
int length,
OutputStream out)
throws IOException
{
return encoder.encode(data, off, length, out);
}
/**
* decode the base 64 encoded input data. It is assumed the input data is valid.
*
* @return a byte array representing the decoded data.
*/
public static byte[] decode(
byte[] data)
{
int len = data.length / 4 * 3;
ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
try
{
encoder.decode(data, 0, data.length, bOut);
}
catch (IOException e)
{
throw new RuntimeException("exception decoding base64 string: " + e);
}
return bOut.toByteArray();
}
/**
* decode the base 64 encoded String data - whitespace will be ignored.
*
* @return a byte array representing the decoded data.
*/
public static byte[] decode(
String data)
{
int len = data.length() / 4 * 3;
ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
try
{
encoder.decode(data, bOut);
}
catch (IOException e)
{
throw new RuntimeException("exception decoding base64 string: " + e);
}
return bOut.toByteArray();
}
/**
* decode the base 64 encoded String data writing it to the given output stream,
* whitespace characters will be ignored.
*
* @return the number of bytes produced.
*/
public static int decode(
String data,
OutputStream out)
throws IOException
{
return encoder.decode(data, out);
}
}
| Java |
package de.blinkt.openvpn.activities;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.provider.OpenableColumns;
import android.security.KeyChain;
import android.security.KeyChainAliasCallback;
import android.text.TextUtils;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import junit.framework.Assert;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
import de.blinkt.openvpn.core.ConfigParser;
import de.blinkt.openvpn.core.ConfigParser.ConfigParseError;
import de.blinkt.openvpn.core.ProfileManager;
import de.blinkt.openvpn.fragments.Utils;
import de.blinkt.openvpn.views.FileSelectLayout;
import static de.blinkt.openvpn.views.FileSelectLayout.FileSelectCallback;
public class ConfigConverter extends Activity implements FileSelectCallback {
public static final String IMPORT_PROFILE = "de.blinkt.openvpn.IMPORT_PROFILE";
private static final int RESULT_INSTALLPKCS12 = 7;
private static final int CHOOSE_FILE_OFFSET = 1000;
public static final String VPNPROFILE = "vpnProfile";
private VpnProfile mResult;
private transient List<String> mPathsegments;
private String mAliasName = null;
private Map<Utils.FileType, FileSelectLayout> fileSelectMap = new HashMap<Utils.FileType, FileSelectLayout>();
private String mEmbeddedPwFile;
private Vector<String> mLogEntries = new Vector<String>();
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.cancel) {
setResult(Activity.RESULT_CANCELED);
finish();
} else if (item.getItemId() == R.id.ok) {
if (mResult == null) {
log("Importing the config had error, cannot save it");
return true;
}
Intent in = installPKCS12();
if (in != null)
startActivityForResult(in, RESULT_INSTALLPKCS12);
else
saveProfile();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onSaveInstanceState(@NotNull Bundle outState) {
super.onSaveInstanceState(outState);
if (mResult != null)
outState.putSerializable(VPNPROFILE, mResult);
outState.putString("mAliasName", mAliasName);
String[] logentries = mLogEntries.toArray(new String[mLogEntries.size()]);
outState.putStringArray("logentries", logentries);
int[] fileselects = new int[fileSelectMap.size()];
int k = 0;
for (Utils.FileType key : fileSelectMap.keySet()) {
fileselects[k] = key.getValue();
k++;
}
outState.putIntArray("fileselects", fileselects);
outState.putString("pwfile",mEmbeddedPwFile);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
if (requestCode == RESULT_INSTALLPKCS12 && resultCode == Activity.RESULT_OK) {
showCertDialog();
}
if (resultCode == Activity.RESULT_OK && requestCode >= CHOOSE_FILE_OFFSET) {
Utils.FileType type = Utils.FileType.getFileTypeByValue(requestCode - CHOOSE_FILE_OFFSET);
FileSelectLayout fs = fileSelectMap.get(type);
fs.parseResponse(result, this);
String data = fs.getData();
switch (type) {
case USERPW_FILE:
mEmbeddedPwFile = data;
break;
case PKCS12:
mResult.mPKCS12Filename = data;
break;
case TLS_AUTH_FILE:
mResult.mTLSAuthFilename = data;
break;
case CA_CERTIFICATE:
mResult.mCaFilename = data;
break;
case CLIENT_CERTIFICATE:
mResult.mClientCertFilename = data;
break;
case KEYFILE:
mResult.mClientKeyFilename = data;
break;
default:
Assert.fail();
}
}
super.onActivityResult(requestCode, resultCode, result);
}
private void saveProfile() {
Intent result = new Intent();
ProfileManager vpl = ProfileManager.getInstance(this);
if (!TextUtils.isEmpty(mEmbeddedPwFile))
ConfigParser.useEmbbedUserAuth(mResult, mEmbeddedPwFile);
vpl.addProfile(mResult);
vpl.saveProfile(this, mResult);
vpl.saveProfileList(this);
result.putExtra(VpnProfile.EXTRA_PROFILEUUID, mResult.getUUID().toString());
setResult(Activity.RESULT_OK, result);
finish();
}
public void showCertDialog() {
try {
KeyChain.choosePrivateKeyAlias(this,
new KeyChainAliasCallback() {
public void alias(String alias) {
// Credential alias selected. Remember the alias selection for future use.
mResult.mAlias = alias;
saveProfile();
}
},
new String[]{"RSA"}, // List of acceptable key types. null for any
null, // issuer, null for any
mResult.mServerName, // host name of server requesting the cert, null if unavailable
-1, // port of server requesting the cert, -1 if unavailable
mAliasName); // alias to preselect, null if unavailable
} catch (ActivityNotFoundException anf) {
Builder ab = new AlertDialog.Builder(this);
ab.setTitle(R.string.broken_image_cert_title);
ab.setMessage(R.string.broken_image_cert);
ab.setPositiveButton(android.R.string.ok, null);
ab.show();
}
}
private Intent installPKCS12() {
if (!((CheckBox) findViewById(R.id.importpkcs12)).isChecked()) {
setAuthTypeToEmbeddedPKCS12();
return null;
}
String pkcs12datastr = mResult.mPKCS12Filename;
if (VpnProfile.isEmbedded(pkcs12datastr)) {
Intent inkeyIntent = KeyChain.createInstallIntent();
pkcs12datastr = VpnProfile.getEmbeddedContent(pkcs12datastr);
byte[] pkcs12data = Base64.decode(pkcs12datastr, Base64.DEFAULT);
inkeyIntent.putExtra(KeyChain.EXTRA_PKCS12, pkcs12data);
if (mAliasName.equals(""))
mAliasName = null;
if (mAliasName != null) {
inkeyIntent.putExtra(KeyChain.EXTRA_NAME, mAliasName);
}
return inkeyIntent;
}
return null;
}
private void setAuthTypeToEmbeddedPKCS12() {
if (VpnProfile.isEmbedded(mResult.mPKCS12Filename)) {
if (mResult.mAuthenticationType == VpnProfile.TYPE_USERPASS_KEYSTORE)
mResult.mAuthenticationType = VpnProfile.TYPE_USERPASS_PKCS12;
if (mResult.mAuthenticationType == VpnProfile.TYPE_KEYSTORE)
mResult.mAuthenticationType = VpnProfile.TYPE_PKCS12;
}
}
private String getUniqueProfileName(String possibleName) {
int i = 0;
ProfileManager vpl = ProfileManager.getInstance(this);
String newname = possibleName;
// Default to
if (mResult.mName != null && !ConfigParser.CONVERTED_PROFILE.equals(mResult.mName))
newname = mResult.mName;
while (newname == null || vpl.getProfileByName(newname) != null) {
i++;
if (i == 1)
newname = getString(R.string.converted_profile);
else
newname = getString(R.string.converted_profile_i, i);
}
return newname;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.import_menu, menu);
return true;
}
private String embedFile(String filename, Utils.FileType type) {
if (filename == null)
return null;
// Already embedded, nothing to do
if (VpnProfile.isEmbedded(filename))
return filename;
File possibleFile = findFile(filename, type);
if (possibleFile == null)
return filename;
else
return readFileContent(possibleFile, type == Utils.FileType.PKCS12);
}
private File findFile(String filename, Utils.FileType fileType) {
File foundfile = findFileRaw(filename);
if (foundfile == null && filename != null && !filename.equals("")) {
log(R.string.import_could_not_open, filename);
addFileSelectDialog(fileType);
}
return foundfile;
}
private void addFileSelectDialog(Utils.FileType type) {
int titleRes = 0;
String value = null;
switch (type) {
case KEYFILE:
titleRes = R.string.client_key_title;
if (mResult != null)
value = mResult.mClientKeyFilename;
break;
case CLIENT_CERTIFICATE:
titleRes = R.string.client_certificate_title;
if (mResult != null)
value = mResult.mClientCertFilename;
break;
case CA_CERTIFICATE:
titleRes = R.string.ca_title;
if (mResult != null)
value = mResult.mCaFilename;
break;
case TLS_AUTH_FILE:
titleRes = R.string.tls_auth_file;
if (mResult != null)
value = mResult.mTLSAuthFilename;
break;
case PKCS12:
titleRes = R.string.client_pkcs12_title;
if (mResult != null)
value = mResult.mPKCS12Filename;
break;
case USERPW_FILE:
titleRes = R.string.userpw_file;
value = mEmbeddedPwFile;
break;
}
boolean isCert = type == Utils.FileType.CA_CERTIFICATE || type == Utils.FileType.CLIENT_CERTIFICATE;
FileSelectLayout fl = new FileSelectLayout(this, getString(titleRes), isCert);
fileSelectMap.put(type, fl);
fl.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
((LinearLayout) findViewById(R.id.config_convert_root)).addView(fl, 2);
findViewById(R.id.files_missing_hint).setVisibility(View.VISIBLE);
fl.setData(value, this);
int i = getFileLayoutOffset(type);
fl.setCaller(this, i, type);
}
private int getFileLayoutOffset(Utils.FileType type) {
return CHOOSE_FILE_OFFSET + type.getValue();
}
private File findFileRaw(String filename) {
if (filename == null || filename.equals(""))
return null;
// Try diffent path relative to /mnt/sdcard
File sdcard = Environment.getExternalStorageDirectory();
File root = new File("/");
HashSet<File> dirlist = new HashSet<File>();
for (int i = mPathsegments.size() - 1; i >= 0; i--) {
String path = "";
for (int j = 0; j <= i; j++) {
path += "/" + mPathsegments.get(j);
}
// Do a little hackish dance for the Android File Importer
// /document/primary:ovpn/openvpn-imt.conf
if (path.indexOf(':') != -1 && path.indexOf('/') != -1) {
String possibleDir = path.substring(path.indexOf(':') + 1, path.length());
possibleDir = possibleDir.substring(0, possibleDir.lastIndexOf('/'));
dirlist.add(new File(sdcard, possibleDir));
}
dirlist.add(new File(path));
}
dirlist.add(sdcard);
dirlist.add(root);
String[] fileparts = filename.split("/");
for (File rootdir : dirlist) {
String suffix = "";
for (int i = fileparts.length - 1; i >= 0; i--) {
if (i == fileparts.length - 1)
suffix = fileparts[i];
else
suffix = fileparts[i] + "/" + suffix;
File possibleFile = new File(rootdir, suffix);
if (!possibleFile.canRead())
continue;
// read the file inline
return possibleFile;
}
}
return null;
}
String readFileContent(File possibleFile, boolean base64encode) {
byte[] filedata;
try {
filedata = readBytesFromFile(possibleFile);
} catch (IOException e) {
log(e.getLocalizedMessage());
return null;
}
String data;
if (base64encode) {
data = Base64.encodeToString(filedata, Base64.DEFAULT);
} else {
data = new String(filedata);
}
return VpnProfile.DISPLAYNAME_TAG + possibleFile.getName() + VpnProfile.INLINE_TAG + data;
}
private byte[] readBytesFromFile(File file) throws IOException {
InputStream input = new FileInputStream(file);
long len = file.length();
if (len > VpnProfile.MAX_EMBED_FILE_SIZE)
throw new IOException("File size of file to import too large.");
// Create the byte array to hold the data
byte[] bytes = new byte[(int) len];
// Read in the bytes
int offset = 0;
int bytesRead;
while (offset < bytes.length
&& (bytesRead = input.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += bytesRead;
}
input.close();
return bytes;
}
void embedFiles() {
// This where I would like to have a c++ style
// void embedFile(std::string & option)
if (mResult.mPKCS12Filename != null) {
File pkcs12file = findFileRaw(mResult.mPKCS12Filename);
if (pkcs12file != null) {
mAliasName = pkcs12file.getName().replace(".p12", "");
} else {
mAliasName = "Imported PKCS12";
}
}
mResult.mCaFilename = embedFile(mResult.mCaFilename, Utils.FileType.CA_CERTIFICATE);
mResult.mClientCertFilename = embedFile(mResult.mClientCertFilename, Utils.FileType.CLIENT_CERTIFICATE);
mResult.mClientKeyFilename = embedFile(mResult.mClientKeyFilename, Utils.FileType.KEYFILE);
mResult.mTLSAuthFilename = embedFile(mResult.mTLSAuthFilename, Utils.FileType.TLS_AUTH_FILE);
mResult.mPKCS12Filename = embedFile(mResult.mPKCS12Filename, Utils.FileType.PKCS12);
mEmbeddedPwFile = embedFile(mResult.mPassword, Utils.FileType.USERPW_FILE);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.config_converter);
super.onCreate(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(VPNPROFILE)) {
mResult = (VpnProfile) savedInstanceState.getSerializable(VPNPROFILE);
mAliasName = savedInstanceState.getString("mAliasName");
mEmbeddedPwFile = savedInstanceState.getString("pwfile");
if (savedInstanceState.containsKey("logentries")) {
//noinspection ConstantConditions
for (String logItem : savedInstanceState.getStringArray("logentries"))
log(logItem);
}
if (savedInstanceState.containsKey("fileselects")) {
//noinspection ConstantConditions
for (int k : savedInstanceState.getIntArray("fileselects")) {
addFileSelectDialog(Utils.FileType.getFileTypeByValue(k));
}
}
return;
}
final android.content.Intent intent = getIntent();
if (intent != null) {
final android.net.Uri data = intent.getData();
if (data != null) {
//log(R.string.import_experimental);
log(R.string.importing_config, data.toString());
try {
String possibleName = null;
if ((data.getScheme() != null && data.getScheme().equals("file")) ||
(data.getLastPathSegment() != null &&
(data.getLastPathSegment().endsWith(".ovpn") ||
data.getLastPathSegment().endsWith(".conf")))
) {
possibleName = data.getLastPathSegment();
if (possibleName.lastIndexOf('/') != -1)
possibleName = possibleName.substring(possibleName.lastIndexOf('/') + 1);
}
InputStream is = getContentResolver().openInputStream(data);
mPathsegments = data.getPathSegments();
Cursor cursor = getContentResolver().query(data, null, null, null, null);
try {
if (cursor!=null && cursor.moveToFirst()) {
int cidx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (cidx != -1) {
String displayName = cursor.getString(cidx);
if (displayName != null)
possibleName = displayName;
}
cidx = cursor.getColumnIndex("mime_type");
if (cidx != -1) {
log("Opening Mime TYPE: " + cursor.getString(cidx));
}
}
} finally {
if(cursor!=null)
cursor.close();
}
if (possibleName != null) {
possibleName = possibleName.replace(".ovpn", "");
possibleName = possibleName.replace(".conf", "");
}
doImport(is, possibleName);
} catch (FileNotFoundException e) {
log(R.string.import_content_resolve_error);
}
}
// We parsed the intent, relay on saved instance for restoring
setIntent(null);
}
}
@Override
protected void onStart() {
super.onStart();
}
private void log(String logmessage) {
mLogEntries.add(logmessage);
TextView tv = new TextView(this);
tv.setText(logmessage);
LinearLayout logLayout = (LinearLayout) findViewById(R.id.config_convert_root);
logLayout.addView(tv);
}
private void doImport(InputStream is, String newName) {
ConfigParser cp = new ConfigParser();
try {
InputStreamReader isr = new InputStreamReader(is);
cp.parseConfig(isr);
mResult = cp.convertProfile();
embedFiles();
displayWarnings();
mResult.mName = getUniqueProfileName(newName);
log(R.string.import_done);
return;
} catch (IOException e) {
log(R.string.error_reading_config_file);
log(e.getLocalizedMessage());
} catch (ConfigParseError e) {
log(R.string.error_reading_config_file);
log(e.getLocalizedMessage());
}
mResult = null;
}
private void displayWarnings() {
if (mResult.mUseCustomConfig) {
log(R.string.import_warning_custom_options);
String copt = mResult.mCustomConfigOptions;
if (copt.startsWith("#")) {
int until = copt.indexOf('\n');
copt = copt.substring(until + 1);
}
log(copt);
}
if (mResult.mAuthenticationType == VpnProfile.TYPE_KEYSTORE ||
mResult.mAuthenticationType == VpnProfile.TYPE_USERPASS_KEYSTORE) {
findViewById(R.id.importpkcs12).setVisibility(View.VISIBLE);
}
}
private void log(int ressourceId, Object... formatArgs) {
log(getString(ressourceId, formatArgs));
}
}
| Java |
package de.blinkt.openvpn.activities;
import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.fragments.LogFragment;
/**
* Created by arne on 13.10.13.
*/
public class LogWindow extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.log_window);
getActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new LogFragment())
.commit();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
| Java |
package de.blinkt.openvpn.activities;
import java.util.List;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.view.Menu;
import android.view.MenuItem;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
import de.blinkt.openvpn.core.ProfileManager;
import de.blinkt.openvpn.fragments.Settings_Authentication;
import de.blinkt.openvpn.fragments.Settings_Basic;
import de.blinkt.openvpn.fragments.Settings_IP;
import de.blinkt.openvpn.fragments.Settings_Obscure;
import de.blinkt.openvpn.fragments.Settings_Routing;
import de.blinkt.openvpn.fragments.ShowConfigFragment;
import de.blinkt.openvpn.fragments.VPNProfileList;
public class VPNPreferences extends PreferenceActivity {
static final Class validFragments[] = new Class[] {
Settings_Authentication.class, Settings_Basic.class, Settings_IP.class,
Settings_Obscure.class, Settings_Routing.class, ShowConfigFragment.class
};
private String mProfileUUID;
private VpnProfile mProfile;
public VPNPreferences() {
super();
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected boolean isValidFragment(String fragmentName) {
for (Class c: validFragments)
if (c.getName().equals(fragmentName))
return true;
return false;
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString(getIntent().getStringExtra(getPackageName() + ".profileUUID"),mProfileUUID);
super.onSaveInstanceState(outState);
}
@Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
if(intent!=null) {
String profileUUID = intent.getStringExtra(getPackageName() + ".profileUUID");
if(profileUUID==null) {
Bundle initialArguments = getIntent().getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS);
profileUUID = initialArguments.getString(getPackageName() + ".profileUUID");
}
if(profileUUID!=null){
mProfileUUID = profileUUID;
mProfile = ProfileManager.get(this,mProfileUUID);
}
}
// When a profile is deleted from a category fragment in hadset mod we need to finish
// this activity as well when returning
if (mProfile==null || mProfile.profileDleted) {
setResult(VPNProfileList.RESULT_VPN_DELETED);
finish();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
mProfileUUID = getIntent().getStringExtra(getPackageName() + ".profileUUID");
if(savedInstanceState!=null){
String savedUUID = savedInstanceState.getString(getPackageName() + ".profileUUID");
if(savedUUID!=null)
mProfileUUID=savedUUID;
}
mProfile = ProfileManager.get(this,mProfileUUID);
if(mProfile!=null) {
setTitle(getString(R.string.edit_profile_title, mProfile.getName()));
}
super.onCreate(savedInstanceState);
}
@Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.vpn_headers, target);
for (Header header : target) {
if(header.fragmentArguments==null)
header.fragmentArguments = new Bundle();
header.fragmentArguments.putString(getPackageName() + ".profileUUID",mProfileUUID);
}
}
@Override
public void onBackPressed() {
setResult(RESULT_OK, getIntent());
super.onBackPressed();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.remove_vpn)
askProfileRemoval();
return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.vpnpreferences_menu, menu);
return super.onCreateOptionsMenu(menu);
}
private void askProfileRemoval() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Confirm deletion");
dialog.setMessage(getString(R.string.remove_vpn_query, mProfile.mName));
dialog.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
removeProfile(mProfile);
}
});
dialog.setNegativeButton(android.R.string.no,null);
dialog.create().show();
}
protected void removeProfile(VpnProfile profile) {
ProfileManager.getInstance(this).removeProfile(this,profile);
setResult(VPNProfileList.RESULT_VPN_DELETED);
finish();
}
}
| Java |
package de.blinkt.openvpn.activities;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import de.blinkt.openvpn.LaunchVPN;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
import de.blinkt.openvpn.core.ProfileManager;
import java.util.Collection;
import java.util.Vector;
/**
* This Activity actually handles two stages of a launcher shortcut's life cycle.
*
* 1. Your application offers to provide shortcuts to the launcher. When
* the user installs a shortcut, an activity within your application
* generates the actual shortcut and returns it to the launcher, where it
* is shown to the user as an icon.
*
* 2. Any time the user clicks on an installed shortcut, an intent is sent.
* Typically this would then be handled as necessary by an activity within
* your application.
*
* We handle stage 1 (creating a shortcut) by simply sending back the information (in the form
* of an {@link android.content.Intent} that the launcher will use to create the shortcut.
*
* You can also implement this in an interactive way, by having your activity actually present
* UI for the user to select the specific nature of the shortcut, such as a contact, picture, URL,
* media item, or action.
*
* We handle stage 2 (responding to a shortcut) in this sample by simply displaying the contents
* of the incoming {@link android.content.Intent}.
*
* In a real application, you would probably use the shortcut intent to display specific content
* or start a particular operation.
*/
public class CreateShortcuts extends ListActivity implements OnItemClickListener {
private static final int START_VPN_PROFILE= 70;
private ProfileManager mPM;
private VpnProfile mSelectedProfile;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mPM =ProfileManager.getInstance(this);
}
@Override
protected void onStart() {
super.onStart();
// Resolve the intent
createListView();
}
private void createListView() {
ListView lv = getListView();
//lv.setTextFilterEnabled(true);
Collection<VpnProfile> vpnList = mPM.getProfiles();
Vector<String> vpnNames=new Vector<String>();
for (VpnProfile vpnProfile : vpnList) {
vpnNames.add(vpnProfile.mName);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,vpnNames);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
/**
* This function creates a shortcut and returns it to the caller. There are actually two
* intents that you will send back.
*
* The first intent serves as a container for the shortcut and is returned to the launcher by
* setResult(). This intent must contain three fields:
*
* <ul>
* <li>{@link android.content.Intent#EXTRA_SHORTCUT_INTENT} The shortcut intent.</li>
* <li>{@link android.content.Intent#EXTRA_SHORTCUT_NAME} The text that will be displayed with
* the shortcut.</li>
* <li>{@link android.content.Intent#EXTRA_SHORTCUT_ICON} The shortcut's icon, if provided as a
* bitmap, <i>or</i> {@link android.content.Intent#EXTRA_SHORTCUT_ICON_RESOURCE} if provided as
* a drawable resource.</li>
* </ul>
*
* If you use a simple drawable resource, note that you must wrapper it using
* {@link android.content.Intent.ShortcutIconResource}, as shown below. This is required so
* that the launcher can access resources that are stored in your application's .apk file. If
* you return a bitmap, such as a thumbnail, you can simply put the bitmap into the extras
* bundle using {@link android.content.Intent#EXTRA_SHORTCUT_ICON}.
*
* The shortcut intent can be any intent that you wish the launcher to send, when the user
* clicks on the shortcut. Typically this will be {@link android.content.Intent#ACTION_VIEW}
* with an appropriate Uri for your content, but any Intent will work here as long as it
* triggers the desired action within your Activity.
* @param profile
*/
private void setupShortcut(VpnProfile profile) {
// First, set up the shortcut intent. For this example, we simply create an intent that
// will bring us directly back to this activity. A more typical implementation would use a
// data Uri in order to display a more specific result, or a custom action in order to
// launch a specific operation.
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClass(this, LaunchVPN.class);
shortcutIntent.putExtra(LaunchVPN.EXTRA_KEY,profile.getUUID().toString());
// Then, set up the container intent (the response to the caller)
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, profile.getName());
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(
this, R.drawable.icon);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
// Now, return the result to the launcher
setResult(RESULT_OK, intent);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String profileName = ((TextView) view).getText().toString();
VpnProfile profile = mPM.getProfileByName(profileName);
setupShortcut(profile);
finish();
}
}
| Java |
package de.blinkt.openvpn.activities;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.*;
import android.os.IBinder;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.core.OpenVpnService;
import de.blinkt.openvpn.core.ProfileManager;
/**
* Created by arne on 13.10.13.
*/
public class DisconnectVPN extends Activity implements DialogInterface.OnClickListener{
protected OpenVpnService mService;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
OpenVpnService.LocalBinder binder = (OpenVpnService.LocalBinder) service;
mService = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mService =null;
}
};
@Override
protected void onResume() {
super.onResume();
Intent intent = new Intent(this, OpenVpnService.class);
intent.setAction(OpenVpnService.START_SERVICE);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
showDisconnectDialog();
}
@Override
protected void onStop() {
super.onStop();
unbindService(mConnection);
}
// if (getIntent() !=null && OpenVpnService.DISCONNECT_VPN.equals(getIntent().getAction()))
// setIntent(null);
/*
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
*/
private void showDisconnectDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.title_cancel);
builder.setMessage(R.string.cancel_connection_query);
builder.setNegativeButton(android.R.string.no, this);
builder.setPositiveButton(android.R.string.yes,this);
builder.show();
}
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
ProfileManager.setConntectedVpnProfileDisconnected(this);
if (mService != null && mService.getManagement() != null)
mService.getManagement().stopVPN();
}
finish();
}
}
| Java |
package de.blinkt.openvpn.activities;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
import de.blinkt.openvpn.fragments.FileSelectionFragment;
import de.blinkt.openvpn.fragments.InlineFileTab;
public class FileSelect extends Activity {
public static final String RESULT_DATA = "RESULT_PATH";
public static final String START_DATA = "START_DATA";
public static final String WINDOW_TITLE = "WINDOW_TILE";
public static final String NO_INLINE_SELECTION = "de.blinkt.openvpn.NO_INLINE_SELECTION";
public static final String SHOW_CLEAR_BUTTON = "de.blinkt.openvpn.SHOW_CLEAR_BUTTON";
public static final String DO_BASE64_ENCODE = "de.blinkt.openvpn.BASE64ENCODE";
private FileSelectionFragment mFSFragment;
private InlineFileTab mInlineFragment;
private String mData;
private Tab inlineFileTab;
private Tab fileExplorerTab;
private boolean mNoInline;
private boolean mShowClear;
private boolean mBase64Encode;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.file_dialog);
mData = getIntent().getStringExtra(START_DATA);
if(mData==null)
mData=Environment.getExternalStorageDirectory().getPath();
String title = getIntent().getStringExtra(WINDOW_TITLE);
int titleId = getIntent().getIntExtra(WINDOW_TITLE, 0);
if(titleId!=0)
title =getString(titleId);
if(title!=null)
setTitle(title);
mNoInline = getIntent().getBooleanExtra(NO_INLINE_SELECTION, false);
mShowClear = getIntent().getBooleanExtra(SHOW_CLEAR_BUTTON, false);
mBase64Encode = getIntent().getBooleanExtra(DO_BASE64_ENCODE, false);
ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
fileExplorerTab = bar.newTab().setText(R.string.file_explorer_tab);
inlineFileTab = bar.newTab().setText(R.string.inline_file_tab);
mFSFragment = new FileSelectionFragment();
fileExplorerTab.setTabListener(new MyTabsListener<FileSelectionFragment>(this, mFSFragment));
bar.addTab(fileExplorerTab);
if(!mNoInline) {
mInlineFragment = new InlineFileTab();
inlineFileTab.setTabListener(new MyTabsListener<InlineFileTab>(this, mInlineFragment));
bar.addTab(inlineFileTab);
} else {
mFSFragment.setNoInLine();
}
}
public boolean showClear() {
if(mData == null || mData.equals(""))
return false;
else
return mShowClear;
}
protected class MyTabsListener<T extends Fragment> implements ActionBar.TabListener
{
private Fragment mFragment;
private boolean mAdded=false;
public MyTabsListener( Activity activity, Fragment fragment){
this.mFragment = fragment;
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (!mAdded) {
// If not, instantiate and add it to the activity
ft.add(android.R.id.content, mFragment);
mAdded =true;
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.detach(mFragment);
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
public void importFile(String path) {
File ifile = new File(path);
Exception fe = null;
try {
String data = "";
byte[] fileData = readBytesFromFile(ifile) ;
if(mBase64Encode)
data += Base64.encodeToString(fileData, Base64.DEFAULT);
else
data += new String(fileData);
mData =data;
/*
mInlineFragment.setData(data);
getActionBar().selectTab(inlineFileTab); */
saveInlineData(ifile.getName(), data);
} catch (FileNotFoundException e) {
fe = e;
} catch (IOException e) {
fe =e;
}
if(fe!=null) {
Builder ab = new AlertDialog.Builder(this);
ab.setTitle(R.string.error_importing_file);
ab.setMessage(getString(R.string.import_error_message) + "\n" + fe.getLocalizedMessage());
ab.setPositiveButton(android.R.string.ok, null);
ab.show();
}
}
static private byte[] readBytesFromFile(File file) throws IOException {
InputStream input = new FileInputStream(file);
long len= file.length();
if (len > VpnProfile.MAX_EMBED_FILE_SIZE)
throw new IOException("selected file size too big to embed into profile");
// Create the byte array to hold the data
byte[] bytes = new byte[(int) len];
// Read in the bytes
int offset = 0;
int bytesRead = 0;
while (offset < bytes.length
&& (bytesRead=input.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += bytesRead;
}
input.close();
return bytes;
}
public void setFile(String path) {
Intent intent = new Intent();
intent.putExtra(RESULT_DATA, path);
setResult(Activity.RESULT_OK,intent);
finish();
}
public String getSelectPath() {
if(VpnProfile.isEmbedded(mData))
return mData;
else
return Environment.getExternalStorageDirectory().getPath();
}
public CharSequence getInlineData() {
if(VpnProfile.isEmbedded(mData))
return VpnProfile.getEmbeddedContent(mData);
else
return "";
}
public void clearData() {
Intent intent = new Intent();
intent.putExtra(RESULT_DATA, (String)null);
setResult(Activity.RESULT_OK,intent);
finish();
}
public void saveInlineData(String fileName, String string) {
Intent intent = new Intent();
if(fileName==null)
intent.putExtra(RESULT_DATA, VpnProfile.INLINE_TAG + string);
else
intent.putExtra(RESULT_DATA,VpnProfile.DISPLAYNAME_TAG + fileName + VpnProfile.INLINE_TAG + string);
setResult(Activity.RESULT_OK, intent);
finish();
}
}
| Java |
package de.blinkt.openvpn.activities;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.fragments.*;
public class MainActivity extends Activity {
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab vpnListTab = bar.newTab().setText(R.string.vpn_list_title);
Tab generalTab = bar.newTab().setText(R.string.generalsettings);
Tab faqtab = bar.newTab().setText(R.string.faq);
Tab abouttab = bar.newTab().setText(R.string.about);
vpnListTab.setTabListener(new TabListener<VPNProfileList>("profiles", VPNProfileList.class));
generalTab.setTabListener(new TabListener<GeneralSettings>("settings", GeneralSettings.class));
faqtab.setTabListener(new TabListener<FaqFragment>("faq", FaqFragment.class));
abouttab.setTabListener(new TabListener<AboutFragment>("about", AboutFragment.class));
bar.addTab(vpnListTab);
bar.addTab(generalTab);
bar.addTab(faqtab);
bar.addTab(abouttab);
if (false) {
Tab logtab = bar.newTab().setText("Log");
logtab.setTabListener(new TabListener<LogFragment>("log", LogFragment.class));
bar.addTab(logtab);
}
if(SendDumpFragment.getLastestDump(this)!=null) {
Tab sendDump = bar.newTab().setText(R.string.crashdump);
sendDump.setTabListener(new TabListener<SendDumpFragment>("crashdump",SendDumpFragment.class));
bar.addTab(sendDump);
}
}
protected class TabListener<T extends Fragment> implements ActionBar.TabListener
{
private Fragment mFragment;
private String mTag;
private Class<T> mClass;
public TabListener(String tag, Class<T> clz) {
mTag = tag;
mClass = clz;
// Check to see if we already have a fragment for this tab, probably
// from a previously saved state. If so, deactivate it, because our
// initial state is that a tab isn't shown.
mFragment = getFragmentManager().findFragmentByTag(mTag);
if (mFragment != null && !mFragment.isDetached()) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(mFragment);
ft.commit();
}
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(MainActivity.this, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
ft.attach(mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
ft.detach(mFragment);
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println(data);
}
}
| Java |
package de.blinkt.openvpn.api;
import java.util.HashSet;
import java.util.Set;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
public class ExternalAppDatabase {
Context mContext;
public ExternalAppDatabase(Context c) {
mContext =c;
}
private final String PREFERENCES_KEY = "PREFERENCES_KEY";
boolean isAllowed(String packagename) {
Set<String> allowedapps = getExtAppList();
return allowedapps.contains(packagename);
}
public Set<String> getExtAppList() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
return prefs.getStringSet(PREFERENCES_KEY, new HashSet<String>());
}
void addApp(String packagename)
{
Set<String> allowedapps = getExtAppList();
allowedapps.add(packagename);
saveExtAppList(allowedapps);
}
private void saveExtAppList( Set<String> allowedapps) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
Editor prefedit = prefs.edit();
prefedit.putStringSet(PREFERENCES_KEY, allowedapps);
prefedit.apply();
}
public void clearAllApiApps() {
saveExtAppList(new HashSet<String>());
}
public void removeApp(String packagename) {
Set<String> allowedapps = getExtAppList();
allowedapps.remove(packagename);
saveExtAppList(allowedapps);
}
}
| Java |
package de.blinkt.openvpn.api;
import android.app.Activity;
import android.content.Intent;
import android.net.VpnService;
public class GrantPermissionsActivity extends Activity {
private static final int VPN_PREPARE = 0;
@Override
protected void onStart() {
super.onStart();
Intent i= VpnService.prepare(this);
if(i==null)
onActivityResult(VPN_PREPARE, RESULT_OK, null);
else
startActivityForResult(i, VPN_PREPARE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
setResult(resultCode);
finish();
}
}
| Java |
package de.blinkt.openvpn.api;
import android.os.RemoteException;
public class SecurityRemoteException extends RemoteException {
/**
*
*/
private static final long serialVersionUID = 1L;
}
| Java |
/*
* Copyright (C) 2011 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 de.blinkt.openvpn.api;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnShowListener;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import de.blinkt.openvpn.R;
public class ConfirmDialog extends Activity implements
CompoundButton.OnCheckedChangeListener, DialogInterface.OnClickListener {
private static final String TAG = "OpenVPNVpnConfirm";
private String mPackage;
private Button mButton;
private AlertDialog mAlert;
@Override
protected void onResume() {
super.onResume();
try {
mPackage = getCallingPackage();
if (mPackage==null) {
finish();
return;
}
PackageManager pm = getPackageManager();
ApplicationInfo app = pm.getApplicationInfo(mPackage, 0);
View view = View.inflate(this, R.layout.api_confirm, null);
((ImageView) view.findViewById(R.id.icon)).setImageDrawable(app.loadIcon(pm));
((TextView) view.findViewById(R.id.prompt)).setText(
getString(R.string.prompt, app.loadLabel(pm), getString(R.string.app)));
((CompoundButton) view.findViewById(R.id.check)).setOnCheckedChangeListener(this);
Builder builder = new AlertDialog.Builder(this);
builder.setView(view);
builder.setIconAttribute(android.R.attr.alertDialogIcon);
builder.setTitle(android.R.string.dialog_alert_title);
builder.setPositiveButton(android.R.string.ok,this);
builder.setNegativeButton(android.R.string.cancel,this);
mAlert = builder.create();
mAlert.setCanceledOnTouchOutside(false);
mAlert.setOnShowListener (new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
mButton = mAlert.getButton(DialogInterface.BUTTON_POSITIVE);
mButton.setEnabled(false);
}
});
//setCloseOnTouchOutside(false);
mAlert.show();
} catch (Exception e) {
Log.e(TAG, "onResume", e);
finish();
}
}
@Override
public void onBackPressed() {
setResult(RESULT_CANCELED);
finish();
}
@Override
public void onCheckedChanged(CompoundButton button, boolean checked) {
mButton.setEnabled(checked);
}
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
ExternalAppDatabase extapps = new ExternalAppDatabase(this);
extapps.addApp(mPackage);
setResult(RESULT_OK);
finish();
}
if (which == DialogInterface.BUTTON_NEGATIVE) {
setResult(RESULT_CANCELED);
finish();
}
}
}
| Java |
package de.blinkt.openvpn.api;
import android.os.Parcel;
import android.os.Parcelable;
public class APIVpnProfile implements Parcelable {
public final String mUUID;
public final String mName;
public final boolean mUserEditable;
public APIVpnProfile(Parcel in) {
mUUID = in.readString();
mName = in.readString();
mUserEditable = in.readInt() != 0;
}
public APIVpnProfile(String uuidString, String name, boolean userEditable) {
mUUID=uuidString;
mName = name;
mUserEditable=userEditable;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mUUID);
dest.writeString(mName);
if(mUserEditable)
dest.writeInt(0);
else
dest.writeInt(1);
}
public static final Parcelable.Creator<APIVpnProfile> CREATOR
= new Parcelable.Creator<APIVpnProfile>() {
public APIVpnProfile createFromParcel(Parcel in) {
return new APIVpnProfile(in);
}
public APIVpnProfile[] newArray(int size) {
return new APIVpnProfile[size];
}
};
}
| Java |
package de.blinkt.openvpn.api;
import java.io.IOException;
import java.io.StringReader;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
import android.annotation.TargetApi;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.VpnService;
import android.os.*;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
import de.blinkt.openvpn.core.ConfigParser;
import de.blinkt.openvpn.core.ConfigParser.ConfigParseError;
import de.blinkt.openvpn.core.VpnStatus;
import de.blinkt.openvpn.core.VpnStatus.ConnectionStatus;
import de.blinkt.openvpn.core.VpnStatus.StateListener;
import de.blinkt.openvpn.core.OpenVpnService;
import de.blinkt.openvpn.core.OpenVpnService.LocalBinder;
import de.blinkt.openvpn.core.ProfileManager;
import de.blinkt.openvpn.core.VPNLaunchHelper;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
public class ExternalOpenVPNService extends Service implements StateListener {
private static final int SEND_TOALL = 0;
final RemoteCallbackList<IOpenVPNStatusCallback> mCallbacks =
new RemoteCallbackList<IOpenVPNStatusCallback>();
private OpenVpnService mService;
private ExternalAppDatabase mExtAppDb;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mService = null;
}
};
@Override
public void onCreate() {
super.onCreate();
VpnStatus.addStateListener(this);
mExtAppDb = new ExternalAppDatabase(this);
Intent intent = new Intent(getBaseContext(), OpenVpnService.class);
intent.setAction(OpenVpnService.START_SERVICE);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
mHandler.setService(this);
}
private final IOpenVPNAPIService.Stub mBinder = new IOpenVPNAPIService.Stub() {
private void checkOpenVPNPermission() throws SecurityRemoteException {
PackageManager pm = getPackageManager();
for (String apppackage : mExtAppDb.getExtAppList()) {
ApplicationInfo app;
try {
app = pm.getApplicationInfo(apppackage, 0);
if (Binder.getCallingUid() == app.uid) {
return;
}
} catch (NameNotFoundException e) {
// App not found. Remove it from the list
mExtAppDb.removeApp(apppackage);
}
}
throw new SecurityException("Unauthorized OpenVPN API Caller");
}
@Override
public List<APIVpnProfile> getProfiles() throws RemoteException {
checkOpenVPNPermission();
ProfileManager pm = ProfileManager.getInstance(getBaseContext());
List<APIVpnProfile> profiles = new LinkedList<APIVpnProfile>();
for (VpnProfile vp : pm.getProfiles())
profiles.add(new APIVpnProfile(vp.getUUIDString(), vp.mName, vp.mUserEditable));
return profiles;
}
@Override
public void startProfile(String profileUUID) throws RemoteException {
checkOpenVPNPermission();
Intent shortVPNIntent = new Intent(Intent.ACTION_MAIN);
shortVPNIntent.setClass(getBaseContext(), de.blinkt.openvpn.LaunchVPN.class);
shortVPNIntent.putExtra(de.blinkt.openvpn.LaunchVPN.EXTRA_KEY, profileUUID);
shortVPNIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(shortVPNIntent);
}
public void startVPN(String inlineconfig) throws RemoteException {
checkOpenVPNPermission();
ConfigParser cp = new ConfigParser();
try {
cp.parseConfig(new StringReader(inlineconfig));
VpnProfile vp = cp.convertProfile();
if (vp.checkProfile(getApplicationContext()) != R.string.no_error_found)
throw new RemoteException(getString(vp.checkProfile(getApplicationContext())));
ProfileManager.setTemporaryProfile(vp);
VPNLaunchHelper.startOpenVpn(vp, getBaseContext());
} catch (IOException e) {
throw new RemoteException(e.getMessage());
} catch (ConfigParseError e) {
throw new RemoteException(e.getMessage());
}
}
@Override
public boolean addVPNProfile(String name, String config) throws RemoteException {
checkOpenVPNPermission();
ConfigParser cp = new ConfigParser();
try {
cp.parseConfig(new StringReader(config));
VpnProfile vp = cp.convertProfile();
vp.mName = name;
ProfileManager pm = ProfileManager.getInstance(getBaseContext());
pm.addProfile(vp);
} catch (IOException e) {
VpnStatus.logException(e);
return false;
} catch (ConfigParseError e) {
VpnStatus.logException(e);
return false;
}
return true;
}
@Override
public Intent prepare(String packagename) {
if (new ExternalAppDatabase(ExternalOpenVPNService.this).isAllowed(packagename))
return null;
Intent intent = new Intent();
intent.setClass(ExternalOpenVPNService.this, ConfirmDialog.class);
return intent;
}
@Override
public Intent prepareVPNService() throws RemoteException {
checkOpenVPNPermission();
if (VpnService.prepare(ExternalOpenVPNService.this) == null)
return null;
else
return new Intent(getBaseContext(), GrantPermissionsActivity.class);
}
@Override
public void registerStatusCallback(IOpenVPNStatusCallback cb)
throws RemoteException {
checkOpenVPNPermission();
if (cb != null) {
cb.newStatus(mMostRecentState.vpnUUID, mMostRecentState.state,
mMostRecentState.logmessage, mMostRecentState.level.name());
mCallbacks.register(cb);
}
}
@Override
public void unregisterStatusCallback(IOpenVPNStatusCallback cb)
throws RemoteException {
checkOpenVPNPermission();
if (cb != null)
mCallbacks.unregister(cb);
}
@Override
public void disconnect() throws RemoteException {
checkOpenVPNPermission();
if (mService != null && mService.getManagement() != null)
mService.getManagement().stopVPN();
}
@Override
public void pause() throws RemoteException {
checkOpenVPNPermission();
if (mService != null)
mService.userPause(true);
}
@Override
public void resume() throws RemoteException {
checkOpenVPNPermission();
if (mService != null)
mService.userPause(false);
}
};
private UpdateMessage mMostRecentState;
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onDestroy() {
super.onDestroy();
mCallbacks.kill();
unbindService(mConnection);
VpnStatus.removeStateListener(this);
}
class UpdateMessage {
public String state;
public String logmessage;
public ConnectionStatus level;
public String vpnUUID;
public UpdateMessage(String state, String logmessage, ConnectionStatus level) {
this.state = state;
this.logmessage = logmessage;
this.level = level;
}
}
@Override
public void updateState(String state, String logmessage, int resid, ConnectionStatus level) {
mMostRecentState = new UpdateMessage(state, logmessage, level);
if (ProfileManager.getLastConnectedVpn() != null)
mMostRecentState.vpnUUID = ProfileManager.getLastConnectedVpn().getUUIDString();
Message msg = mHandler.obtainMessage(SEND_TOALL, mMostRecentState);
msg.sendToTarget();
}
private static final OpenVPNServiceHandler mHandler = new OpenVPNServiceHandler();
static class OpenVPNServiceHandler extends Handler {
WeakReference<ExternalOpenVPNService> service = null;
private void setService(ExternalOpenVPNService eos) {
service = new WeakReference<ExternalOpenVPNService>(eos);
}
@Override
public void handleMessage(Message msg) {
RemoteCallbackList<IOpenVPNStatusCallback> callbacks;
switch (msg.what) {
case SEND_TOALL:
if (service == null || service.get() == null)
return;
callbacks = service.get().mCallbacks;
// Broadcast to all clients the new value.
final int N = callbacks.beginBroadcast();
for (int i = 0; i < N; i++) {
try {
sendUpdate(callbacks.getBroadcastItem(i), (UpdateMessage) msg.obj);
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing
// the dead object for us.
}
}
callbacks.finishBroadcast();
break;
}
}
private void sendUpdate(IOpenVPNStatusCallback broadcastItem,
UpdateMessage um) throws RemoteException {
broadcastItem.newStatus(um.vpnUUID, um.state, um.logmessage, um.level.name());
}
}
} | Java |
package de.blinkt.openvpn;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.preference.PreferenceManager;
import android.security.KeyChain;
import android.security.KeyChainException;
import android.util.Base64;
import de.blinkt.openvpn.core.NativeUtils;
import de.blinkt.openvpn.core.VpnStatus;
import de.blinkt.openvpn.core.OpenVpnService;
import de.blinkt.openvpn.core.X509Utils;
import org.spongycastle.util.io.pem.PemObject;
import org.spongycastle.util.io.pem.PemWriter;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Locale;
import java.util.UUID;
import java.util.Vector;
public class VpnProfile implements Serializable {
// Note that this class cannot be moved to core where it belongs since
// the profile loading depends on it being here
// The Serializable documentation mentions that class name change are possible
// but the how is unclear
//
transient public static final long MAX_EMBED_FILE_SIZE = 2048*1024; // 2048kB
// Don't change this, not all parts of the program use this constant
public static final String EXTRA_PROFILEUUID = "de.blinkt.openvpn.profileUUID";
public static final String INLINE_TAG = "[[INLINE]]";
public static final String DISPLAYNAME_TAG = "[[NAME]]";
public static final String MINIVPN = "miniopenvpn";
private static final long serialVersionUID = 7085688938959334563L;
private static final String OVPNCONFIGFILE = "android.conf";
public static final int MAXLOGLEVEL = 4;
public static final int CURRENT_PROFILE_VERSION = 2;
public static String DEFAULT_DNS1 = "8.8.8.8";
public static String DEFAULT_DNS2 = "8.8.4.4";
public transient String mTransientPW = null;
public transient String mTransientPCKS12PW = null;
public static final int TYPE_CERTIFICATES = 0;
public static final int TYPE_PKCS12 = 1;
public static final int TYPE_KEYSTORE = 2;
public static final int TYPE_USERPASS = 3;
public static final int TYPE_STATICKEYS = 4;
public static final int TYPE_USERPASS_CERTIFICATES = 5;
public static final int TYPE_USERPASS_PKCS12 = 6;
public static final int TYPE_USERPASS_KEYSTORE = 7;
public static final int X509_VERIFY_TLSREMOTE = 0;
public static final int X509_VERIFY_TLSREMOTE_COMPAT_NOREMAPPING = 1;
public static final int X509_VERIFY_TLSREMOTE_DN = 2;
public static final int X509_VERIFY_TLSREMOTE_RDN = 3;
public static final int X509_VERIFY_TLSREMOTE_RDN_PREFIX = 4;
// variable named wrong and should haven beeen transient
// but needs to keep wrong name to guarante loading of old
// profiles
public transient boolean profileDleted = false;
public int mAuthenticationType = TYPE_KEYSTORE;
public String mName;
public String mAlias;
public String mClientCertFilename;
public String mTLSAuthDirection = "";
public String mTLSAuthFilename;
public String mClientKeyFilename;
public String mCaFilename;
public boolean mUseLzo = true;
public String mServerPort = "1194";
public boolean mUseUdp = true;
public String mPKCS12Filename;
public String mPKCS12Password;
public boolean mUseTLSAuth = false;
public String mServerName = "openvpn.blinkt.de";
public String mDNS1 = DEFAULT_DNS1;
public String mDNS2 = DEFAULT_DNS2;
public String mIPv4Address;
public String mIPv6Address;
public boolean mOverrideDNS = false;
public String mSearchDomain = "blinkt.de";
public boolean mUseDefaultRoute = true;
public boolean mUsePull = true;
public String mCustomRoutes;
public boolean mCheckRemoteCN = false;
public boolean mExpectTLSCert = true;
public String mRemoteCN = "";
public String mPassword = "";
public String mUsername = "";
public boolean mRoutenopull = false;
public boolean mUseRandomHostname = false;
public boolean mUseFloat = false;
public boolean mUseCustomConfig = false;
public String mCustomConfigOptions = "";
public String mVerb = "1"; //ignored
public String mCipher = "";
public boolean mNobind = false;
public boolean mUseDefaultRoutev6 = true;
public String mCustomRoutesv6 = "";
public String mKeyPassword = "";
public boolean mPersistTun = false;
public String mConnectRetryMax = "5";
public String mConnectRetry = "5";
public boolean mUserEditable = true;
public String mAuth = "";
public int mX509AuthType = X509_VERIFY_TLSREMOTE_RDN;
private transient PrivateKey mPrivateKey;
// Public attributes, since I got mad with getter/setter
// set members to default values
private UUID mUuid;
public boolean mAllowLocalLAN;
private int mProfileVersion;
public String mExcludedRoutes;
public String mExcludedRoutesv6;
public VpnProfile(String name) {
mUuid = UUID.randomUUID();
mName = name;
mProfileVersion = CURRENT_PROFILE_VERSION;
}
public static String openVpnEscape(String unescaped) {
if (unescaped == null)
return null;
String escapedString = unescaped.replace("\\", "\\\\");
escapedString = escapedString.replace("\"", "\\\"");
escapedString = escapedString.replace("\n", "\\n");
if (escapedString.equals(unescaped) && !escapedString.contains(" ") && !escapedString.contains("#"))
return unescaped;
else
return '"' + escapedString + '"';
}
public void clearDefaults() {
mServerName = "unknown";
mUsePull = false;
mUseLzo = false;
mUseDefaultRoute = false;
mUseDefaultRoutev6 = false;
mExpectTLSCert = false;
mPersistTun = false;
mAllowLocalLAN = true;
}
public UUID getUUID() {
return mUuid;
}
public String getName() {
if (mName==null)
return "No profile name";
return mName;
}
public void upgradeProfile(){
if(mProfileVersion< 2) {
/* default to the behaviour the OS used */
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
mAllowLocalLAN = true;
else
mAllowLocalLAN = false;
}
mProfileVersion= CURRENT_PROFILE_VERSION;
}
public String getConfigFile(Context context, boolean configForOvpn3) {
File cacheDir = context.getCacheDir();
String cfg = "";
// Enable managment interface
cfg += "# Enables connection to GUI\n";
cfg += "management ";
cfg += cacheDir.getAbsolutePath() + "/" + "mgmtsocket";
cfg += " unix\n";
cfg += "management-client\n";
// Not needed, see updated man page in 2.3
//cfg += "management-signal\n";
cfg += "management-query-passwords\n";
cfg += "management-hold\n\n";
cfg += getVersionEnvString(context);
cfg += "machine-readable-output\n";
boolean useTLSClient = (mAuthenticationType != TYPE_STATICKEYS);
if (useTLSClient && mUsePull)
cfg += "client\n";
else if (mUsePull)
cfg += "pull\n";
else if (useTLSClient)
cfg += "tls-client\n";
//cfg += "verb " + mVerb + "\n";
cfg += "verb " + MAXLOGLEVEL + "\n";
if (mConnectRetryMax == null) {
mConnectRetryMax = "5";
}
if (!mConnectRetryMax.equals("-1"))
cfg += "connect-retry-max " + mConnectRetryMax + "\n";
if (mConnectRetry == null)
mConnectRetry = "5";
cfg += "connect-retry " + mConnectRetry + "\n";
cfg += "resolv-retry 60\n";
// We cannot use anything else than tun
cfg += "dev tun\n";
// Server Address
cfg += "remote ";
cfg += mServerName;
cfg += " ";
cfg += mServerPort;
if (mUseUdp)
cfg += " udp\n";
else
cfg += " tcp-client\n";
switch (mAuthenticationType) {
case VpnProfile.TYPE_USERPASS_CERTIFICATES:
cfg += "auth-user-pass\n";
case VpnProfile.TYPE_CERTIFICATES:
// Ca
cfg += insertFileData("ca", mCaFilename);
// Client Cert + Key
cfg += insertFileData("key", mClientKeyFilename);
cfg += insertFileData("cert", mClientCertFilename);
break;
case VpnProfile.TYPE_USERPASS_PKCS12:
cfg += "auth-user-pass\n";
case VpnProfile.TYPE_PKCS12:
cfg += insertFileData("pkcs12", mPKCS12Filename);
break;
case VpnProfile.TYPE_USERPASS_KEYSTORE:
cfg += "auth-user-pass\n";
case VpnProfile.TYPE_KEYSTORE:
if (!configForOvpn3) {
String[] ks = getKeyStoreCertificates(context);
cfg += "### From Keystore ####\n";
if (ks != null) {
cfg += "<ca>\n" + ks[0] + "\n</ca>\n";
if (ks[1] != null)
cfg += "<extra-certs>\n" + ks[1] + "\n</extra-certs>\n";
cfg += "<cert>\n" + ks[2] + "\n</cert>\n";
cfg += "management-external-key\n";
} else {
cfg += context.getString(R.string.keychain_access) + "\n";
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN)
if (!mAlias.matches("^[a-zA-Z0-9]$"))
cfg += context.getString(R.string.jelly_keystore_alphanumeric_bug) + "\n";
}
}
break;
case VpnProfile.TYPE_USERPASS:
cfg += "auth-user-pass\n";
cfg += insertFileData("ca", mCaFilename);
}
if (mUseLzo) {
cfg += "comp-lzo\n";
}
if (mUseTLSAuth) {
if (mAuthenticationType == TYPE_STATICKEYS)
cfg += insertFileData("secret", mTLSAuthFilename);
else
cfg += insertFileData("tls-auth", mTLSAuthFilename);
if (nonNull(mTLSAuthDirection)) {
cfg += "key-direction ";
cfg += mTLSAuthDirection;
cfg += "\n";
}
}
if (!mUsePull) {
if (nonNull(mIPv4Address))
cfg += "ifconfig " + cidrToIPAndNetmask(mIPv4Address) + "\n";
if (nonNull(mIPv6Address))
cfg += "ifconfig-ipv6 " + mIPv6Address + "\n";
}
if (mUsePull && mRoutenopull)
cfg += "route-nopull\n";
String routes = "";
if (mUseDefaultRoute)
routes += "route 0.0.0.0 0.0.0.0 vpn_gateway\n";
else
{
for (String route : getCustomRoutes(mCustomRoutes)) {
routes += "route " + route + " vpn_gateway\n";
}
for (String route: getCustomRoutes(mExcludedRoutes)) {
routes += "route " + route + " net_gateway";
}
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT && !mAllowLocalLAN)
cfg+="redirect-private block-local\n";
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && mAllowLocalLAN)
cfg+="redirect-private unblock-local\n";
if (mUseDefaultRoutev6)
cfg += "route-ipv6 ::/0\n";
else
for (String route : getCustomRoutesv6(mCustomRoutesv6)) {
routes += "route-ipv6 " + route + "\n";
}
cfg += routes;
if (mOverrideDNS || !mUsePull) {
if (nonNull(mDNS1))
cfg += "dhcp-option DNS " + mDNS1 + "\n";
if (nonNull(mDNS2))
cfg += "dhcp-option DNS " + mDNS2 + "\n";
if (nonNull(mSearchDomain))
cfg += "dhcp-option DOMAIN " + mSearchDomain + "\n";
}
if (mNobind)
cfg += "nobind\n";
// Authentication
if (mAuthenticationType != TYPE_STATICKEYS) {
if (mCheckRemoteCN) {
if (mRemoteCN == null || mRemoteCN.equals(""))
cfg += "verify-x509-name " + mServerName + " name\n";
else
switch (mX509AuthType) {
// 2.2 style x509 checks
case X509_VERIFY_TLSREMOTE_COMPAT_NOREMAPPING:
cfg += "compat-names no-remapping\n";
case X509_VERIFY_TLSREMOTE:
cfg += "tls-remote " + openVpnEscape(mRemoteCN) + "\n";
break;
case X509_VERIFY_TLSREMOTE_RDN:
cfg += "verify-x509-name " + openVpnEscape(mRemoteCN) + " name\n";
break;
case X509_VERIFY_TLSREMOTE_RDN_PREFIX:
cfg += "verify-x509-name " + openVpnEscape(mRemoteCN) + " name-prefix\n";
break;
case X509_VERIFY_TLSREMOTE_DN:
cfg += "verify-x509-name " + openVpnEscape(mRemoteCN) + "\n";
break;
}
}
if (mExpectTLSCert)
cfg += "remote-cert-tls server\n";
}
if (nonNull(mCipher)) {
cfg += "cipher " + mCipher + "\n";
}
if (nonNull(mAuth)) {
cfg += "auth " + mAuth + "\n";
}
// Obscure Settings dialog
if (mUseRandomHostname)
cfg += "#my favorite options :)\nremote-random-hostname\n";
if (mUseFloat)
cfg += "float\n";
if (mPersistTun) {
cfg += "persist-tun\n";
cfg += "# persist-tun also enables pre resolving to avoid DNS resolve problem\n";
cfg += "preresolve\n";
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean usesystemproxy = prefs.getBoolean("usesystemproxy", true);
if (usesystemproxy) {
cfg += "# Use system proxy setting\n";
cfg += "management-query-proxy\n";
}
if (mUseCustomConfig) {
cfg += "# Custom configuration options\n";
cfg += "# You are on your on own here :)\n";
cfg += mCustomConfigOptions;
cfg += "\n";
}
return cfg;
}
private String getVersionEnvString(Context c) {
String version = "unknown";
try {
PackageInfo packageinfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
version = packageinfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
VpnStatus.logException(e);
}
return String.format(Locale.US, "setenv IV_GUI_VER \"%s %s\"\n", c.getPackageName(), version);
}
//! Put inline data inline and other data as normal escaped filename
private String insertFileData(String cfgentry, String filedata) {
if (filedata == null) {
// TODO: generate good error
return String.format("%s %s\n", cfgentry, "missing");
} else if (isEmbedded(filedata)) {
String dataWithOutHeader = getEmbeddedContent(filedata);
return String.format(Locale.ENGLISH, "<%s>\n%s\n</%s>\n", cfgentry, dataWithOutHeader, cfgentry);
} else {
return String.format(Locale.ENGLISH, "%s %s\n", cfgentry, openVpnEscape(filedata));
}
}
private boolean nonNull(String val) {
if (val == null || val.equals(""))
return false;
else
return true;
}
private Collection<String> getCustomRoutes(String routes) {
Vector<String> cidrRoutes = new Vector<String>();
if (routes == null) {
// No routes set, return empty vector
return cidrRoutes;
}
for (String route : routes.split("[\n \t]")) {
if (!route.equals("")) {
String cidrroute = cidrToIPAndNetmask(route);
if (cidrroute == null)
return null;
cidrRoutes.add(cidrroute);
}
}
return cidrRoutes;
}
private Collection<String> getCustomRoutesv6(String routes) {
Vector<String> cidrRoutes = new Vector<String>();
if (routes == null) {
// No routes set, return empty vector
return cidrRoutes;
}
for (String route : routes.split("[\n \t]")) {
if (!route.equals("")) {
cidrRoutes.add(route);
}
}
return cidrRoutes;
}
private String cidrToIPAndNetmask(String route) {
String[] parts = route.split("/");
// No /xx, assume /32 as netmask
if (parts.length == 1)
parts = (route + "/32").split("/");
if (parts.length != 2)
return null;
int len;
try {
len = Integer.parseInt(parts[1]);
} catch (NumberFormatException ne) {
return null;
}
if (len < 0 || len > 32)
return null;
long nm = 0xffffffffl;
nm = (nm << (32 - len)) & 0xffffffffl;
String netmask = String.format(Locale.ENGLISH, "%d.%d.%d.%d", (nm & 0xff000000) >> 24, (nm & 0xff0000) >> 16, (nm & 0xff00) >> 8, nm & 0xff);
return parts[0] + " " + netmask;
}
private String[] buildOpenvpnArgv(File cacheDir) {
Vector<String> args = new Vector<String>();
// Add fixed paramenters
//args.add("/data/data/de.blinkt.openvpn/lib/openvpn");
args.add(cacheDir.getAbsolutePath() + "/" + VpnProfile.MINIVPN);
args.add("--config");
args.add(cacheDir.getAbsolutePath() + "/" + OVPNCONFIGFILE);
return args.toArray(new String[args.size()]);
}
public Intent prepareIntent(Context context) {
String prefix = context.getPackageName();
Intent intent = new Intent(context, OpenVpnService.class);
if (mAuthenticationType == VpnProfile.TYPE_KEYSTORE || mAuthenticationType == VpnProfile.TYPE_USERPASS_KEYSTORE) {
if (getKeyStoreCertificates(context) == null)
return null;
}
intent.putExtra(prefix + ".ARGV", buildOpenvpnArgv(context.getCacheDir()));
intent.putExtra(prefix + ".profileUUID", mUuid.toString());
ApplicationInfo info = context.getApplicationInfo();
intent.putExtra(prefix + ".nativelib", info.nativeLibraryDir);
try {
FileWriter cfg = new FileWriter(context.getCacheDir().getAbsolutePath() + "/" + OVPNCONFIGFILE);
cfg.write(getConfigFile(context, false));
cfg.flush();
cfg.close();
} catch (IOException e) {
VpnStatus.logException(e);
}
return intent;
}
String[] getKeyStoreCertificates(Context context) {
return getKeyStoreCertificates(context, 5);
}
public static String getDisplayName(String embeddedFile) {
int start = DISPLAYNAME_TAG.length();
int end = embeddedFile.indexOf(INLINE_TAG);
return embeddedFile.substring(start,end);
}
public static String getEmbeddedContent(String data)
{
if (!data.contains(INLINE_TAG))
return data;
int start = data.indexOf(INLINE_TAG) + INLINE_TAG.length();
return data.substring(start);
}
public static boolean isEmbedded(String data) {
if (data==null)
return false;
if(data.startsWith(INLINE_TAG) || data.startsWith(DISPLAYNAME_TAG))
return true;
else
return false;
}
class NoCertReturnedException extends Exception {
public NoCertReturnedException (String msg) {
super(msg);
}
}
synchronized String[] getKeyStoreCertificates(Context context,int tries) {
PrivateKey privateKey = null;
X509Certificate[] cachain;
Exception exp=null;
try {
privateKey = KeyChain.getPrivateKey(context, mAlias);
mPrivateKey = privateKey;
String keystoreChain = null;
cachain = KeyChain.getCertificateChain(context, mAlias);
if(cachain == null)
throw new NoCertReturnedException("No certificate returned from Keystore");
if (cachain.length <= 1 && !nonNull(mCaFilename)) {
VpnStatus.logMessage(VpnStatus.LogLevel.ERROR, "", context.getString(R.string.keychain_nocacert));
} else {
StringWriter ksStringWriter = new StringWriter();
PemWriter pw = new PemWriter(ksStringWriter);
for (int i = 1; i < cachain.length; i++) {
X509Certificate cert = cachain[i];
pw.writeObject(new PemObject("CERTIFICATE", cert.getEncoded()));
}
pw.close();
keystoreChain = ksStringWriter.toString();
}
String caout = null;
if (nonNull(mCaFilename)) {
try {
Certificate cacert = X509Utils.getCertificateFromFile(mCaFilename);
StringWriter caoutWriter = new StringWriter();
PemWriter pw = new PemWriter(caoutWriter);
pw.writeObject(new PemObject("CERTIFICATE", cacert.getEncoded()));
pw.close();
caout= caoutWriter.toString();
} catch (Exception e) {
VpnStatus.logError("Could not read CA certificate" + e.getLocalizedMessage());
}
}
StringWriter certout = new StringWriter();
if (cachain.length >= 1) {
X509Certificate usercert = cachain[0];
PemWriter upw = new PemWriter(certout);
upw.writeObject(new PemObject("CERTIFICATE", usercert.getEncoded()));
upw.close();
}
String user = certout.toString();
String ca, extra;
if(caout==null) {
ca =keystoreChain;
extra=null;
} else {
ca = caout;
extra=keystoreChain;
}
return new String[]{ca, extra, user};
} catch (InterruptedException e) {
exp=e;
} catch (FileNotFoundException e) {
exp=e;
} catch (CertificateException e) {
exp=e;
} catch (IOException e) {
exp=e;
} catch (KeyChainException e) {
exp=e;
} catch (NoCertReturnedException e) {
exp =e;
} catch (IllegalArgumentException e) {
exp =e;
} catch (AssertionError e) {
if (tries ==0)
return null;
VpnStatus.logError(String.format("Failure getting Keystore Keys (%s), retrying",e.getLocalizedMessage()));
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
VpnStatus.logException(e1);
}
return getKeyStoreCertificates(context, tries-1);
}
if (exp != null) {
exp.printStackTrace();
VpnStatus.logError(R.string.keyChainAccessError, exp.getLocalizedMessage());
VpnStatus.logError(R.string.keychain_access);
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN) {
if (!mAlias.matches("^[a-zA-Z0-9]$")) {
VpnStatus.logError(R.string.jelly_keystore_alphanumeric_bug);
}
}
}
return null;
}
//! Return an error if somethign is wrong
public int checkProfile(Context context) {
if (mAuthenticationType == TYPE_KEYSTORE || mAuthenticationType == TYPE_USERPASS_KEYSTORE) {
if (mAlias == null)
return R.string.no_keystore_cert_selected;
}
if (!mUsePull || mAuthenticationType == TYPE_STATICKEYS) {
if (mIPv4Address == null || cidrToIPAndNetmask(mIPv4Address) == null)
return R.string.ipv4_format_error;
}
if (!mUseDefaultRoute && (getCustomRoutes(mCustomRoutes) == null || getCustomRoutes(mExcludedRoutes) ==null))
return R.string.custom_route_format_error;
// Everything okay
return R.string.no_error_found;
}
//! Openvpn asks for a "Private Key", this should be pkcs12 key
//
public String getPasswordPrivateKey() {
if (mTransientPCKS12PW != null) {
String pwcopy = mTransientPCKS12PW;
mTransientPCKS12PW = null;
return pwcopy;
}
switch (mAuthenticationType) {
case TYPE_PKCS12:
case TYPE_USERPASS_PKCS12:
return mPKCS12Password;
case TYPE_CERTIFICATES:
case TYPE_USERPASS_CERTIFICATES:
return mKeyPassword;
case TYPE_USERPASS:
case TYPE_STATICKEYS:
default:
return null;
}
}
boolean isUserPWAuth() {
switch (mAuthenticationType) {
case TYPE_USERPASS:
case TYPE_USERPASS_CERTIFICATES:
case TYPE_USERPASS_KEYSTORE:
case TYPE_USERPASS_PKCS12:
return true;
default:
return false;
}
}
public boolean requireTLSKeyPassword() {
if (!nonNull(mClientKeyFilename))
return false;
String data = "";
if (isEmbedded(mClientKeyFilename))
data = mClientKeyFilename;
else {
char[] buf = new char[2048];
FileReader fr;
try {
fr = new FileReader(mClientKeyFilename);
int len = fr.read(buf);
while (len > 0) {
data += new String(buf, 0, len);
len = fr.read(buf);
}
fr.close();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
}
if (data.contains("Proc-Type: 4,ENCRYPTED"))
return true;
else if (data.contains("-----BEGIN ENCRYPTED PRIVATE KEY-----"))
return true;
else
return false;
}
public int needUserPWInput() {
if ((mAuthenticationType == TYPE_PKCS12 || mAuthenticationType == TYPE_USERPASS_PKCS12) &&
(mPKCS12Password == null || mPKCS12Password.equals(""))) {
if (mTransientPCKS12PW == null)
return R.string.pkcs12_file_encryption_key;
}
if (mAuthenticationType == TYPE_CERTIFICATES || mAuthenticationType == TYPE_USERPASS_CERTIFICATES) {
if (requireTLSKeyPassword() && !nonNull(mKeyPassword))
if (mTransientPCKS12PW == null) {
return R.string.private_key_password;
}
}
if (isUserPWAuth() && !(nonNull(mUsername) && (nonNull(mPassword) || mTransientPW != null))) {
return R.string.password;
}
return 0;
}
public String getPasswordAuth() {
if (mTransientPW != null) {
String pwcopy = mTransientPW;
mTransientPW = null;
return pwcopy;
} else {
return mPassword;
}
}
// Used by the Array Adapter
@Override
public String toString() {
return mName;
}
public String getUUIDString() {
return mUuid.toString();
}
public PrivateKey getKeystoreKey() {
return mPrivateKey;
}
public String getSignedData(String b64data) {
PrivateKey privkey = getKeystoreKey();
Exception err;
byte[] data = Base64.decode(b64data, Base64.DEFAULT);
// The Jelly Bean *evil* Hack
// 4.2 implements the RSA/ECB/PKCS1PADDING in the OpenSSLprovider
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN) {
return processSignJellyBeans(privkey, data);
}
try {
Cipher rsasinger = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
rsasinger.init(Cipher.ENCRYPT_MODE, privkey);
byte[] signed_bytes = rsasinger.doFinal(data);
return Base64.encodeToString(signed_bytes, Base64.NO_WRAP);
} catch (NoSuchAlgorithmException e) {
err = e;
} catch (InvalidKeyException e) {
err = e;
} catch (NoSuchPaddingException e) {
err = e;
} catch (IllegalBlockSizeException e) {
err = e;
} catch (BadPaddingException e) {
err = e;
}
VpnStatus.logError(R.string.error_rsa_sign, err.getClass().toString(), err.getLocalizedMessage());
return null;
}
private String processSignJellyBeans(PrivateKey privkey, byte[] data) {
Exception err;
try {
Method getKey = privkey.getClass().getSuperclass().getDeclaredMethod("getOpenSSLKey");
getKey.setAccessible(true);
// Real object type is OpenSSLKey
Object opensslkey = getKey.invoke(privkey);
getKey.setAccessible(false);
Method getPkeyContext = opensslkey.getClass().getDeclaredMethod("getPkeyContext");
// integer pointer to EVP_pkey
getPkeyContext.setAccessible(true);
int pkey = (Integer) getPkeyContext.invoke(opensslkey);
getPkeyContext.setAccessible(false);
// 112 with TLS 1.2 (172 back with 4.3), 36 with TLS 1.0
byte[] signed_bytes = NativeUtils.rsasign(data, pkey);
return Base64.encodeToString(signed_bytes, Base64.NO_WRAP);
} catch (NoSuchMethodException e) {
err = e;
} catch (IllegalArgumentException e) {
err = e;
} catch (IllegalAccessException e) {
err = e;
} catch (InvocationTargetException e) {
err = e;
} catch (InvalidKeyException e) {
err = e;
}
VpnStatus.logError(R.string.error_rsa_sign, err.getClass().toString(), err.getLocalizedMessage());
return null;
}
}
| Java |
package de.blinkt.openvpn;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import de.blinkt.openvpn.core.ProfileManager;
public class OnBootReceiver extends BroadcastReceiver {
// Debug: am broadcast -a android.intent.action.BOOT_COMPLETED
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(Intent.ACTION_BOOT_COMPLETED.equals(action)) {
VpnProfile bootProfile = ProfileManager.getOnBootProfile(context);
if(bootProfile != null) {
launchVPN(bootProfile, context);
}
}
}
void launchVPN(VpnProfile profile, Context context) {
Intent startVpnIntent = new Intent(Intent.ACTION_MAIN);
startVpnIntent.setClass(context, LaunchVPN.class);
startVpnIntent.putExtra(LaunchVPN.EXTRA_KEY,profile.getUUIDString());
startVpnIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startVpnIntent.putExtra(LaunchVPN.EXTRA_HIDELOG, true);
context.startActivity(startVpnIntent);
}
}
| Java |
package de.blinkt.openvpn.views;
import android.content.Context;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
public class RemoteCNPreference extends DialogPreference {
private Spinner mSpinner;
private EditText mEditText;
private int mDNType;
private String mDn;
private TextView mRemoteTLSNote;
//private ScrollView mScrollView;
public RemoteCNPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.tlsremote);
}
@Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
mEditText = (EditText) view.findViewById(R.id.tlsremotecn);
mSpinner = (Spinner) view.findViewById(R.id.x509verifytype);
mRemoteTLSNote = (TextView) view.findViewById(R.id.tlsremotenote);
//mScrollView = (ScrollView) view.findViewById(R.id.tlsremotescroll);
if(mDn!=null)
mEditText.setText(mDn);
populateSpinner();
}
public String getCNText() {
return mDn;
}
public int getAuthtype() {
return mDNType;
}
public void setDN(String dn) {
mDn = dn;
if(mEditText!=null)
mEditText.setText(dn);
}
public void setAuthType(int x509authtype) {
mDNType = x509authtype;
if (mSpinner!=null)
populateSpinner();
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
String dn = mEditText.getText().toString();
int authtype = getAuthTypeFromSpinner();
if (callChangeListener(new Pair<Integer, String>(authtype, dn))) {
mDn = dn;
mDNType = authtype;
}
}
}
private void populateSpinner() {
ArrayAdapter<String> authtypes = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item);
authtypes.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
authtypes.add(getContext().getString(R.string.complete_dn));
authtypes.add(getContext().getString(R.string.rdn));
authtypes.add(getContext().getString(R.string.rdn_prefix));
if ((mDNType == VpnProfile.X509_VERIFY_TLSREMOTE || mDNType == VpnProfile.X509_VERIFY_TLSREMOTE_COMPAT_NOREMAPPING)
&& !(mDn==null || "".equals(mDn))) {
authtypes.add(getContext().getString(R.string.tls_remote_deprecated));
mRemoteTLSNote.setVisibility(View.VISIBLE);
} else {
mRemoteTLSNote.setVisibility(View.GONE);
}
mSpinner.setAdapter(authtypes);
mSpinner.setSelection(getSpinnerPositionFromAuthTYPE());
}
private int getSpinnerPositionFromAuthTYPE() {
switch (mDNType) {
case VpnProfile.X509_VERIFY_TLSREMOTE_DN:
return 0;
case VpnProfile.X509_VERIFY_TLSREMOTE_RDN:
return 1;
case VpnProfile.X509_VERIFY_TLSREMOTE_RDN_PREFIX:
return 2;
case VpnProfile.X509_VERIFY_TLSREMOTE_COMPAT_NOREMAPPING:
case VpnProfile.X509_VERIFY_TLSREMOTE:
if (mDn==null || "".equals(mDn))
return 1;
else
return 3;
default:
return 0;
}
}
private int getAuthTypeFromSpinner() {
int pos = mSpinner.getSelectedItemPosition();
switch (pos) {
case 0:
return VpnProfile.X509_VERIFY_TLSREMOTE_DN;
case 1:
return VpnProfile.X509_VERIFY_TLSREMOTE_RDN;
case 2:
return VpnProfile.X509_VERIFY_TLSREMOTE_RDN_PREFIX;
case 3:
// This is the tls-remote entry, only visible if mDntype is a
// tls-remote type
return mDNType;
default:
return VpnProfile.X509_VERIFY_TLSREMOTE;
}
}
}
| Java |
package de.blinkt.openvpn.views;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.ViewConfiguration;
import android.widget.SeekBar;
public class SeekBarTicks extends SeekBar {
private Paint mTickPaint;
private float mTickHeight;
private float tickHeightRatio = 0.6f;
public SeekBarTicks(Context context, AttributeSet attrs) {
super (context, attrs);
initTicks (context, attrs, android.R.attr.seekBarStyle);
}
public SeekBarTicks(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initTicks (context, attrs, defStyle);
/*mTickHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
tickHeightDP,
ctx.getResources().getDisplayMetrics()); */
}
private void initTicks(Context context, AttributeSet attrs, int defStyle) {
TypedArray a = context.obtainStyledAttributes(attrs,
new int[] { android.R.attr.secondaryProgress }, defStyle, 0);
int tickColor = a.getColor(0, android.R.color.black);
mTickPaint = new Paint();
mTickPaint.setColor( context.getResources().getColor(tickColor));
a.recycle();
}
@Override
protected synchronized void onDraw(Canvas canvas) {
drawTicks(canvas);
super.onDraw(canvas);
}
private void drawTicks(Canvas canvas) {
final int available = getWidth() - getPaddingLeft() - getPaddingRight();
final int availableHeight = getHeight() - getPaddingBottom() - getPaddingTop();
int extrapadding = (int) ((availableHeight- (availableHeight * tickHeightRatio))/2);
int tickSpacing = available / (getMax() );
for (int i = 1; i < getMax(); i++) {
final float x = getPaddingLeft() + i * tickSpacing;
canvas.drawLine(x, getPaddingTop()+extrapadding, x, getHeight()-getPaddingBottom()-extrapadding, mTickPaint);
}
}
}
| Java |
package de.blinkt.openvpn.views;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
import de.blinkt.openvpn.activities.FileSelect;
import de.blinkt.openvpn.core.VpnStatus;
import de.blinkt.openvpn.core.X509Utils;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import de.blinkt.openvpn.fragments.Utils;
import java.io.*;
import static android.os.Build.*;
public class FileSelectLayout extends LinearLayout implements OnClickListener {
public void parseResponse(Intent data, Context c) {
if (VERSION.SDK_INT < VERSION_CODES.KITKAT) {
String fileData = data.getStringExtra(FileSelect.RESULT_DATA);
setData(fileData, c);
} else if (data != null) {
try {
String newData = Utils.getFilePickerResult(fileType, data, c);
if (newData!=null)
setData(newData, c);
} catch (IOException e) {
VpnStatus.logException(e);
}
}
}
public interface FileSelectCallback {
String getString(int res);
void startActivityForResult(Intent startFC, int mTaskId);
}
private boolean mIsCertificate;
private TextView mDataView;
private String mData;
private FileSelectCallback mFragment;
private int mTaskId;
private Button mSelectButton;
private Utils.FileType fileType;
private String mTitle;
private boolean mShowClear;
private TextView mDataDetails;
public FileSelectLayout(Context context, AttributeSet attrset) {
super(context, attrset);
TypedArray ta = context.obtainStyledAttributes(attrset, R.styleable.FileSelectLayout);
setupViews(ta.getString(R.styleable.FileSelectLayout_title), ta.getBoolean(R.styleable.FileSelectLayout_certificate, true));
ta.recycle();
}
public FileSelectLayout (Context context, String title, boolean isCerticate)
{
super(context);
setupViews(title, isCerticate);
}
private void setupViews(String title, boolean isCertificate) {
inflate(getContext(), R.layout.file_select, this);
mTitle = title;
mIsCertificate = isCertificate;
TextView tview = (TextView) findViewById(R.id.file_title);
tview.setText(mTitle);
mDataView = (TextView) findViewById(R.id.file_selected_item);
mDataDetails = (TextView) findViewById(R.id.file_selected_description);
mSelectButton = (Button) findViewById(R.id.file_select_button);
mSelectButton.setOnClickListener(this);
}
public void setCaller(FileSelectCallback fragment, int i, Utils.FileType ft) {
mTaskId = i;
mFragment = fragment;
fileType = ft;
}
public void getCertificateFileDialog() {
Intent startFC = new Intent(getContext(), FileSelect.class);
startFC.putExtra(FileSelect.START_DATA, mData);
startFC.putExtra(FileSelect.WINDOW_TITLE, mTitle);
if (fileType == Utils.FileType.PKCS12)
startFC.putExtra(FileSelect.DO_BASE64_ENCODE, true);
if (mShowClear)
startFC.putExtra(FileSelect.SHOW_CLEAR_BUTTON, true);
mFragment.startActivityForResult(startFC, mTaskId);
}
public String getData() {
return mData;
}
public void setData(String data, Context c) {
mData = data;
if (data == null) {
mDataView.setText(c.getString(R.string.no_data));
mDataDetails.setText("");
} else {
if (mData.startsWith(VpnProfile.DISPLAYNAME_TAG)) {
mDataView.setText(c.getString(R.string.imported_from_file, VpnProfile.getDisplayName(mData)));
} else if (mData.startsWith(VpnProfile.INLINE_TAG))
mDataView.setText(R.string.inline_file_data);
else
mDataView.setText(data);
if (mIsCertificate)
mDataDetails.setText(X509Utils.getCertificateFriendlyName(c, data));
}
}
@Override
public void onClick(View v) {
if (v == mSelectButton) {
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
Intent startFilePicker = Utils.getFilePickerIntent(fileType);
mFragment.startActivityForResult(startFilePicker, mTaskId);
} else {
getCertificateFileDialog();
}
}
}
public void setShowClear() {
mShowClear = true;
}
}
| Java |
package de.blinkt.openvpn;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.ContentProvider;
import android.content.ContentProvider.PipeDataWriter;
import android.content.ContentValues;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.provider.OpenableColumns;
import android.util.Log;
import de.blinkt.openvpn.core.VpnStatus;
/**
* A very simple content provider that can serve arbitrary asset files from
* our .apk.
*/
public class FileProvider extends ContentProvider
implements PipeDataWriter<InputStream> {
@Override
public boolean onCreate() {
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
try {
File dumpfile = getFileFromURI(uri);
MatrixCursor c = new MatrixCursor(projection);
Object[] row = new Object[projection.length];
int i=0;
for (String r:projection) {
if(r.equals(OpenableColumns.SIZE))
row[i] = dumpfile.length();
if(r.equals(OpenableColumns.DISPLAY_NAME))
row[i] = dumpfile.getName();
i++;
}
c.addRow(row);
return c;
} catch (FileNotFoundException e) {
VpnStatus.logException(e);
return null;
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// Don't support inserts.
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// Don't support deletes.
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
// Don't support updates.
return 0;
}
@Override
public String getType(Uri uri) {
// For this sample, assume all files are .apks.
return "application/octet-stream";
}
@Override
public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
File dumpfile = getFileFromURI(uri);
try {
InputStream is = new FileInputStream(dumpfile);
// Start a new thread that pipes the stream data back to the caller.
return new AssetFileDescriptor(
openPipeHelper(uri, null, null, is, this), 0,
dumpfile.length());
} catch (IOException e) {
throw new FileNotFoundException("Unable to open minidump " + uri);
}
}
private File getFileFromURI(Uri uri) throws FileNotFoundException {
// Try to open an asset with the given name.
String path = uri.getPath();
if(path.startsWith("/"))
path = path.replaceFirst("/", "");
// I think this already random enough, no need for magic secure cookies
// 1f9563a4-a1f5-2165-255f2219-111823ef.dmp
if (!path.matches("^[0-9a-z-.]*(dmp|dmp.log)$"))
throw new FileNotFoundException("url not in expect format " + uri);
File cachedir = getContext().getCacheDir();
return new File(cachedir,path);
}
@Override
public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
Bundle opts, InputStream args) {
// Transfer data from the asset to the pipe the client is reading.
byte[] buffer = new byte[8192];
int n;
FileOutputStream fout = new FileOutputStream(output.getFileDescriptor());
try {
while ((n=args.read(buffer)) >= 0) {
fout.write(buffer, 0, n);
}
} catch (IOException e) {
Log.i("OpenVPNFileProvider", "Failed transferring", e);
} finally {
try {
args.close();
} catch (IOException e) {
}
try {
fout.close();
} catch (IOException e) {
}
}
}
}
| Java |
package de.blinkt.openvpn.core;
import android.Manifest.permission;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.VpnService;
import android.os.*;
import android.os.Handler.Callback;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import de.blinkt.openvpn.activities.DisconnectVPN;
import de.blinkt.openvpn.activities.LogWindow;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
import de.blinkt.openvpn.core.VpnStatus.ByteCountListener;
import de.blinkt.openvpn.core.VpnStatus.ConnectionStatus;
import de.blinkt.openvpn.core.VpnStatus.StateListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Vector;
import static de.blinkt.openvpn.core.NetworkSpace.*;
import static de.blinkt.openvpn.core.VpnStatus.ConnectionStatus.*;
public class OpenVpnService extends VpnService implements StateListener, Callback, ByteCountListener {
public static final String START_SERVICE = "de.blinkt.openvpn.START_SERVICE";
public static final String START_SERVICE_STICKY = "de.blinkt.openvpn.START_SERVICE_STICKY";
public static final String ALWAYS_SHOW_NOTIFICATION = "de.blinkt.openvpn.NOTIFICATION_ALWAYS_VISIBLE";
public static final String DISCONNECT_VPN = "de.blinkt.openvpn.DISCONNECT_VPN";
private static final String PAUSE_VPN = "de.blinkt.openvpn.PAUSE_VPN";
private static final String RESUME_VPN = "de.blinkt.openvpn.RESUME_VPN";
private static final int OPENVPN_STATUS = 1;
private static boolean mNotificationAlwaysVisible = false;
private final Vector<String> mDnslist = new Vector<String>();
private final NetworkSpace mRoutes = new NetworkSpace();
private final NetworkSpace mRoutesv6 = new NetworkSpace();
private final IBinder mBinder = new LocalBinder();
private Thread mProcessThread = null;
private VpnProfile mProfile;
private String mDomain = null;
private CIDRIP mLocalIP = null;
private int mMtu;
private String mLocalIPv6 = null;
private DeviceStateReceiver mDeviceStateReceiver;
private boolean mDisplayBytecount = false;
private boolean mStarting = false;
private long mConnecttime;
private boolean mOvpn3 = false;
private OpenVPNManagement mManagement;
private String mLastTunCfg;
private String mRemoteGW;
// From: http://stackoverflow.com/questions/3758606/how-to-convert-byte-size-into-human-readable-format-in-java
public static String humanReadableByteCount(long bytes, boolean mbit) {
if (mbit)
bytes = bytes * 8;
int unit = mbit ? 1000 : 1024;
if (bytes < unit)
return bytes + (mbit ? " bit" : " B");
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (mbit ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (mbit ? "" : "");
if (mbit)
return String.format(Locale.getDefault(), "%.1f %sbit", bytes / Math.pow(unit, exp), pre);
else
return String.format(Locale.getDefault(), "%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
@Override
public IBinder onBind(Intent intent) {
String action = intent.getAction();
if (action != null && action.equals(START_SERVICE))
return mBinder;
else
return super.onBind(intent);
}
@Override
public void onRevoke() {
mManagement.stopVPN();
endVpnService();
}
// Similar to revoke but do not try to stop process
public void processDied() {
endVpnService();
}
private void endVpnService() {
mProcessThread = null;
VpnStatus.removeByteCountListener(this);
unregisterDeviceStateReceiver();
ProfileManager.setConntectedVpnProfileDisconnected(this);
if (!mStarting) {
stopForeground(!mNotificationAlwaysVisible);
if (!mNotificationAlwaysVisible) {
stopSelf();
VpnStatus.removeStateListener(this);
}
}
}
private void showNotification(String msg, String tickerText, boolean lowpriority, long when, ConnectionStatus status) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = getIconByConnectionStatus(status);
android.app.Notification.Builder nbuilder = new Notification.Builder(this);
if (mProfile != null)
nbuilder.setContentTitle(getString(R.string.notifcation_title, mProfile.mName));
else
nbuilder.setContentTitle(getString(R.string.notifcation_title_notconnect));
nbuilder.setContentText(msg);
nbuilder.setOnlyAlertOnce(true);
nbuilder.setOngoing(true);
nbuilder.setContentIntent(getLogPendingIntent());
nbuilder.setSmallIcon(icon);
if (when != 0)
nbuilder.setWhen(when);
// Try to set the priority available since API 16 (Jellybean)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
jbNotificationExtras(lowpriority, nbuilder);
if (tickerText != null && !tickerText.equals(""))
nbuilder.setTicker(tickerText);
@SuppressWarnings("deprecation")
Notification notification = nbuilder.getNotification();
mNotificationManager.notify(OPENVPN_STATUS, notification);
startForeground(OPENVPN_STATUS, notification);
}
private int getIconByConnectionStatus(ConnectionStatus level) {
switch (level) {
case LEVEL_CONNECTED:
return R.drawable.ic_stat_vpn;
case LEVEL_AUTH_FAILED:
case LEVEL_NONETWORK:
case LEVEL_NOTCONNECTED:
return R.drawable.ic_stat_vpn_offline;
case LEVEL_CONNECTING_NO_SERVER_REPLY_YET:
case LEVEL_WAITING_FOR_USER_INPUT:
return R.drawable.ic_stat_vpn_outline;
case LEVEL_CONNECTING_SERVER_REPLIED:
return R.drawable.ic_stat_vpn_empty_halo;
case LEVEL_VPNPAUSED:
return android.R.drawable.ic_media_pause;
case UNKNOWN_LEVEL:
default:
return R.drawable.ic_stat_vpn;
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void jbNotificationExtras(boolean lowpriority,
android.app.Notification.Builder nbuilder) {
try {
if (lowpriority) {
Method setpriority = nbuilder.getClass().getMethod("setPriority", int.class);
// PRIORITY_MIN == -2
setpriority.invoke(nbuilder, -2);
Method setUsesChronometer = nbuilder.getClass().getMethod("setUsesChronometer", boolean.class);
setUsesChronometer.invoke(nbuilder, true);
}
Intent disconnectVPN = new Intent(this, DisconnectVPN.class);
disconnectVPN.setAction(DISCONNECT_VPN);
PendingIntent disconnectPendingIntent = PendingIntent.getActivity(this, 0, disconnectVPN, 0);
nbuilder.addAction(android.R.drawable.ic_menu_close_clear_cancel,
getString(R.string.cancel_connection), disconnectPendingIntent);
Intent pauseVPN = new Intent(this, OpenVpnService.class);
if (mDeviceStateReceiver == null || !mDeviceStateReceiver.isUserPaused()) {
pauseVPN.setAction(PAUSE_VPN);
PendingIntent pauseVPNPending = PendingIntent.getService(this, 0, pauseVPN, 0);
nbuilder.addAction(android.R.drawable.ic_media_pause,
getString(R.string.pauseVPN), pauseVPNPending);
} else {
pauseVPN.setAction(RESUME_VPN);
PendingIntent resumeVPNPending = PendingIntent.getService(this, 0, pauseVPN, 0);
nbuilder.addAction(android.R.drawable.ic_media_play,
getString(R.string.resumevpn), resumeVPNPending);
}
//ignore exception
} catch (NoSuchMethodException nsm) {
VpnStatus.logException(nsm);
} catch (IllegalArgumentException e) {
VpnStatus.logException(e);
} catch (IllegalAccessException e) {
VpnStatus.logException(e);
} catch (InvocationTargetException e) {
VpnStatus.logException(e);
}
}
PendingIntent getLogPendingIntent() {
// Let the configure Button show the Log
Intent intent = new Intent(getBaseContext(), LogWindow.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
PendingIntent startLW = PendingIntent.getActivity(this, 0, intent, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
return startLW;
}
synchronized void registerDeviceStateReceiver(OpenVPNManagement magnagement) {
// Registers BroadcastReceiver to track network connection changes.
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
mDeviceStateReceiver = new DeviceStateReceiver(magnagement);
registerReceiver(mDeviceStateReceiver, filter);
VpnStatus.addByteCountListener(mDeviceStateReceiver);
}
synchronized void unregisterDeviceStateReceiver() {
if (mDeviceStateReceiver != null)
try {
VpnStatus.removeByteCountListener(mDeviceStateReceiver);
this.unregisterReceiver(mDeviceStateReceiver);
} catch (IllegalArgumentException iae) {
// I don't know why this happens:
// java.lang.IllegalArgumentException: Receiver not registered: de.blinkt.openvpn.NetworkSateReceiver@41a61a10
// Ignore for now ...
iae.printStackTrace();
}
mDeviceStateReceiver = null;
}
public void userPause(boolean shouldBePaused) {
if (mDeviceStateReceiver != null)
mDeviceStateReceiver.userPause(shouldBePaused);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getBooleanExtra(ALWAYS_SHOW_NOTIFICATION, false))
mNotificationAlwaysVisible = true;
VpnStatus.addStateListener(this);
VpnStatus.addByteCountListener(this);
if (intent != null && PAUSE_VPN.equals(intent.getAction())) {
if (mDeviceStateReceiver != null)
mDeviceStateReceiver.userPause(true);
return START_NOT_STICKY;
}
if (intent != null && RESUME_VPN.equals(intent.getAction())) {
if (mDeviceStateReceiver != null)
mDeviceStateReceiver.userPause(false);
return START_NOT_STICKY;
}
if (intent != null && START_SERVICE.equals(intent.getAction()))
return START_NOT_STICKY;
if (intent != null && START_SERVICE_STICKY.equals(intent.getAction())) {
return START_REDELIVER_INTENT;
}
assert (intent != null);
// Extract information from the intent.
String prefix = getPackageName();
String[] argv = intent.getStringArrayExtra(prefix + ".ARGV");
String nativelibdir = intent.getStringExtra(prefix + ".nativelib");
String profileUUID = intent.getStringExtra(prefix + ".profileUUID");
mProfile = ProfileManager.get(this, profileUUID);
String startTitle = getString(R.string.start_vpn_title, mProfile.mName);
String startTicker = getString(R.string.start_vpn_ticker, mProfile.mName);
showNotification(startTitle, startTicker,
false, 0, LEVEL_CONNECTING_NO_SERVER_REPLY_YET);
// Set a flag that we are starting a new VPN
mStarting = true;
// Stop the previous session by interrupting the thread.
if (mManagement != null && mManagement.stopVPN())
// an old was asked to exit, wait 1s
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
if (mProcessThread != null) {
mProcessThread.interrupt();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
// An old running VPN should now be exited
mStarting = false;
// Start a new session by creating a new thread.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mOvpn3 = prefs.getBoolean("ovpn3", false);
mOvpn3 = false;
// Open the Management Interface
if (!mOvpn3) {
// start a Thread that handles incoming messages of the managment socket
OpenVpnManagementThread ovpnManagementThread = new OpenVpnManagementThread(mProfile, this);
if (ovpnManagementThread.openManagementInterface(this)) {
Thread mSocketManagerThread = new Thread(ovpnManagementThread, "OpenVPNManagementThread");
mSocketManagerThread.start();
mManagement = ovpnManagementThread;
VpnStatus.logInfo("started Socket Thread");
} else {
return START_NOT_STICKY;
}
}
Runnable processThread;
if (mOvpn3) {
OpenVPNManagement mOpenVPN3 = instantiateOpenVPN3Core();
processThread = (Runnable) mOpenVPN3;
mManagement = mOpenVPN3;
} else {
HashMap<String, String> env = new HashMap<String, String>();
processThread = new OpenVPNThread(this, argv, env, nativelibdir);
}
mProcessThread = new Thread(processThread, "OpenVPNProcessThread");
mProcessThread.start();
if (mDeviceStateReceiver != null)
unregisterDeviceStateReceiver();
registerDeviceStateReceiver(mManagement);
ProfileManager.setConnectedVpnProfile(this, mProfile);
return START_NOT_STICKY;
}
private OpenVPNManagement instantiateOpenVPN3Core() {
return null;
}
@Override
public void onDestroy() {
if (mProcessThread != null) {
mManagement.stopVPN();
mProcessThread.interrupt();
}
if (mDeviceStateReceiver != null) {
this.unregisterReceiver(mDeviceStateReceiver);
}
// Just in case unregister for state
VpnStatus.removeStateListener(this);
}
private String getTunConfigString() {
// The format of the string is not important, only that
// two identical configurations produce the same result
String cfg = "TUNCFG UNQIUE STRING ips:";
if (mLocalIP != null)
cfg += mLocalIP.toString();
if (mLocalIPv6 != null)
cfg += mLocalIPv6.toString();
cfg += "routes: " + TextUtils.join("|", mRoutes.getNetworks(true)) + TextUtils.join("|", mRoutesv6.getNetworks(true));
cfg += "excl. routes:" + TextUtils.join("|", mRoutes.getNetworks(false)) + TextUtils.join("|", mRoutesv6.getNetworks(false));
cfg += "dns: " + TextUtils.join("|", mDnslist);
cfg += "domain: " + mDomain;
cfg += "mtu: " + mMtu;
return cfg;
}
public ParcelFileDescriptor openTun() {
//Debug.startMethodTracing(getExternalFilesDir(null).toString() + "/opentun.trace", 40* 1024 * 1024);
Builder builder = new Builder();
VpnStatus.logInfo(R.string.last_openvpn_tun_config);
if (mLocalIP == null && mLocalIPv6 == null) {
VpnStatus.logError(getString(R.string.opentun_no_ipaddr));
return null;
}
if (mLocalIP != null) {
try {
builder.addAddress(mLocalIP.mIp, mLocalIP.len);
} catch (IllegalArgumentException iae) {
VpnStatus.logError(R.string.dns_add_error, mLocalIP, iae.getLocalizedMessage());
return null;
}
}
if (mLocalIPv6 != null) {
String[] ipv6parts = mLocalIPv6.split("/");
try {
builder.addAddress(ipv6parts[0], Integer.parseInt(ipv6parts[1]));
} catch (IllegalArgumentException iae) {
VpnStatus.logError(R.string.ip_add_error, mLocalIPv6, iae.getLocalizedMessage());
return null;
}
}
for (String dns : mDnslist) {
try {
builder.addDnsServer(dns);
} catch (IllegalArgumentException iae) {
VpnStatus.logError(R.string.dns_add_error, dns, iae.getLocalizedMessage());
}
}
builder.setMtu(mMtu);
Collection<ipAddress> positiveIPv4Routes = mRoutes.getPositiveIPList();
Collection<ipAddress> positiveIPv6Routes = mRoutesv6.getPositiveIPList();
for (NetworkSpace.ipAddress route : positiveIPv4Routes) {
try {
builder.addRoute(route.getIPv4Address(), route.networkMask);
} catch (IllegalArgumentException ia) {
VpnStatus.logError(getString(R.string.route_rejected) + route + " " + ia.getLocalizedMessage());
}
}
for (NetworkSpace.ipAddress route6 : positiveIPv6Routes) {
try {
builder.addRoute(route6.getIPv6Address(), route6.networkMask);
} catch (IllegalArgumentException ia) {
VpnStatus.logError(getString(R.string.route_rejected) + route6 + " " + ia.getLocalizedMessage());
}
}
if (mDomain != null)
builder.addSearchDomain(mDomain);
VpnStatus.logInfo(R.string.local_ip_info, mLocalIP.mIp, mLocalIP.len, mLocalIPv6, mMtu);
VpnStatus.logInfo(R.string.dns_server_info, TextUtils.join(", ", mDnslist), mDomain);
VpnStatus.logInfo(R.string.routes_info_incl, TextUtils.join(", ", mRoutes.getNetworks(true)), TextUtils.join(", ", mRoutesv6.getNetworks(true)));
VpnStatus.logInfo(R.string.routes_info_excl, TextUtils.join(", ", mRoutes.getNetworks(false)),TextUtils.join(", ", mRoutesv6.getNetworks(false)));
VpnStatus.logDebug(R.string.routes_debug, TextUtils.join(", ", positiveIPv4Routes), TextUtils.join(", ", positiveIPv6Routes));
String session = mProfile.mName;
if (mLocalIP != null && mLocalIPv6 != null)
session = getString(R.string.session_ipv6string, session, mLocalIP, mLocalIPv6);
else if (mLocalIP != null)
session = getString(R.string.session_ipv4string, session, mLocalIP);
builder.setSession(session);
// No DNS Server, log a warning
if (mDnslist.size() == 0)
VpnStatus.logInfo(R.string.warn_no_dns);
mLastTunCfg = getTunConfigString();
// Reset information
mDnslist.clear();
mRoutes.clear();
mRoutesv6.clear();
mLocalIP = null;
mLocalIPv6 = null;
mDomain = null;
builder.setConfigureIntent(getLogPendingIntent());
try {
ParcelFileDescriptor tun = builder.establish();
//Debug.stopMethodTracing();
return tun;
} catch (Exception e) {
VpnStatus.logError(R.string.tun_open_error);
VpnStatus.logError(getString(R.string.error) + e.getLocalizedMessage());
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR1) {
VpnStatus.logError(R.string.tun_error_helpful);
}
return null;
}
}
public void addDNS(String dns) {
mDnslist.add(dns);
}
public void setDomain(String domain) {
if (mDomain == null) {
mDomain = domain;
}
}
public void addRoute (String dest, String mask, String gateway, String device) {
CIDRIP route = new CIDRIP(dest, mask);
boolean include = isAndroidTunDevice(device);
NetworkSpace.ipAddress gatewayIP = new NetworkSpace.ipAddress(new CIDRIP(gateway, 32),false);
if (mLocalIP==null) {
VpnStatus.logError("Local IP address unset but adding route?! This is broken! Please contact author with log");
return;
}
NetworkSpace.ipAddress localNet = new NetworkSpace.ipAddress(mLocalIP,true);
if (localNet.containsNet(gatewayIP))
include=true;
if (gateway!= null &&
(gateway.equals("255.255.255.255") || gateway.equals(mRemoteGW)))
include=true;
if (route.len == 32 && !mask.equals("255.255.255.255")) {
VpnStatus.logWarning(R.string.route_not_cidr, dest, mask);
}
if (route.normalise())
VpnStatus.logWarning(R.string.route_not_netip, dest, route.len, route.mIp);
mRoutes.addIP(route, include);
}
public void addRoutev6(String network, String device) {
String[] v6parts = network.split("/");
boolean included = isAndroidTunDevice(device);
// Tun is opened after ROUTE6, no device name may be present
try {
Inet6Address ip = (Inet6Address) InetAddress.getAllByName(v6parts[0])[0];
int mask = Integer.parseInt(v6parts[1]);
mRoutesv6.addIPv6(ip, mask, included);
} catch (UnknownHostException e) {
VpnStatus.logException(e);
}
}
private boolean isAndroidTunDevice(String device) {
return device!=null &&
(device.startsWith("tun") || "(null)".equals(device) || "vpnservice-tun".equals(device));
}
public void setMtu(int mtu) {
mMtu = mtu;
}
public void setLocalIP(CIDRIP cdrip) {
mLocalIP = cdrip;
}
public void setLocalIP(String local, String netmask, int mtu, String mode) {
mLocalIP = new CIDRIP(local, netmask);
mMtu = mtu;
mRemoteGW=null;
if (mLocalIP.len == 32 && !netmask.equals("255.255.255.255")) {
// get the netmask as IP
long netMaskAsInt = CIDRIP.getInt(netmask);
// Netmask is Ip address +/-1, assume net30/p2p with small net
if (Math.abs(netMaskAsInt - mLocalIP.getInt()) == 1) {
if ("net30".equals(mode))
mLocalIP.len = 30;
else
mLocalIP.len = 31;
} else {
if (!"p2p".equals(mode))
VpnStatus.logWarning(R.string.ip_not_cidr, local, netmask, mode);
mRemoteGW=netmask;
}
}
}
public void setLocalIPv6(String ipv6addr) {
mLocalIPv6 = ipv6addr;
}
@Override
public void updateState(String state, String logmessage, int resid, ConnectionStatus level) {
// If the process is not running, ignore any state,
// Notification should be invisible in this state
doSendBroadcast(state, level);
if (mProcessThread == null && !mNotificationAlwaysVisible)
return;
boolean lowpriority = false;
// Display byte count only after being connected
{
if (level == LEVEL_WAITING_FOR_USER_INPUT) {
// The user is presented a dialog of some kind, no need to inform the user
// with a notifcation
return;
} else if (level == LEVEL_CONNECTED) {
mDisplayBytecount = true;
mConnecttime = System.currentTimeMillis();
lowpriority = true;
} else {
mDisplayBytecount = false;
}
// Other notifications are shown,
// This also mean we are no longer connected, ignore bytecount messages until next
// CONNECTED
// Does not work :(
String msg = getString(resid);
String ticker = msg;
showNotification(msg + " " + logmessage, ticker, lowpriority , 0, level);
}
}
private void doSendBroadcast(String state, ConnectionStatus level) {
Intent vpnstatus = new Intent();
vpnstatus.setAction("de.blinkt.openvpn.VPN_STATUS");
vpnstatus.putExtra("status", level.toString());
vpnstatus.putExtra("detailstatus", state);
sendBroadcast(vpnstatus, permission.ACCESS_NETWORK_STATE);
}
@Override
public void updateByteCount(long in, long out, long diffIn, long diffOut) {
if (mDisplayBytecount) {
String netstat = String.format(getString(R.string.statusline_bytecount),
humanReadableByteCount(in, false),
humanReadableByteCount(diffIn / OpenVPNManagement.mBytecountInterval, true),
humanReadableByteCount(out, false),
humanReadableByteCount(diffOut / OpenVPNManagement.mBytecountInterval, true));
boolean lowpriority = !mNotificationAlwaysVisible;
showNotification(netstat, null, lowpriority, mConnecttime, LEVEL_CONNECTED);
}
}
@Override
public boolean handleMessage(Message msg) {
Runnable r = msg.getCallback();
if (r != null) {
r.run();
return true;
} else {
return false;
}
}
public OpenVPNManagement getManagement() {
return mManagement;
}
public String getTunReopenStatus() {
String currentConfiguration = getTunConfigString();
if (currentConfiguration.equals(mLastTunCfg))
return "NOACTION";
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
return "OPEN_AFTER_CLOSE";
else
return "OPEN_BEFORE_CLOSE";
}
public class LocalBinder extends Binder {
public OpenVpnService getService() {
// Return this instance of LocalService so clients can call public methods
return OpenVpnService.this;
}
}
}
| Java |
package de.blinkt.openvpn.core;
import java.security.InvalidKeyException;
public class NativeUtils {
public static native byte[] rsasign(byte[] input,int pkey) throws InvalidKeyException;
static native void jniclose(int fdint);
static {
System.loadLibrary("stlport_shared");
System.loadLibrary("opvpnutil");
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.