code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package de.blinkt.openvpn.core;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.preference.PreferenceManager;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.core.VpnStatus.ByteCountListener;
import java.util.LinkedList;
import static de.blinkt.openvpn.core.OpenVPNManagement.pauseReason;
public class DeviceStateReceiver extends BroadcastReceiver implements ByteCountListener {
private int lastNetwork = -1;
private OpenVPNManagement mManagement;
// Window time in s
private final int TRAFFIC_WINDOW = 60;
// Data traffic limit in bytes
private final long TRAFFIC_LIMIT = 64 * 1024;
connectState network = connectState.DISCONNECTED;
connectState screen = connectState.SHOULDBECONNECTED;
connectState userpause = connectState.SHOULDBECONNECTED;
private String lastStateMsg = null;
enum connectState {
SHOULDBECONNECTED,
PENDINGDISCONNECT,
DISCONNECTED
}
static class Datapoint {
private Datapoint(long t, long d) {
timestamp = t;
data = d;
}
long timestamp;
long data;
}
LinkedList<Datapoint> trafficdata = new LinkedList<DeviceStateReceiver.Datapoint>();
@Override
public void updateByteCount(long in, long out, long diffIn, long diffOut) {
if (screen != connectState.PENDINGDISCONNECT)
return;
long total = diffIn + diffOut;
trafficdata.add(new Datapoint(System.currentTimeMillis(), total));
while (trafficdata.getFirst().timestamp <= (System.currentTimeMillis() - TRAFFIC_WINDOW * 1000)) {
trafficdata.removeFirst();
}
long windowtraffic = 0;
for (Datapoint dp : trafficdata)
windowtraffic += dp.data;
if (windowtraffic < TRAFFIC_LIMIT) {
screen = connectState.DISCONNECTED;
VpnStatus.logInfo(R.string.screenoff_pause,
OpenVpnService.humanReadableByteCount(TRAFFIC_LIMIT, false), TRAFFIC_WINDOW);
mManagement.pause(getPauseReason());
}
}
public void userPause(boolean pause) {
if (pause) {
userpause = connectState.DISCONNECTED;
// Check if we should disconnect
mManagement.pause(getPauseReason());
} else {
boolean wereConnected = shouldBeConnected();
userpause = connectState.SHOULDBECONNECTED;
if (shouldBeConnected() && !wereConnected)
mManagement.resume();
else
// Update the reason why we currently paused
mManagement.pause(getPauseReason());
}
}
public DeviceStateReceiver(OpenVPNManagement magnagement) {
super();
mManagement = magnagement;
}
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
networkStateChange(context);
} else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
boolean screenOffPause = prefs.getBoolean("screenoff", false);
if (screenOffPause) {
if (ProfileManager.getLastConnectedVpn()!=null && !ProfileManager.getLastConnectedVpn().mPersistTun)
VpnStatus.logError(R.string.screen_nopersistenttun);
screen = connectState.PENDINGDISCONNECT;
fillTrafficData();
if (network == connectState.DISCONNECTED || userpause == connectState.DISCONNECTED)
screen = connectState.DISCONNECTED;
}
} else if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
// Network was disabled because screen off
boolean connected = shouldBeConnected();
screen = connectState.SHOULDBECONNECTED;
/* should be connected has changed because the screen is on now, connect the VPN */
if (shouldBeConnected() != connected)
mManagement.resume();
else if (!shouldBeConnected())
/*Update the reason why we are still paused */
mManagement.pause(getPauseReason());
}
}
private void fillTrafficData() {
trafficdata.add(new Datapoint(System.currentTimeMillis(), TRAFFIC_LIMIT));
}
public void networkStateChange(Context context) {
NetworkInfo networkInfo = getCurrentNetworkInfo(context);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean sendusr1 = prefs.getBoolean("netchangereconnect", true);
String netstatestring;
if (networkInfo == null) {
netstatestring = "not connected";
} else {
String subtype = networkInfo.getSubtypeName();
if (subtype == null)
subtype = "";
String extrainfo = networkInfo.getExtraInfo();
if (extrainfo == null)
extrainfo = "";
/*
if(networkInfo.getType()==android.net.ConnectivityManager.TYPE_WIFI) {
WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiinfo = wifiMgr.getConnectionInfo();
extrainfo+=wifiinfo.getBSSID();
subtype += wifiinfo.getNetworkId();
}*/
netstatestring = String.format("%2$s %4$s to %1$s %3$s", networkInfo.getTypeName(),
networkInfo.getDetailedState(), extrainfo, subtype);
}
if (networkInfo != null && networkInfo.getState() == State.CONNECTED) {
int newnet = networkInfo.getType();
network = connectState.SHOULDBECONNECTED;
if (sendusr1 && lastNetwork != newnet) {
if (screen == connectState.PENDINGDISCONNECT)
screen = connectState.DISCONNECTED;
if (shouldBeConnected()) {
if (lastNetwork == -1) {
mManagement.resume();
} else {
mManagement.reconnect();
}
}
lastNetwork = newnet;
}
} else if (networkInfo == null) {
// Not connected, stop openvpn, set last connected network to no network
lastNetwork = -1;
if (sendusr1) {
network = connectState.DISCONNECTED;
// Set screen state to be disconnected if disconnect pending
if (screen == connectState.PENDINGDISCONNECT)
screen = connectState.DISCONNECTED;
mManagement.pause(getPauseReason());
}
}
if (!netstatestring.equals(lastStateMsg))
VpnStatus.logInfo(R.string.netstatus, netstatestring);
lastStateMsg = netstatestring;
}
public boolean isUserPaused() {
return userpause == connectState.DISCONNECTED;
}
private boolean shouldBeConnected() {
return (screen == connectState.SHOULDBECONNECTED && userpause == connectState.SHOULDBECONNECTED &&
network == connectState.SHOULDBECONNECTED);
}
private pauseReason getPauseReason() {
if (userpause == connectState.DISCONNECTED)
return pauseReason.userPause;
if (screen == connectState.DISCONNECTED)
return pauseReason.screenOff;
if (network == connectState.DISCONNECTED)
return pauseReason.noNetwork;
return pauseReason.userPause;
}
private NetworkInfo getCurrentNetworkInfo(Context context) {
ConnectivityManager conn = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
return conn.getActiveNetworkInfo();
}
}
| Java |
package de.blinkt.openvpn.core;
import java.util.Locale;
class CIDRIP {
String mIp;
int len;
public CIDRIP(String ip, String mask) {
mIp = ip;
long netmask = getInt(mask);
// Add 33. bit to ensure the loop terminates
netmask += 1l << 32;
int lenZeros = 0;
while ((netmask & 0x1) == 0) {
lenZeros++;
netmask = netmask >> 1;
}
// Check if rest of netmask is only 1s
if (netmask != (0x1ffffffffl >> lenZeros)) {
// Asume no CIDR, set /32
len = 32;
} else {
len = 32 - lenZeros;
}
}
public CIDRIP(String address, int prefix_length) {
len = prefix_length;
mIp = address;
}
@Override
public String toString() {
return String.format(Locale.ENGLISH, "%s/%d", mIp, len);
}
public boolean normalise() {
long ip = getInt(mIp);
long newip = ip & (0xffffffffl << (32 - len));
if (newip != ip) {
mIp = String.format("%d.%d.%d.%d", (newip & 0xff000000) >> 24, (newip & 0xff0000) >> 16, (newip & 0xff00) >> 8, newip & 0xff);
return true;
} else {
return false;
}
}
static long getInt(String ipaddr) {
String[] ipt = ipaddr.split("\\.");
long ip = 0;
ip += Long.parseLong(ipt[0]) << 24;
ip += Integer.parseInt(ipt[1]) << 16;
ip += Integer.parseInt(ipt[2]) << 8;
ip += Integer.parseInt(ipt[3]);
return ip;
}
public long getInt() {
return getInt(mIp);
}
} | Java |
package de.blinkt.openvpn.core;
import android.util.Log;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
import de.blinkt.openvpn.core.VpnStatus.ConnectionStatus;
import de.blinkt.openvpn.core.VpnStatus.LogItem;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class OpenVPNThread implements Runnable {
private static final String DUMP_PATH_STRING = "Dump path: ";
private static final String TAG = "OpenVPN";
public static final int M_FATAL = (1 << 4);
public static final int M_NONFATAL = (1 << 5);
public static final int M_WARN = (1 << 6);
public static final int M_DEBUG = (1 << 7);
private String[] mArgv;
private Process mProcess;
private String mNativeDir;
private OpenVpnService mService;
private String mDumpPath;
private Map<String, String> mProcessEnv;
public OpenVPNThread(OpenVpnService service,String[] argv, Map<String,String> processEnv, String nativelibdir)
{
mArgv = argv;
mNativeDir = nativelibdir;
mService = service;
mProcessEnv = processEnv;
}
public void stopProcess() {
mProcess.destroy();
}
@Override
public void run() {
try {
Log.i(TAG, "Starting openvpn");
startOpenVPNThreadArgs(mArgv, mProcessEnv);
Log.i(TAG, "Giving up");
} catch (Exception e) {
VpnStatus.logException("Starting OpenVPN Thread" ,e);
Log.e(TAG, "OpenVPNThread Got " + e.toString());
} finally {
int exitvalue = 0;
try {
if (mProcess!=null)
exitvalue = mProcess.waitFor();
} catch ( IllegalThreadStateException ite) {
VpnStatus.logError("Illegal Thread state: " + ite.getLocalizedMessage());
} catch (InterruptedException ie) {
VpnStatus.logError("InterruptedException: " + ie.getLocalizedMessage());
}
if( exitvalue != 0)
VpnStatus.logError("Process exited with exit value " + exitvalue);
VpnStatus.updateStateString("NOPROCESS", "No process running.", R.string.state_noprocess, ConnectionStatus.LEVEL_NOTCONNECTED);
if(mDumpPath!=null) {
try {
BufferedWriter logout = new BufferedWriter(new FileWriter(mDumpPath + ".log"));
SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.GERMAN);
for(LogItem li : VpnStatus.getlogbuffer()){
String time = timeformat.format(new Date(li.getLogtime()));
logout.write(time +" " + li.getString(mService) + "\n");
}
logout.close();
VpnStatus.logError(R.string.minidump_generated);
} catch (IOException e) {
VpnStatus.logError("Writing minidump log: " + e.getLocalizedMessage());
}
}
mService.processDied();
Log.i(TAG, "Exiting");
}
}
private void startOpenVPNThreadArgs(String[] argv, Map<String, String> env) {
LinkedList<String> argvlist = new LinkedList<String>();
Collections.addAll(argvlist, argv);
ProcessBuilder pb = new ProcessBuilder(argvlist);
// Hack O rama
String lbpath = genLibraryPath(argv, pb);
pb.environment().put("LD_LIBRARY_PATH", lbpath);
// Add extra variables
for(Entry<String,String> e:env.entrySet()){
pb.environment().put(e.getKey(), e.getValue());
}
pb.redirectErrorStream(true);
try {
mProcess = pb.start();
// Close the output, since we don't need it
mProcess.getOutputStream().close();
InputStream in = mProcess.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while(true) {
String logline = br.readLine();
if(logline==null)
return;
if (logline.startsWith(DUMP_PATH_STRING))
mDumpPath = logline.substring(DUMP_PATH_STRING.length());
// 1380308330.240114 18000002 Send to HTTP proxy: 'X-Online-Host: bla.blabla.com'
Pattern p = Pattern.compile("(\\d+).(\\d+) ([0-9a-f])+ (.*)");
Matcher m = p.matcher(logline);
if(m.matches()) {
int flags = Integer.parseInt(m.group(3),16);
String msg = m.group(4);
int logLevel = flags & 0x0F;
VpnStatus.LogLevel logStatus = VpnStatus.LogLevel.INFO;
if ((flags & M_FATAL) != 0)
logStatus = VpnStatus.LogLevel.ERROR;
else if ((flags & M_NONFATAL)!=0)
logStatus = VpnStatus.LogLevel.WARNING;
else if ((flags & M_WARN)!=0)
logStatus = VpnStatus.LogLevel.WARNING;
else if ((flags & M_DEBUG)!=0)
logStatus = VpnStatus.LogLevel.VERBOSE;
if (msg.startsWith("MANAGEMENT: CMD"))
logLevel = Math.max(4, logLevel);
VpnStatus.logMessageOpenVPN(logStatus,logLevel,msg);
} else {
VpnStatus.logInfo("P:" + logline);
}
}
} catch (IOException e) {
VpnStatus.logException("Error reading from output of OpenVPN process" , e);
stopProcess();
}
}
private String genLibraryPath(String[] argv, ProcessBuilder pb) {
// Hack until I find a good way to get the real library path
String applibpath = argv[0].replace("/cache/" + VpnProfile.MINIVPN , "/lib");
String lbpath = pb.environment().get("LD_LIBRARY_PATH");
if(lbpath==null)
lbpath = applibpath;
else
lbpath = lbpath + ":" + applibpath;
if (!applibpath.equals(mNativeDir)) {
lbpath = lbpath + ":" + mNativeDir;
}
return lbpath;
}
}
| Java |
package de.blinkt.openvpn.core;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
public class VPNLaunchHelper {
static private boolean writeMiniVPN(Context context) {
File mvpnout = new File(context.getCacheDir(),VpnProfile.MINIVPN);
if (mvpnout.exists() && mvpnout.canExecute())
return true;
IOException e2 = null;
try {
InputStream mvpn;
try {
mvpn = context.getAssets().open("minivpn." + Build.CPU_ABI);
}
catch (IOException errabi) {
VpnStatus.logInfo("Failed getting assets for archicture " + Build.CPU_ABI);
e2=errabi;
mvpn = context.getAssets().open("minivpn." + Build.CPU_ABI2);
}
FileOutputStream fout = new FileOutputStream(mvpnout);
byte buf[]= new byte[4096];
int lenread = mvpn.read(buf);
while(lenread> 0) {
fout.write(buf, 0, lenread);
lenread = mvpn.read(buf);
}
fout.close();
if(!mvpnout.setExecutable(true)) {
VpnStatus.logError("Failed to set minivpn executable");
return false;
}
return true;
} catch (IOException e) {
if(e2!=null)
VpnStatus.logException(e2);
VpnStatus.logException(e);
return false;
}
}
public static void startOpenVpn(VpnProfile startprofile, Context context) {
if(!writeMiniVPN(context)) {
VpnStatus.logError("Error writing minivpn binary");
return;
}
VpnStatus.logInfo(R.string.building_configration);
Intent startVPN = startprofile.prepareIntent(context);
if(startVPN!=null)
context.startService(startVPN);
}
}
| Java |
package de.blinkt.openvpn.core;
import android.content.Context;
import android.text.TextUtils;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
import org.spongycastle.util.io.pem.PemObject;
import org.spongycastle.util.io.pem.PemReader;
import javax.security.auth.x500.X500Principal;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Hashtable;
public class X509Utils {
public static Certificate getCertificateFromFile(String certfilename) throws FileNotFoundException, CertificateException {
CertificateFactory certFact = CertificateFactory.getInstance("X.509");
InputStream inStream;
if(VpnProfile.isEmbedded(certfilename)) {
// The java certifcate reader is ... kind of stupid
// It does NOT ignore chars before the --BEGIN ...
int subIndex = certfilename.indexOf("-----BEGIN CERTIFICATE-----");
subIndex = Math.max(0,subIndex);
inStream = new ByteArrayInputStream(certfilename.substring(subIndex).getBytes());
} else {
inStream = new FileInputStream(certfilename);
}
return certFact.generateCertificate(inStream);
}
public static PemObject readPemObjectFromFile (String keyfilename) throws IOException {
Reader inStream;
if(VpnProfile.isEmbedded(keyfilename))
inStream = new StringReader(VpnProfile.getEmbeddedContent(keyfilename));
else
inStream = new FileReader(new File(keyfilename));
PemReader pr = new PemReader(inStream);
PemObject r = pr.readPemObject();
pr.close();
return r;
}
public static String getCertificateFriendlyName (Context c, String filename) {
if(!TextUtils.isEmpty(filename)) {
try {
X509Certificate cert = (X509Certificate) getCertificateFromFile(filename);
return getCertificateFriendlyName(cert);
} catch (Exception e) {
VpnStatus.logError("Could not read certificate" + e.getLocalizedMessage());
}
}
return c.getString(R.string.cannotparsecert);
}
public static String getCertificateFriendlyName(X509Certificate cert) {
X500Principal principal = cert.getSubjectX500Principal();
byte[] encodedSubject = principal.getEncoded();
String friendlyName=null;
/* Hack so we do not have to ship a whole Spongy/bouncycastle */
Exception exp=null;
try {
Class X509NameClass = Class.forName("com.android.org.bouncycastle.asn1.x509.X509Name");
Method getInstance = X509NameClass.getMethod("getInstance",Object.class);
Hashtable defaultSymbols = (Hashtable) X509NameClass.getField("DefaultSymbols").get(X509NameClass);
if (!defaultSymbols.containsKey("1.2.840.113549.1.9.1"))
defaultSymbols.put("1.2.840.113549.1.9.1","eMail");
Object subjectName = getInstance.invoke(X509NameClass, encodedSubject);
Method toString = X509NameClass.getMethod("toString",boolean.class,Hashtable.class);
friendlyName= (String) toString.invoke(subjectName,true,defaultSymbols);
} catch (ClassNotFoundException e) {
exp =e ;
} catch (NoSuchMethodException e) {
exp =e;
} catch (InvocationTargetException e) {
exp =e;
} catch (IllegalAccessException e) {
exp =e;
} catch (NoSuchFieldException e) {
exp =e;
}
if (exp!=null)
VpnStatus.logException("Getting X509 Name from certificate", exp);
/* Fallback if the reflection method did not work */
if(friendlyName==null)
friendlyName = principal.getName();
// Really evil hack to decode email address
// See: http://code.google.com/p/android/issues/detail?id=21531
String[] parts = friendlyName.split(",");
for (int i=0;i<parts.length;i++){
String part = parts[i];
if (part.startsWith("1.2.840.113549.1.9.1=#16")) {
parts[i] = "email=" + ia5decode(part.replace("1.2.840.113549.1.9.1=#16", ""));
}
}
friendlyName = TextUtils.join(",", parts);
return friendlyName;
}
public static boolean isPrintableChar(char c) {
Character.UnicodeBlock block = Character.UnicodeBlock.of( c );
return (!Character.isISOControl(c)) &&
block != null &&
block != Character.UnicodeBlock.SPECIALS;
}
private static String ia5decode(String ia5string) {
String d = "";
for (int i=1;i<ia5string.length();i=i+2) {
String hexstr = ia5string.substring(i-1,i+1);
char c = (char) Integer.parseInt(hexstr,16);
if (isPrintableChar(c)) {
d+=c;
} else if (i==1 && (c==0x12 || c==0x1b)) {
; // ignore
} else {
d += "\\x" + hexstr;
}
}
return d;
}
}
| Java |
package de.blinkt.openvpn.core;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.RestrictionEntry;
import android.os.Build;
import android.os.Bundle;
import java.util.ArrayList;
import de.blinkt.openvpn.R;
/**
* Created by arne on 25.07.13.
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class GetRestrictionReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
final PendingResult result = goAsync();
new Thread() {
@Override
public void run() {
final Bundle extras = new Bundle();
ArrayList<RestrictionEntry> restrictionEntries = initRestrictions(context);
extras.putParcelableArrayList(Intent.EXTRA_RESTRICTIONS_LIST, restrictionEntries);
result.setResult(Activity.RESULT_OK,null,extras);
result.finish();
}
}.run();
}
private ArrayList<RestrictionEntry> initRestrictions(Context context) {
ArrayList<RestrictionEntry> restrictions = new ArrayList<RestrictionEntry>();
RestrictionEntry allowChanges = new RestrictionEntry("allow_changes",false);
allowChanges.setTitle(context.getString(R.string.allow_vpn_changes));
restrictions.add(allowChanges);
return restrictions;
}
}
| Java |
package de.blinkt.openvpn.core;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager;
import android.util.Log;
import org.jetbrains.annotations.NotNull;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
import de.blinkt.openvpn.core.VpnStatus.ConnectionStatus;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.*;
public class OpenVpnManagementThread implements Runnable, OpenVPNManagement {
private static final String TAG = "openvpn";
private LocalSocket mSocket;
private VpnProfile mProfile;
private OpenVpnService mOpenVPNService;
private LinkedList<FileDescriptor> mFDList=new LinkedList<FileDescriptor>();
private LocalServerSocket mServerSocket;
private boolean mReleaseHold=true;
private boolean mWaitingForRelease=false;
private long mLastHoldRelease=0;
private static Vector<OpenVpnManagementThread> active=new Vector<OpenVpnManagementThread>();
private LocalSocket mServerSocketLocal;
private pauseReason lastPauseReason = pauseReason.noNetwork;
public OpenVpnManagementThread(VpnProfile profile, OpenVpnService openVpnService) {
mProfile = profile;
mOpenVPNService = openVpnService;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(openVpnService);
boolean managemeNetworkState = prefs.getBoolean("netchangereconnect", true);
if(managemeNetworkState)
mReleaseHold=false;
}
public boolean openManagementInterface(@NotNull Context c) {
// Could take a while to open connection
int tries=8;
String socketName = (c.getCacheDir().getAbsolutePath() + "/" + "mgmtsocket");
// The mServerSocketLocal is transferred to the LocalServerSocket, ignore warning
mServerSocketLocal = new LocalSocket();
while(tries > 0 && !mServerSocketLocal.isConnected()) {
try {
mServerSocketLocal.bind(new LocalSocketAddress(socketName,
LocalSocketAddress.Namespace.FILESYSTEM));
} catch (IOException e) {
// wait 300 ms before retrying
try { Thread.sleep(300);
} catch (InterruptedException e1) {
}
}
tries--;
}
try {
mServerSocket = new LocalServerSocket(mServerSocketLocal.getFileDescriptor());
return true;
} catch (IOException e) {
VpnStatus.logException(e);
}
return false;
}
public void managmentCommand(String cmd) {
try {
if(mSocket!=null && mSocket.getOutputStream() !=null) {
mSocket.getOutputStream().write(cmd.getBytes());
mSocket.getOutputStream().flush();
}
}catch (IOException e) {
// Ignore socket stack traces
}
}
@Override
public void run() {
byte [] buffer =new byte[2048];
// mSocket.setSoTimeout(5); // Setting a timeout cannot be that bad
String pendingInput="";
active.add(this);
try {
// Wait for a client to connect
mSocket= mServerSocket.accept();
InputStream instream = mSocket.getInputStream();
// Close the management socket after client connected
mServerSocket.close();
// Closing one of the two sockets also closes the other
//mServerSocketLocal.close();
while(true) {
int numbytesread = instream.read(buffer);
if(numbytesread==-1)
return;
FileDescriptor[] fds = null;
try {
fds = mSocket.getAncillaryFileDescriptors();
} catch (IOException e) {
VpnStatus.logException("Error reading fds from socket", e);
}
if(fds!=null){
Collections.addAll(mFDList, fds);
}
String input = new String(buffer,0,numbytesread,"UTF-8");
pendingInput += input;
pendingInput=processInput(pendingInput);
}
} catch (IOException e) {
if (!e.getMessage().equals("socket closed"))
VpnStatus.logException(e);
}
active.remove(this);
}
//! Hack O Rama 2000!
private void protectFileDescriptor(FileDescriptor fd) {
Exception exp;
try {
Method getInt = FileDescriptor.class.getDeclaredMethod("getInt$");
int fdint = (Integer) getInt.invoke(fd);
// You can even get more evil by parsing toString() and extract the int from that :)
mOpenVPNService.protect(fdint);
//ParcelFileDescriptor pfd = ParcelFileDescriptor.fromFd(fdint);
//pfd.close();
NativeUtils.jniclose(fdint);
return;
} catch (NoSuchMethodException e) {
exp =e;
} catch (IllegalArgumentException e) {
exp =e;
} catch (IllegalAccessException e) {
exp =e;
} catch (InvocationTargetException e) {
exp =e;
} catch (NullPointerException e) {
exp =e;
}
Log.d("Openvpn", "Failed to retrieve fd from socket: " + fd);
VpnStatus.logException("Failed to retrieve fd from socket (" + fd + ")" , exp);
}
private String processInput(String pendingInput) {
while(pendingInput.contains("\n")) {
String[] tokens = pendingInput.split("\\r?\\n", 2);
processCommand(tokens[0]);
if(tokens.length == 1)
// No second part, newline was at the end
pendingInput="";
else
pendingInput=tokens[1];
}
return pendingInput;
}
private void processCommand(String command) {
//Log.i(TAG, "Line from managment" + command);
if (command.startsWith(">") && command.contains(":")) {
String[] parts = command.split(":",2);
String cmd = parts[0].substring(1);
String argument = parts[1];
if(cmd.equals("INFO")) {
/* Ignore greeting from management */
return;
}else if (cmd.equals("PASSWORD")) {
processPWCommand(argument);
} else if (cmd.equals("HOLD")) {
handleHold();
} else if (cmd.equals("NEED-OK")) {
processNeedCommand(argument);
} else if (cmd.equals("BYTECOUNT")){
processByteCount(argument);
} else if (cmd.equals("STATE")) {
processState(argument);
} else if (cmd.equals("PROXY")) {
processProxyCMD(argument);
} else if (cmd.equals("LOG")) {
processLogMessage(argument);
} else if (cmd.equals("RSA_SIGN")) {
processSignCommand(argument);
} else {
VpnStatus.logWarning("MGMT: Got unrecognized command" + command);
Log.i(TAG, "Got unrecognized command" + command);
}
} else if (command.startsWith("SUCCESS:")) {
/* Ignore this kind of message too */
return;
} else {
Log.i(TAG, "Got unrecognized line from managment" + command);
VpnStatus.logWarning("MGMT: Got unrecognized line from management:" + command);
}
}
private void processLogMessage(String argument) {
String[] args = argument.split(",",4);
// 0 unix time stamp
// 1 log level N,I,E etc.
/*
(b) zero or more message flags in a single string:
I -- informational
F -- fatal error
N -- non-fatal error
W -- warning
D -- debug, and
*/
// 2 log message
Log.d("OpenVPN", argument);
VpnStatus.LogLevel level;
if (args[1].equals("I")) {
level = VpnStatus.LogLevel.INFO;
} else if (args[1].equals("W")) {
level = VpnStatus.LogLevel.WARNING;
} else if (args[1].equals("D")) {
level = VpnStatus.LogLevel.VERBOSE;
} else if (args[1].equals("F")) {
level = VpnStatus.LogLevel.ERROR;
} else {
level = VpnStatus.LogLevel.INFO;
}
int ovpnlevel = Integer.parseInt(args[2]) & 0x0F;
String msg = args[3];
if (msg.startsWith("MANAGEMENT: CMD"))
ovpnlevel = Math.max(4, ovpnlevel);
VpnStatus.logMessageOpenVPN(level,ovpnlevel, msg);
}
private void handleHold() {
if(mReleaseHold) {
releaseHoldCmd();
} else {
mWaitingForRelease=true;
VpnStatus.updateStatePause(lastPauseReason);
}
}
private void releaseHoldCmd() {
if ((System.currentTimeMillis()- mLastHoldRelease) < 5000) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
}
mWaitingForRelease=false;
mLastHoldRelease = System.currentTimeMillis();
managmentCommand("hold release\n");
managmentCommand("bytecount " + mBytecountInterval + "\n");
managmentCommand("state on\n");
//managmentCommand("log on all\n");
}
public void releaseHold() {
mReleaseHold=true;
if(mWaitingForRelease)
releaseHoldCmd();
}
private void processProxyCMD(String argument) {
String[] args = argument.split(",",3);
SocketAddress proxyaddr = ProxyDetection.detectProxy(mProfile);
if(args.length >= 2) {
String proto = args[1];
if(proto.equals("UDP")) {
proxyaddr=null;
}
}
if(proxyaddr instanceof InetSocketAddress ){
InetSocketAddress isa = (InetSocketAddress) proxyaddr;
VpnStatus.logInfo(R.string.using_proxy, isa.getHostName(), isa.getPort());
String proxycmd = String.format(Locale.ENGLISH,"proxy HTTP %s %d\n", isa.getHostName(),isa.getPort());
managmentCommand(proxycmd);
} else {
managmentCommand("proxy NONE\n");
}
}
private void processState(String argument) {
String[] args = argument.split(",",3);
String currentstate = args[1];
if(args[2].equals(",,"))
VpnStatus.updateStateString(currentstate, "");
else
VpnStatus.updateStateString(currentstate, args[2]);
}
private void processByteCount(String argument) {
// >BYTECOUNT:{BYTES_IN},{BYTES_OUT}
int comma = argument.indexOf(',');
long in = Long.parseLong(argument.substring(0, comma));
long out = Long.parseLong(argument.substring(comma+1));
VpnStatus.updateByteCount(in, out);
}
private void processNeedCommand(String argument) {
int p1 =argument.indexOf('\'');
int p2 = argument.indexOf('\'',p1+1);
String needed = argument.substring(p1+1, p2);
String extra = argument.split(":",2)[1];
String status = "ok";
if (needed.equals("PROTECTFD")) {
FileDescriptor fdtoprotect = mFDList.pollFirst();
protectFileDescriptor(fdtoprotect);
} else if (needed.equals("DNSSERVER")) {
mOpenVPNService.addDNS(extra);
}else if (needed.equals("DNSDOMAIN")){
mOpenVPNService.setDomain(extra);
} else if (needed.equals("ROUTE")) {
String[] routeparts = extra.split(" ");
/*
buf_printf (&out, "%s %s %s dev %s", network, netmask, gateway, rgi->iface);
else
buf_printf (&out, "%s %s %s", network, netmask, gateway);
*/
if(routeparts.length==5) {
assert(routeparts[3].equals("dev"));
mOpenVPNService.addRoute(routeparts[0], routeparts[1], routeparts[2], routeparts[4]);
} else if (routeparts.length >= 3) {
mOpenVPNService.addRoute(routeparts[0], routeparts[1], routeparts[2], null);
} else {
VpnStatus.logError("Unrecognized ROUTE cmd:" + Arrays.toString(routeparts) + " | " + argument);
}
} else if (needed.equals("ROUTE6")) {
String[] routeparts = extra.split(" ");
mOpenVPNService.addRoutev6(routeparts[0],routeparts[1]);
} else if (needed.equals("IFCONFIG")) {
String[] ifconfigparts = extra.split(" ");
int mtu = Integer.parseInt(ifconfigparts[2]);
mOpenVPNService.setLocalIP(ifconfigparts[0], ifconfigparts[1],mtu,ifconfigparts[3]);
} else if (needed.equals("IFCONFIG6")) {
mOpenVPNService.setLocalIPv6(extra);
} else if (needed.equals("PERSIST_TUN_ACTION")) {
// check if tun cfg stayed the same
status = mOpenVPNService.getTunReopenStatus();
} else if (needed.equals("OPENTUN")) {
if(sendTunFD(needed,extra))
return;
else
status="cancel";
// This not nice or anything but setFileDescriptors accepts only FilDescriptor class :(
} else {
Log.e(TAG,"Unkown needok command " + argument);
return;
}
String cmd = String.format("needok '%s' %s\n", needed, status);
managmentCommand(cmd);
}
private boolean sendTunFD (String needed, String extra) {
Exception exp;
if(!extra.equals("tun")) {
// We only support tun
VpnStatus.logError(String.format("Device type %s requested, but only tun is possible with the Android API, sorry!",extra));
return false;
}
ParcelFileDescriptor pfd = mOpenVPNService.openTun();
if(pfd==null)
return false;
Method setInt;
int fdint = pfd.getFd();
try {
setInt = FileDescriptor.class.getDeclaredMethod("setInt$",int.class);
FileDescriptor fdtosend = new FileDescriptor();
setInt.invoke(fdtosend,fdint);
FileDescriptor[] fds = {fdtosend};
mSocket.setFileDescriptorsForSend(fds);
// Trigger a send so we can close the fd on our side of the channel
// The API documentation fails to mention that it will not reset the file descriptor to
// be send and will happily send the file descriptor on every write ...
String cmd = String.format("needok '%s' %s\n", needed, "ok");
managmentCommand(cmd);
// Set the FileDescriptor to null to stop this mad behavior
mSocket.setFileDescriptorsForSend(null);
pfd.close();
return true;
} catch (NoSuchMethodException e) {
exp =e;
} catch (IllegalArgumentException e) {
exp =e;
} catch (IllegalAccessException e) {
exp =e;
} catch (InvocationTargetException e) {
exp =e;
} catch (IOException e) {
exp =e;
}
VpnStatus.logException("Could not send fd over socket" , exp);
return false;
}
private void processPWCommand(String argument) {
//argument has the form Need 'Private Key' password
// or ">PASSWORD:Verification Failed: '%s' ['%s']"
String needed;
try{
int p1 = argument.indexOf('\'');
int p2 = argument.indexOf('\'',p1+1);
needed = argument.substring(p1+1, p2);
if (argument.startsWith("Verification Failed")) {
proccessPWFailed(needed, argument.substring(p2+1));
return;
}
} catch (StringIndexOutOfBoundsException sioob) {
VpnStatus.logError("Could not parse management Password command: " + argument);
return;
}
String pw=null;
if(needed.equals("Private Key")) {
pw = mProfile.getPasswordPrivateKey();
} else if (needed.equals("Auth")) {
String usercmd = String.format("username '%s' %s\n",
needed, VpnProfile.openVpnEscape(mProfile.mUsername));
managmentCommand(usercmd);
pw = mProfile.getPasswordAuth();
}
if(pw!=null) {
String cmd = String.format("password '%s' %s\n", needed, VpnProfile.openVpnEscape(pw));
managmentCommand(cmd);
} else {
VpnStatus.logError(String.format("Openvpn requires Authentication type '%s' but no password/key information available", needed));
}
}
private void proccessPWFailed(String needed, String args) {
VpnStatus.updateStateString("AUTH_FAILED", needed + args, R.string.state_auth_failed, ConnectionStatus.LEVEL_AUTH_FAILED);
}
private static boolean stopOpenVPN() {
boolean sendCMD=false;
for (OpenVpnManagementThread mt: active){
mt.managmentCommand("signal SIGINT\n");
sendCMD=true;
try {
if(mt.mSocket !=null)
mt.mSocket.close();
} catch (IOException e) {
// Ignore close error on already closed socket
}
}
return sendCMD;
}
public void signalusr1() {
mReleaseHold=false;
if(!mWaitingForRelease)
managmentCommand("signal SIGUSR1\n");
else
// If signalusr1 is called update the state string
// if there is another for stopping
VpnStatus.updateStatePause(lastPauseReason);
}
public void reconnect() {
signalusr1();
releaseHold();
}
private void processSignCommand(String b64data) {
String signed_string = mProfile.getSignedData(b64data);
if(signed_string==null) {
managmentCommand("rsa-sig\n");
managmentCommand("\nEND\n");
stopOpenVPN();
return;
}
managmentCommand("rsa-sig\n");
managmentCommand(signed_string);
managmentCommand("\nEND\n");
}
@Override
public void pause (pauseReason reason) {
lastPauseReason = reason;
signalusr1();
}
@Override
public void resume() {
releaseHold();
/* Reset the reason why we are disconnected */
lastPauseReason = pauseReason.noNetwork;
}
@Override
public boolean stopVPN() {
return stopOpenVPN();
}
}
| Java |
package de.blinkt.openvpn.core;
public interface OpenVPNManagement {
enum pauseReason {
noNetwork,
userPause,
screenOff
}
int mBytecountInterval =2;
void reconnect();
void pause(pauseReason reason);
void resume();
boolean stopVPN();
}
| Java |
package de.blinkt.openvpn.core;/*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will Google be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, as long as the origin is not misrepresented.
*/
import android.os.Build;
import android.os.Process;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.SecureRandomSpi;
import java.security.Security;
/**
* Fixes for the output of the default PRNG having low entropy.
*
* The fixes need to be applied via {@link #apply()} before any use of Java
* Cryptography Architecture primitives. A good place to invoke them is in the
* application's {@code onCreate}.
*/
public final class PRNGFixes {
private static final int VERSION_CODE_JELLY_BEAN = 16;
private static final int VERSION_CODE_JELLY_BEAN_MR2 = 18;
private static final byte[] BUILD_FINGERPRINT_AND_DEVICE_SERIAL =
getBuildFingerprintAndDeviceSerial();
/** Hidden constructor to prevent instantiation. */
private PRNGFixes() {}
/**
* Applies all fixes.
*
* @throws SecurityException if a fix is needed but could not be applied.
*/
public static void apply() {
applyOpenSSLFix();
installLinuxPRNGSecureRandom();
}
/**
* Applies the fix for OpenSSL PRNG having low entropy. Does nothing if the
* fix is not needed.
*
* @throws SecurityException if the fix is needed but could not be applied.
*/
private static void applyOpenSSLFix() throws SecurityException {
if ((Build.VERSION.SDK_INT < VERSION_CODE_JELLY_BEAN)
|| (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2)) {
// No need to apply the fix
return;
}
try {
// Mix in the device- and invocation-specific seed.
Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto")
.getMethod("RAND_seed", byte[].class)
.invoke(null, generateSeed());
// Mix output of Linux PRNG into OpenSSL's PRNG
int bytesRead = (Integer) Class.forName(
"org.apache.harmony.xnet.provider.jsse.NativeCrypto")
.getMethod("RAND_load_file", String.class, long.class)
.invoke(null, "/dev/urandom", 1024);
if (bytesRead != 1024) {
throw new IOException(
"Unexpected number of bytes read from Linux PRNG: "
+ bytesRead);
}
} catch (Exception e) {
throw new SecurityException("Failed to seed OpenSSL PRNG", e);
}
}
/**
* Installs a Linux PRNG-backed {@code SecureRandom} implementation as the
* default. Does nothing if the implementation is already the default or if
* there is not need to install the implementation.
*
* @throws SecurityException if the fix is needed but could not be applied.
*/
private static void installLinuxPRNGSecureRandom()
throws SecurityException {
if (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2) {
// No need to apply the fix
return;
}
// Install a Linux PRNG-based SecureRandom implementation as the
// default, if not yet installed.
Provider[] secureRandomProviders =
Security.getProviders("SecureRandom.SHA1PRNG");
if ((secureRandomProviders == null)
|| (secureRandomProviders.length < 1)
|| (!LinuxPRNGSecureRandomProvider.class.equals(
secureRandomProviders[0].getClass()))) {
Security.insertProviderAt(new LinuxPRNGSecureRandomProvider(), 1);
}
// Assert that new SecureRandom() and
// SecureRandom.getInstance("SHA1PRNG") return a SecureRandom backed
// by the Linux PRNG-based SecureRandom implementation.
SecureRandom rng1 = new SecureRandom();
if (!LinuxPRNGSecureRandomProvider.class.equals(
rng1.getProvider().getClass())) {
throw new SecurityException(
"new SecureRandom() backed by wrong Provider: "
+ rng1.getProvider().getClass());
}
SecureRandom rng2;
try {
rng2 = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
throw new SecurityException("SHA1PRNG not available", e);
}
if (!LinuxPRNGSecureRandomProvider.class.equals(
rng2.getProvider().getClass())) {
throw new SecurityException(
"SecureRandom.getInstance(\"SHA1PRNG\") backed by wrong"
+ " Provider: " + rng2.getProvider().getClass());
}
}
/**
* {@code Provider} of {@code SecureRandom} engines which pass through
* all requests to the Linux PRNG.
*/
private static class LinuxPRNGSecureRandomProvider extends Provider {
public LinuxPRNGSecureRandomProvider() {
super("LinuxPRNG",
1.0,
"A Linux-specific random number provider that uses"
+ " /dev/urandom");
// Although /dev/urandom is not a SHA-1 PRNG, some apps
// explicitly request a SHA1PRNG SecureRandom and we thus need to
// prevent them from getting the default implementation whose output
// may have low entropy.
put("SecureRandom.SHA1PRNG", LinuxPRNGSecureRandom.class.getName());
put("SecureRandom.SHA1PRNG ImplementedIn", "Software");
}
}
/**
* {@link SecureRandomSpi} which passes all requests to the Linux PRNG
* ({@code /dev/urandom}).
*/
public static class LinuxPRNGSecureRandom extends SecureRandomSpi {
/*
* IMPLEMENTATION NOTE: Requests to generate bytes and to mix in a seed
* are passed through to the Linux PRNG (/dev/urandom). Instances of
* this class seed themselves by mixing in the current time, PID, UID,
* build fingerprint, and hardware serial number (where available) into
* Linux PRNG.
*
* Concurrency: Read requests to the underlying Linux PRNG are
* serialized (on sLock) to ensure that multiple threads do not get
* duplicated PRNG output.
*/
private static final File URANDOM_FILE = new File("/dev/urandom");
private static final Object sLock = new Object();
/**
* Input stream for reading from Linux PRNG or {@code null} if not yet
* opened.
*
* @GuardedBy("sLock")
*/
private static DataInputStream sUrandomIn;
/**
* Output stream for writing to Linux PRNG or {@code null} if not yet
* opened.
*
* @GuardedBy("sLock")
*/
private static OutputStream sUrandomOut;
/**
* Whether this engine instance has been seeded. This is needed because
* each instance needs to seed itself if the client does not explicitly
* seed it.
*/
private boolean mSeeded;
@Override
protected void engineSetSeed(byte[] bytes) {
try {
OutputStream out;
synchronized (sLock) {
out = getUrandomOutputStream();
}
out.write(bytes);
out.flush();
} catch (IOException e) {
// On a small fraction of devices /dev/urandom is not writable.
// Log and ignore.
Log.w(PRNGFixes.class.getSimpleName(),
"Failed to mix seed into " + URANDOM_FILE);
} finally {
mSeeded = true;
}
}
@Override
protected void engineNextBytes(byte[] bytes) {
if (!mSeeded) {
// Mix in the device- and invocation-specific seed.
engineSetSeed(generateSeed());
}
try {
DataInputStream in;
synchronized (sLock) {
in = getUrandomInputStream();
}
synchronized (in) {
in.readFully(bytes);
}
} catch (IOException e) {
throw new SecurityException(
"Failed to read from " + URANDOM_FILE, e);
}
}
@Override
protected byte[] engineGenerateSeed(int size) {
byte[] seed = new byte[size];
engineNextBytes(seed);
return seed;
}
private DataInputStream getUrandomInputStream() {
synchronized (sLock) {
if (sUrandomIn == null) {
// NOTE: Consider inserting a BufferedInputStream between
// DataInputStream and FileInputStream if you need higher
// PRNG output performance and can live with future PRNG
// output being pulled into this process prematurely.
try {
sUrandomIn = new DataInputStream(
new FileInputStream(URANDOM_FILE));
} catch (IOException e) {
throw new SecurityException("Failed to open "
+ URANDOM_FILE + " for reading", e);
}
}
return sUrandomIn;
}
}
private OutputStream getUrandomOutputStream() throws IOException {
synchronized (sLock) {
if (sUrandomOut == null) {
sUrandomOut = new FileOutputStream(URANDOM_FILE);
}
return sUrandomOut;
}
}
}
/**
* Generates a device- and invocation-specific seed to be mixed into the
* Linux PRNG.
*/
private static byte[] generateSeed() {
try {
ByteArrayOutputStream seedBuffer = new ByteArrayOutputStream();
DataOutputStream seedBufferOut =
new DataOutputStream(seedBuffer);
seedBufferOut.writeLong(System.currentTimeMillis());
seedBufferOut.writeLong(System.nanoTime());
seedBufferOut.writeInt(Process.myPid());
seedBufferOut.writeInt(Process.myUid());
seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL);
seedBufferOut.close();
return seedBuffer.toByteArray();
} catch (IOException e) {
throw new SecurityException("Failed to generate seed", e);
}
}
/**
* Gets the hardware serial number of this device.
*
* @return serial number or {@code null} if not available.
*/
private static String getDeviceSerialNumber() {
// We're using the Reflection API because Build.SERIAL is only available
// since API Level 9 (Gingerbread, Android 2.3).
try {
return (String) Build.class.getField("SERIAL").get(null);
} catch (Exception ignored) {
return null;
}
}
private static byte[] getBuildFingerprintAndDeviceSerial() {
StringBuilder result = new StringBuilder();
String fingerprint = Build.FINGERPRINT;
if (fingerprint != null) {
result.append(fingerprint);
}
String serial = getDeviceSerialNumber();
if (serial != null) {
result.append(serial);
}
try {
return result.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 encoding not supported");
}
}
} | Java |
package de.blinkt.openvpn.core;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
public class ProxyDetection {
static SocketAddress detectProxy(VpnProfile vp) {
// Construct a new url with https as protocol
try {
URL url = new URL(String.format("https://%s:%s",vp.mServerName,vp.mServerPort));
Proxy proxy = getFirstProxy(url);
if(proxy==null)
return null;
SocketAddress addr = proxy.address();
if (addr instanceof InetSocketAddress) {
return addr;
}
} catch (MalformedURLException e) {
VpnStatus.logError(R.string.getproxy_error, e.getLocalizedMessage());
} catch (URISyntaxException e) {
VpnStatus.logError(R.string.getproxy_error, e.getLocalizedMessage());
}
return null;
}
static Proxy getFirstProxy(URL url) throws URISyntaxException {
System.setProperty("java.net.useSystemProxies", "true");
List<Proxy> proxylist = ProxySelector.getDefault().select(url.toURI());
if (proxylist != null) {
for (Proxy proxy: proxylist) {
SocketAddress addr = proxy.address();
if (addr != null) {
return proxy;
}
}
}
return null;
}
} | Java |
package de.blinkt.openvpn.core;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import de.blinkt.openvpn.R;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.FormatFlagsConversionMismatchException;
import java.util.LinkedList;
import java.util.Locale;
import java.util.UnknownFormatConversionException;
import java.util.Vector;
public class VpnStatus {
public static LinkedList<LogItem> logbuffer;
private static Vector<LogListener> logListener;
private static Vector<StateListener> stateListener;
private static Vector<ByteCountListener> byteCountListener;
private static String mLaststatemsg="";
private static String mLaststate = "NOPROCESS";
private static int mLastStateresid=R.string.state_noprocess;
private static long mlastByteCount[]={0,0,0,0};
public static void logException(LogLevel ll, String context, Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
LogItem li;
if (context !=null) {
li = new LogItem(ll, R.string.unhandled_exception_context, e.getMessage(), sw.toString(), context);
} else {
li = new LogItem(ll, R.string.unhandled_exception, e.getMessage(), sw.toString());
}
newLogItem(li);
}
public static void logException(Exception e) {
logException(LogLevel.ERROR, null, e);
}
public static void logException(String context, Exception e) {
logException(LogLevel.ERROR, context, e);
}
private static final int MAXLOGENTRIES = 1000;
public static final String MANAGMENT_PREFIX = "M:";
public enum ConnectionStatus {
LEVEL_CONNECTED,
LEVEL_VPNPAUSED,
LEVEL_CONNECTING_SERVER_REPLIED,
LEVEL_CONNECTING_NO_SERVER_REPLY_YET,
LEVEL_NONETWORK,
LEVEL_NOTCONNECTED,
LEVEL_AUTH_FAILED,
LEVEL_WAITING_FOR_USER_INPUT,
UNKNOWN_LEVEL
}
public enum LogLevel {
INFO(2),
ERROR(-2),
WARNING(1),
VERBOSE(3),
DEBUG(4);
protected int mValue;
LogLevel(int value) {
mValue = value;
}
public int getInt() {
return mValue;
}
public static LogLevel getEnumByValue(int value) {
switch (value) {
case 1: return INFO;
case 2: return ERROR;
case 3: return WARNING;
case 4: return DEBUG;
default: return null;
}
}
}
// keytool -printcert -jarfile de.blinkt.openvpn_85.apk
public static final byte[] officalkey = {-58, -42, -44, -106, 90, -88, -87, -88, -52, -124, 84, 117, 66, 79, -112, -111, -46, 86, -37, 109};
public static final byte[] officaldebugkey = {-99, -69, 45, 71, 114, -116, 82, 66, -99, -122, 50, -70, -56, -111, 98, -35, -65, 105, 82, 43};
public static final byte[] amazonkey = {-116, -115, -118, -89, -116, -112, 120, 55, 79, -8, -119, -23, 106, -114, -85, -56, -4, 105, 26, -57};
public static final byte[] fdroidkey = {-92, 111, -42, -46, 123, -96, -60, 79, -27, -31, 49, 103, 11, -54, -68, -27, 17, 2, 121, 104};
private static ConnectionStatus mLastLevel=ConnectionStatus.LEVEL_NOTCONNECTED;
static {
logbuffer = new LinkedList<LogItem>();
logListener = new Vector<VpnStatus.LogListener>();
stateListener = new Vector<VpnStatus.StateListener>();
byteCountListener = new Vector<VpnStatus.ByteCountListener>();
logInformation();
}
public static class LogItem implements Parcelable {
private Object [] mArgs = null;
private String mMessage = null;
private int mRessourceId;
// Default log priority
LogLevel mLevel = LogLevel.INFO;
private long logtime = System.currentTimeMillis();
private int mVerbosityLevel = -1;
private LogItem(int ressourceId, Object[] args) {
mRessourceId = ressourceId;
mArgs = args;
}
public LogItem(LogLevel level, int verblevel, String message) {
mMessage=message;
mLevel = level;
mVerbosityLevel = verblevel;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeArray(mArgs);
dest.writeString(mMessage);
dest.writeInt(mRessourceId);
dest.writeInt(mLevel.getInt());
dest.writeInt(mVerbosityLevel);
dest.writeLong(logtime);
}
public LogItem(Parcel in) {
mArgs = in.readArray(Object.class.getClassLoader());
mMessage = in.readString();
mRessourceId = in.readInt();
mLevel = LogLevel.getEnumByValue(in.readInt());
mVerbosityLevel = in.readInt();
logtime = in.readLong();
}
public static final Parcelable.Creator<LogItem> CREATOR
= new Parcelable.Creator<LogItem>() {
public LogItem createFromParcel(Parcel in) {
return new LogItem(in);
}
public LogItem[] newArray(int size) {
return new LogItem[size];
}
};
public LogItem(LogLevel loglevel,int ressourceId, Object... args) {
mRessourceId = ressourceId;
mArgs =args;
mLevel = loglevel;
}
public LogItem(LogLevel loglevel, String msg) {
mLevel = loglevel;
mMessage = msg;
}
public LogItem(LogLevel loglevel, int ressourceId) {
mRessourceId =ressourceId;
mLevel = loglevel;
}
public String getString(Context c) {
try {
if(mMessage !=null) {
return mMessage;
} else {
if(c!=null) {
if(mRessourceId==R.string.mobile_info)
return getMobileInfoString(c);
if(mArgs == null)
return c.getString(mRessourceId);
else
return c.getString(mRessourceId,mArgs);
} else {
String str = String.format(Locale.ENGLISH,"Log (no context) resid %d", mRessourceId);
if(mArgs !=null)
for(Object o:mArgs)
str += "|" + o.toString();
return str;
}
}
} catch (UnknownFormatConversionException e) {
if (c != null)
throw new UnknownFormatConversionException(e.getLocalizedMessage() + getString(null));
else
throw e;
} catch (java.util.FormatFlagsConversionMismatchException e) {
if (c != null)
throw new FormatFlagsConversionMismatchException(e.getLocalizedMessage() + getString(null),e.getConversion());
else
throw e;
}
}
public LogLevel getLogLevel()
{
return mLevel;
}
// The lint is wrong here
@SuppressLint("StringFormatMatches")
private String getMobileInfoString(Context c) {
c.getPackageManager();
String apksign="error getting package signature";
String version="error getting version";
try {
Signature raw = c.getPackageManager().getPackageInfo(c.getPackageName(), PackageManager.GET_SIGNATURES).signatures[0];
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(raw.toByteArray()));
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] der = cert.getEncoded();
md.update(der);
byte[] digest = md.digest();
if (Arrays.equals(digest, officalkey))
apksign = c.getString(R.string.official_build);
else if (Arrays.equals(digest, officaldebugkey))
apksign = c.getString(R.string.debug_build);
else if (Arrays.equals(digest, amazonkey))
apksign = "amazon version";
else if (Arrays.equals(digest, fdroidkey))
apksign = "F-Droid built and signed version";
else
apksign = c.getString(R.string.built_by,cert.getSubjectX500Principal().getName());
PackageInfo packageinfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
version = packageinfo.versionName;
} catch (NameNotFoundException e) {
} catch (CertificateException e) {
} catch (NoSuchAlgorithmException e) {
}
Object[] argsext = Arrays.copyOf(mArgs, mArgs.length+2);
argsext[argsext.length-1]=apksign;
argsext[argsext.length-2]=version;
return c.getString(R.string.mobile_info_extended, argsext);
}
public long getLogtime() {
return logtime;
}
public int getVerbosityLevel() {
if (mVerbosityLevel==-1) {
// Hack:
// For message not from OpenVPN, report the status level as log level
return mLevel.getInt();
}
return mVerbosityLevel;
}
}
public interface LogListener {
void newLog(LogItem logItem);
}
public interface StateListener {
void updateState(String state, String logmessage, int localizedResId, ConnectionStatus level);
}
public interface ByteCountListener {
void updateByteCount(long in, long out, long diffIn, long diffOut);
}
public synchronized static void logMessage(LogLevel level,String prefix, String message)
{
newLogItem(new LogItem(level, prefix + message));
}
public synchronized static void clearLog() {
logbuffer.clear();
logInformation();
}
private static void logInformation() {
logInfo(R.string.mobile_info,Build.MODEL, Build.BOARD,Build.BRAND,Build.VERSION.SDK_INT);
}
public synchronized static void addLogListener(LogListener ll){
logListener.add(ll);
}
public synchronized static void removeLogListener(LogListener ll) {
logListener.remove(ll);
}
public synchronized static void addByteCountListener(ByteCountListener bcl) {
bcl.updateByteCount(mlastByteCount[0], mlastByteCount[1], mlastByteCount[2], mlastByteCount[3]);
byteCountListener.add(bcl);
}
public synchronized static void removeByteCountListener(ByteCountListener bcl) {
byteCountListener.remove(bcl);
}
public synchronized static void addStateListener(StateListener sl){
if(!stateListener.contains(sl)){
stateListener.add(sl);
if(mLaststate!=null)
sl.updateState(mLaststate, mLaststatemsg, mLastStateresid, mLastLevel);
}
}
private static int getLocalizedState(String state){
if (state.equals("CONNECTING"))
return R.string.state_connecting;
else if (state.equals("WAIT"))
return R.string.state_wait;
else if (state.equals("AUTH"))
return R.string.state_auth;
else if (state.equals("GET_CONFIG"))
return R.string.state_get_config;
else if (state.equals("ASSIGN_IP"))
return R.string.state_assign_ip;
else if (state.equals("ADD_ROUTES"))
return R.string.state_add_routes;
else if (state.equals("CONNECTED"))
return R.string.state_connected;
else if (state.equals("DISCONNECTED"))
return R.string.state_disconnected;
else if (state.equals("RECONNECTING"))
return R.string.state_reconnecting;
else if (state.equals("EXITING"))
return R.string.state_exiting;
else if (state.equals("RESOLVE"))
return R.string.state_resolve;
else if (state.equals("TCP_CONNECT"))
return R.string.state_tcp_connect;
else
return R.string.unknown_state;
}
public static void updateStatePause(OpenVPNManagement.pauseReason pauseReason) {
switch (pauseReason) {
case noNetwork:
VpnStatus.updateStateString("NONETWORK", "", R.string.state_nonetwork, ConnectionStatus.LEVEL_NONETWORK);
break;
case screenOff:
VpnStatus.updateStateString("SCREENOFF", "", R.string.state_screenoff, ConnectionStatus.LEVEL_VPNPAUSED);
break;
case userPause:
VpnStatus.updateStateString("USERPAUSE", "", R.string.state_userpause, ConnectionStatus.LEVEL_VPNPAUSED);
break;
}
}
private static ConnectionStatus getLevel(String state){
String[] noreplyet = {"CONNECTING","WAIT", "RECONNECTING", "RESOLVE", "TCP_CONNECT"};
String[] reply = {"AUTH","GET_CONFIG","ASSIGN_IP","ADD_ROUTES"};
String[] connected = {"CONNECTED"};
String[] notconnected = {"DISCONNECTED", "EXITING"};
for(String x:noreplyet)
if(state.equals(x))
return ConnectionStatus.LEVEL_CONNECTING_NO_SERVER_REPLY_YET;
for(String x:reply)
if(state.equals(x))
return ConnectionStatus.LEVEL_CONNECTING_SERVER_REPLIED;
for(String x:connected)
if(state.equals(x))
return ConnectionStatus.LEVEL_CONNECTED;
for(String x:notconnected)
if(state.equals(x))
return ConnectionStatus.LEVEL_NOTCONNECTED;
return ConnectionStatus.UNKNOWN_LEVEL;
}
public synchronized static void removeStateListener(StateListener sl) {
stateListener.remove(sl);
}
synchronized public static LogItem[] getlogbuffer() {
// The stoned way of java to return an array from a vector
// brought to you by eclipse auto complete
return logbuffer.toArray(new LogItem[logbuffer.size()]);
}
public static void updateStateString (String state, String msg) {
int rid = getLocalizedState(state);
ConnectionStatus level = getLevel(state);
updateStateString(state, msg, rid, level);
}
public synchronized static void updateStateString(String state, String msg, int resid, ConnectionStatus level) {
// Workound for OpenVPN doing AUTH and wait and being connected
// Simply ignore these state
if (mLastLevel == ConnectionStatus.LEVEL_CONNECTED &&
(state.equals("WAIT") || state.equals("AUTH")))
{
newLogItem(new LogItem((LogLevel.DEBUG), String.format("Ignoring OpenVPN Status in CONNECTED state (%s->%s): %s",state,level.toString(),msg)));
return;
}
mLaststate= state;
mLaststatemsg = msg;
mLastStateresid = resid;
mLastLevel = level;
for (StateListener sl : stateListener) {
sl.updateState(state,msg,resid,level);
}
//newLogItem(new LogItem((LogLevel.DEBUG), String.format("New OpenVPN Status (%s->%s): %s",state,level.toString(),msg)));
}
public static void logInfo(String message) {
newLogItem(new LogItem(LogLevel.INFO, message));
}
public static void logInfo(int resourceId, Object... args) {
newLogItem(new LogItem(LogLevel.INFO, resourceId, args));
}
public static void logDebug(int resourceId, Object... args) {
newLogItem(new LogItem(LogLevel.DEBUG, resourceId, args));
}
private synchronized static void newLogItem(LogItem logItem) {
logbuffer.addLast(logItem);
if(logbuffer.size()>MAXLOGENTRIES)
logbuffer.removeFirst();
for (LogListener ll : logListener) {
ll.newLog(logItem);
}
}
public static void logError(String msg) {
newLogItem(new LogItem(LogLevel.ERROR, msg));
}
public static void logWarning(int resourceId, Object... args) {
newLogItem(new LogItem(LogLevel.WARNING, resourceId, args));
}
public static void logWarning(String msg) {
newLogItem(new LogItem(LogLevel.WARNING, msg));
}
public static void logError(int resourceId) {
newLogItem(new LogItem(LogLevel.ERROR, resourceId));
}
public static void logError(int resourceId, Object... args) {
newLogItem(new LogItem(LogLevel.ERROR, resourceId, args));
}
public static void logMessageOpenVPN(LogLevel level, int ovpnlevel, String message) {
newLogItem(new LogItem(level, ovpnlevel, message));
}
public static synchronized void updateByteCount(long in, long out) {
long lastIn = mlastByteCount[0];
long lastOut = mlastByteCount[1];
long diffIn = mlastByteCount[2] = in - lastIn;
long diffOut = mlastByteCount[3] = out - lastOut;
mlastByteCount = new long[] {in,out,diffIn,diffOut};
for(ByteCountListener bcl:byteCountListener){
bcl.updateByteCount(in, out, diffIn,diffOut);
}
}
}
| Java |
package de.blinkt.openvpn.core;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import de.blinkt.openvpn.VpnProfile;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
public class ProfileManager {
private static final String PREFS_NAME = "VPNList";
private static final String ONBOOTPROFILE = "onBootProfile";
private static ProfileManager instance;
private static VpnProfile mLastConnectedVpn=null;
private HashMap<String,VpnProfile> profiles=new HashMap<String, VpnProfile>();
private static VpnProfile tmpprofile=null;
private static VpnProfile get(String key) {
if (tmpprofile!=null && tmpprofile.getUUIDString().equals(key))
return tmpprofile;
if(instance==null)
return null;
return instance.profiles.get(key);
}
private ProfileManager() { }
private static void checkInstance(Context context) {
if(instance == null) {
instance = new ProfileManager();
instance.loadVPNList(context);
}
}
synchronized public static ProfileManager getInstance(Context context) {
checkInstance(context);
return instance;
}
public static void setConntectedVpnProfileDisconnected(Context c) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
Editor prefsedit = prefs.edit();
prefsedit.putString(ONBOOTPROFILE, null);
prefsedit.apply();
}
public static void setConnectedVpnProfile(Context c, VpnProfile connectedrofile) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
Editor prefsedit = prefs.edit();
prefsedit.putString(ONBOOTPROFILE, connectedrofile.getUUIDString());
prefsedit.apply();
mLastConnectedVpn=connectedrofile;
}
public static VpnProfile getOnBootProfile(Context c) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
boolean useStartOnBoot = prefs.getBoolean("restartvpnonboot", false);
String mBootProfileUUID = prefs.getString(ONBOOTPROFILE,null);
if(useStartOnBoot && mBootProfileUUID!=null)
return get(c, mBootProfileUUID);
else
return null;
}
public Collection<VpnProfile> getProfiles() {
return profiles.values();
}
public VpnProfile getProfileByName(String name) {
for (VpnProfile vpnp : profiles.values()) {
if(vpnp.getName().equals(name)) {
return vpnp;
}
}
return null;
}
public void saveProfileList(Context context) {
SharedPreferences sharedprefs = context.getSharedPreferences(PREFS_NAME,Activity.MODE_PRIVATE);
Editor editor = sharedprefs.edit();
editor.putStringSet("vpnlist", profiles.keySet());
// For reasing I do not understand at all
// Android saves my prefs file only one time
// if I remove the debug code below :(
int counter = sharedprefs.getInt("counter", 0);
editor.putInt("counter", counter+1);
editor.apply();
}
public void addProfile(VpnProfile profile) {
profiles.put(profile.getUUID().toString(),profile);
}
public static void setTemporaryProfile(VpnProfile tmp) {
ProfileManager.tmpprofile = tmp;
}
public void saveProfile(Context context,VpnProfile profile) {
// First let basic settings save its state
ObjectOutputStream vpnfile;
try {
vpnfile = new ObjectOutputStream(context.openFileOutput((profile.getUUID().toString() + ".vp"),Activity.MODE_PRIVATE));
vpnfile.writeObject(profile);
vpnfile.flush();
vpnfile.close();
} catch (FileNotFoundException e) {
VpnStatus.logException("saving VPN profile", e);
throw new RuntimeException(e);
} catch (IOException e) {
VpnStatus.logException("saving VPN profile", e);
throw new RuntimeException(e);
}
}
private void loadVPNList(Context context) {
profiles = new HashMap<String, VpnProfile>();
SharedPreferences listpref = context.getSharedPreferences(PREFS_NAME,Activity.MODE_PRIVATE);
Set<String> vlist = listpref.getStringSet("vpnlist", null);
Exception exp =null;
if(vlist==null){
vlist = new HashSet<String>();
}
for (String vpnentry : vlist) {
try {
ObjectInputStream vpnfile = new ObjectInputStream(context.openFileInput(vpnentry + ".vp"));
VpnProfile vp = ((VpnProfile) vpnfile.readObject());
// Sanity check
if(vp==null || vp.mName==null || vp.getUUID()==null)
continue;
vp.upgradeProfile();
profiles.put(vp.getUUID().toString(), vp);
} catch (StreamCorruptedException e) {
exp=e;
} catch (FileNotFoundException e) {
exp=e;
} catch (IOException e) {
exp=e;
} catch (ClassNotFoundException e) {
exp=e;
}
if(exp!=null) {
VpnStatus.logException("Loading VPN List",exp);
}
}
}
public int getNumberOfProfiles() {
return profiles.size();
}
public void removeProfile(Context context,VpnProfile profile) {
String vpnentry = profile.getUUID().toString();
profiles.remove(vpnentry);
saveProfileList(context);
context.deleteFile(vpnentry + ".vp");
if(mLastConnectedVpn==profile)
mLastConnectedVpn=null;
}
public static VpnProfile get(Context context, String profileUUID) {
checkInstance(context);
return get(profileUUID);
}
public static VpnProfile getLastConnectedVpn() {
return mLastConnectedVpn;
}
}
| Java |
package de.blinkt.openvpn.core;
import android.os.Build;
import android.text.TextUtils;
import java.math.BigInteger;
import java.net.Inet6Address;
import java.util.*;
public class NetworkSpace {
static class ipAddress implements Comparable<ipAddress> {
private BigInteger netAddress;
public int networkMask;
private boolean included;
private boolean isV4;
private BigInteger firstaddr;
private BigInteger lastaddr;
@Override
public int compareTo(ipAddress another) {
int comp = getFirstAddress().compareTo(another.getFirstAddress());
if (comp != 0)
return comp;
// bigger mask means smaller address block
if (networkMask > another.networkMask)
return -1;
else if (another.networkMask == networkMask)
return 0;
else
return 1;
}
public ipAddress(CIDRIP ip, boolean include) {
included = include;
netAddress = BigInteger.valueOf(ip.getInt());
networkMask = ip.len;
isV4 = true;
}
public ipAddress(Inet6Address address, int mask, boolean include) {
networkMask = mask;
included = include;
int s = 128;
netAddress = BigInteger.ZERO;
for (byte b : address.getAddress()) {
s -= 16;
netAddress = netAddress.add(BigInteger.valueOf(b).shiftLeft(s));
}
}
public BigInteger getLastAddress() {
if(lastaddr==null)
lastaddr= getMaskedAddress(true);
return lastaddr;
}
public BigInteger getFirstAddress() {
if (firstaddr==null)
firstaddr=getMaskedAddress(false);
return firstaddr;
}
private BigInteger getMaskedAddress(boolean one) {
BigInteger numAddress = netAddress;
int numBits;
if (isV4) {
numBits = 32 - networkMask;
} else {
numBits = 128 - networkMask;
}
for (int i = 0; i < numBits; i++) {
if (one)
numAddress = numAddress.setBit(i);
else
numAddress = numAddress.clearBit(i);
}
return numAddress;
}
@Override
public String toString() {
//String in = included ? "+" : "-";
if (isV4)
return String.format(Locale.US,"%s/%d", getIPv4Address(), networkMask);
else
return String.format(Locale.US, "%s/%d", getIPv6Address(), networkMask);
}
ipAddress(BigInteger baseAddress, int mask, boolean included, boolean isV4) {
this.netAddress = baseAddress;
this.networkMask = mask;
this.included = included;
this.isV4 = isV4;
}
public ipAddress[] split() {
ipAddress firsthalf = new ipAddress(getFirstAddress(), networkMask + 1, included, isV4);
ipAddress secondhalf = new ipAddress(firsthalf.getLastAddress().add(BigInteger.ONE), networkMask + 1, included, isV4);
assert secondhalf.getLastAddress().equals(getLastAddress());
return new ipAddress[]{firsthalf, secondhalf};
}
String getIPv4Address() {
assert (isV4);
assert (netAddress.longValue() <= 0xffffffffl);
assert (netAddress.longValue() >= 0);
long ip = netAddress.longValue();
return String.format(Locale.US, "%d.%d.%d.%d", (ip >> 24) % 256, (ip >> 16) % 256, (ip >> 8) % 256, ip % 256);
}
String getIPv6Address() {
assert (!isV4);
BigInteger r = netAddress;
if (r.longValue() == 0)
return "::";
Vector<String> parts = new Vector<String>();
while (r.compareTo(BigInteger.ZERO) == 1) {
parts.add(0, String.format(Locale.US, "%x", r.mod(BigInteger.valueOf(256)).longValue()));
r = r.shiftRight(16);
}
return TextUtils.join(":", parts);
}
public boolean containsNet(ipAddress network) {
return getFirstAddress().compareTo(network.getFirstAddress()) != 1 &&
getLastAddress().compareTo(network.getLastAddress()) != -1;
}
}
TreeSet<ipAddress> mIpAddresses = new TreeSet<ipAddress>();
public Collection<ipAddress> getNetworks(boolean included) {
Vector<ipAddress> ips = new Vector<ipAddress>();
for (ipAddress ip : mIpAddresses) {
if (ip.included == included)
ips.add(ip);
}
return ips;
}
public void clear() {
mIpAddresses.clear();
}
void addIP(CIDRIP cidrIp, boolean include) {
mIpAddresses.add(new ipAddress(cidrIp, include));
}
void addIPv6(Inet6Address address, int mask, boolean included) {
mIpAddresses.add(new ipAddress(address, mask, included));
}
TreeSet<ipAddress> generateIPList() {
PriorityQueue<ipAddress> networks = new PriorityQueue<ipAddress>(mIpAddresses);
TreeSet<ipAddress> ipsDone = new TreeSet<ipAddress>();
ipAddress currentNet = networks.poll();
if (currentNet==null)
return ipsDone;
while (currentNet!=null) {
// Check if it and the next of it are compatbile
ipAddress nextNet = networks.poll();
assert currentNet != null;
if (nextNet== null || currentNet.getLastAddress().compareTo(nextNet.getFirstAddress()) == -1) {
// Everything good, no overlapping nothing to do
ipsDone.add(currentNet);
currentNet = nextNet;
} else {
// This network is smaller or equal to the next but has the same base address
if (currentNet.getFirstAddress().equals(nextNet.getFirstAddress()) && currentNet.networkMask >= nextNet.networkMask) {
if (currentNet.included == nextNet.included) {
// Included in the next next and same type
// Simply forget our current network
currentNet=nextNet;
} else {
// our currentnet is included in next and types differ. Need to split the next network
ipAddress[] newNets = nextNet.split();
// First add the second half to keep the order in networks
if (!networks.contains(newNets[1]))
networks.add(newNets[1]);
if (newNets[0].getLastAddress().equals(currentNet.getLastAddress())) {
assert (newNets[0].networkMask == currentNet.networkMask);
// Don't add the lower half that would conflict with currentNet
} else {
if (!networks.contains(newNets[0]))
networks.add(newNets[0]);
}
// Keep currentNet as is
}
} else {
assert (currentNet.networkMask < nextNet.networkMask);
assert (nextNet.getFirstAddress().compareTo(currentNet.getFirstAddress()) == 1);
assert (currentNet.getLastAddress().compareTo(nextNet.getLastAddress()) != -1);
// This network is bigger than the next and last ip of current >= next
if (currentNet.included == nextNet.included) {
// Next network is in included in our network with the same type,
// simply ignore the next and move on
} else {
// We need to split our network
ipAddress[] newNets = currentNet.split();
if (newNets[1].networkMask == nextNet.networkMask) {
assert (newNets[1].getFirstAddress().equals(nextNet.getFirstAddress()));
assert (newNets[1].getLastAddress().equals(currentNet.getLastAddress()));
// Splitted second equal the next network, do not add it
networks.add(nextNet);
} else {
// Add the smaller network first
networks.add(newNets[1]);
networks.add(nextNet);
}
currentNet = newNets[0];
}
}
}
}
return ipsDone;
}
Collection<ipAddress> getPositiveIPList() {
TreeSet<ipAddress> ipsSorted = generateIPList();
Vector<ipAddress> ips = new Vector<ipAddress>();
for (ipAddress ia : ipsSorted) {
if (ia.included)
ips.add(ia);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
// Include postive routes from the original set under < 4.4 since these might overrule the local
// network but only if no smaller negative route exists
for(ipAddress origIp: mIpAddresses){
if (!origIp.included)
continue;
// The netspace exists
if(ipsSorted.contains(origIp))
continue;
boolean skipIp=false;
// If there is any smaller net that is excluded we may not add the positive route back
for (ipAddress calculatedIp: ipsSorted) {
if(!calculatedIp.included && origIp.containsNet(calculatedIp)) {
skipIp=true;
break;
}
}
if (skipIp)
continue;
// It is safe to include the IP
ips.add(origIp);
}
}
return ips;
}
}
| Java |
package de.blinkt.openvpn.core;
import android.app.Application;
/**
* Created by arne on 28.12.13.
*/
public class ICSOpenVPNApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
PRNGFixes.apply();
}
}
| Java |
package de.blinkt.openvpn.core;
import de.blinkt.openvpn.VpnProfile;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Vector;
//! Openvpn Config FIle Parser, probably not 100% accurate but close enough
// And remember, this is valid :)
// --<foo>
// bar
// </foo>
public class ConfigParser {
public static final String CONVERTED_PROFILE = "converted Profile";
private HashMap<String, Vector<Vector<String>>> options = new HashMap<String, Vector<Vector<String>>>();
private HashMap<String, Vector<String>> meta = new HashMap<String, Vector<String>>();
private boolean extraRemotesAsCustom=false;
public void parseConfig(Reader reader) throws IOException, ConfigParseError {
BufferedReader br =new BufferedReader(reader);
while (true){
String line = br.readLine();
if(line==null)
break;
// Check for OpenVPN Access Server Meta information
if (line.startsWith("# OVPN_ACCESS_SERVER_")) {
Vector<String> metaarg = parsemeta(line);
meta.put(metaarg.get(0),metaarg);
continue;
}
Vector<String> args = parseline(line);
if(args.size() ==0)
continue;
if(args.get(0).startsWith("--"))
args.set(0, args.get(0).substring(2));
checkinlinefile(args,br);
String optionname = args.get(0);
if(!options.containsKey(optionname)) {
options.put(optionname, new Vector<Vector<String>>());
}
options.get(optionname).add(args);
}
}
private Vector<String> parsemeta(String line) {
String meta = line.split("#\\sOVPN_ACCESS_SERVER_", 2)[1];
String[] parts = meta.split("=",2);
Vector<String> rval = new Vector<String>();
Collections.addAll(rval, parts);
return rval;
}
private void checkinlinefile(Vector<String> args, BufferedReader br) throws IOException, ConfigParseError {
String arg0 = args.get(0).trim();
// CHeck for <foo>
if(arg0.startsWith("<") && arg0.endsWith(">")) {
String argname = arg0.substring(1, arg0.length()-1);
String inlinefile = VpnProfile.INLINE_TAG;
String endtag = String.format("</%s>",argname);
do {
String line = br.readLine();
if(line==null){
throw new ConfigParseError(String.format("No endtag </%s> for starttag <%s> found",argname,argname));
}
if(line.trim().equals(endtag))
break;
else {
inlinefile+=line;
inlinefile+= "\n";
}
} while(true);
args.clear();
args.add(argname);
args.add(inlinefile);
}
}
enum linestate {
initial,
readin_single_quote
, reading_quoted, reading_unquoted, done}
private boolean space(char c) {
// I really hope nobody is using zero bytes inside his/her config file
// to sperate parameter but here we go:
return Character.isWhitespace(c) || c == '\0';
}
public class ConfigParseError extends Exception {
private static final long serialVersionUID = -60L;
public ConfigParseError(String msg) {
super(msg);
}
}
// adapted openvpn's parse function to java
private Vector<String> parseline(String line) throws ConfigParseError {
Vector<String> parameters = new Vector<String>();
if (line.length()==0)
return parameters;
linestate state = linestate.initial;
boolean backslash = false;
char out=0;
int pos=0;
String currentarg="";
do {
// Emulate the c parsing ...
char in;
if(pos < line.length())
in = line.charAt(pos);
else
in = '\0';
if (!backslash && in == '\\' && state != linestate.readin_single_quote)
{
backslash = true;
}
else
{
if (state == linestate.initial)
{
if (!space (in))
{
if (in == ';' || in == '#') /* comment */
break;
if (!backslash && in == '\"')
state = linestate.reading_quoted;
else if (!backslash && in == '\'')
state = linestate.readin_single_quote;
else
{
out = in;
state = linestate.reading_unquoted;
}
}
}
else if (state == linestate.reading_unquoted)
{
if (!backslash && space (in))
state = linestate.done;
else
out = in;
}
else if (state == linestate.reading_quoted)
{
if (!backslash && in == '\"')
state = linestate.done;
else
out = in;
}
else if (state == linestate.readin_single_quote)
{
if (in == '\'')
state = linestate.done;
else
out = in;
}
if (state == linestate.done)
{
/* ASSERT (parm_len > 0); */
state = linestate.initial;
parameters.add(currentarg);
currentarg = "";
out =0;
}
if (backslash && out!=0)
{
if (!(out == '\\' || out == '\"' || space (out)))
{
throw new ConfigParseError("Options warning: Bad backslash ('\\') usage");
}
}
backslash = false;
}
/* store parameter character */
if (out!=0)
{
currentarg+=out;
}
} while (pos++ < line.length());
return parameters;
}
final String[] unsupportedOptions = { "config",
"connection",
"proto-force",
"remote-random",
"tls-server"
};
// Ignore all scripts
// in most cases these won't work and user who wish to execute scripts will
// figure out themselves
final String[] ignoreOptions = { "tls-client",
"askpass",
"auth-nocache",
"up",
"down",
"route-up",
"ipchange",
"route-up",
"route-pre-down",
"auth-user-pass-verify",
"dhcp-release",
"dhcp-renew",
"dh",
"group",
"ip-win32",
"management-hold",
"management",
"management-client",
"management-query-remote",
"management-query-passwords",
"management-query-proxy",
"management-external-key",
"management-forget-disconnect",
"management-signal",
"management-log-cache",
"management-up-down",
"management-client-user",
"management-client-group",
"pause-exit",
"plugin",
"machine-readable-output",
"persist-key",
"register-dns",
"route-delay",
"route-gateway",
"route-metric",
"route-method",
"status",
"script-security",
"show-net-up",
"suppress-timestamps",
"tmp-dir",
"tun-ipv6",
"topology",
"user",
"win-sys",
};
final String[][] ignoreOptionsWithArg =
{
{"setenv", "IV_GUI_VER"},
{"setenv", "IV_OPENVPN_GUI_VERSION"}
};
final String[] connectionOptions = {
"local",
"remote",
"float",
"port",
// "connect-retry",
"connect-timeout",
"connect-retry-max",
"link-mtu",
"tun-mtu",
"tun-mtu-extra",
"fragment",
"mtu-disc",
"local-port",
"remote-port",
"bind",
"nobind",
"proto",
"http-proxy",
"http-proxy-retry",
"http-proxy-timeout",
"http-proxy-option",
"socks-proxy",
"socks-proxy-retry",
"explicit-exit-notify",
"mssfix"
};
// This method is far too long
@SuppressWarnings("ConstantConditions")
public VpnProfile convertProfile() throws ConfigParseError{
boolean noauthtypeset=true;
VpnProfile np = new VpnProfile(CONVERTED_PROFILE);
// Pull, client, tls-client
np.clearDefaults();
if(options.containsKey("client") || options.containsKey("pull")) {
np.mUsePull=true;
options.remove("pull");
options.remove("client");
}
Vector<String> secret = getOption("secret", 1, 2);
if(secret!=null)
{
np.mAuthenticationType=VpnProfile.TYPE_STATICKEYS;
noauthtypeset=false;
np.mUseTLSAuth=true;
np.mTLSAuthFilename=secret.get(1);
if(secret.size()==3)
np.mTLSAuthDirection=secret.get(2);
}
Vector<Vector<String>> routes = getAllOption("route", 1, 4);
if(routes!=null) {
String routeopt = "";
String routeExcluded = "";
for(Vector<String> route:routes){
String netmask = "255.255.255.255";
String gateway = "vpn_gateway";
if(route.size() >= 3)
netmask = route.get(2);
if (route.size() >= 4)
gateway = route.get(3);
String net = route.get(1);
try {
CIDRIP cidr = new CIDRIP(net, netmask);
if (gateway.equals("net_gateway"))
routeExcluded += cidr.toString() + " ";
else
routeopt+=cidr.toString() + " ";
} catch (ArrayIndexOutOfBoundsException aioob) {
throw new ConfigParseError("Could not parse netmask of route " + netmask);
} catch (NumberFormatException ne) {
throw new ConfigParseError("Could not parse netmask of route " + netmask);
}
}
np.mCustomRoutes=routeopt;
np.mExcludedRoutes=routeExcluded;
}
Vector<Vector<String>> routesV6 = getAllOption("route-ipv6", 1, 4);
if (routesV6!=null) {
String customIPv6Routes = "";
for (Vector<String> route:routesV6){
customIPv6Routes += route.get(1) + " ";
}
np.mCustomRoutesv6 = customIPv6Routes;
}
// Also recognize tls-auth [inline] direction ...
Vector<Vector<String>> tlsauthoptions = getAllOption("tls-auth", 1, 2);
if(tlsauthoptions!=null) {
for(Vector<String> tlsauth:tlsauthoptions) {
if(tlsauth!=null)
{
if(!tlsauth.get(1).equals("[inline]")) {
np.mTLSAuthFilename=tlsauth.get(1);
np.mUseTLSAuth=true;
}
if(tlsauth.size()==3)
np.mTLSAuthDirection=tlsauth.get(2);
}
}
}
Vector<String> direction = getOption("key-direction", 1, 1);
if(direction!=null)
np.mTLSAuthDirection=direction.get(1);
Vector<Vector<String>> defgw = getAllOption("redirect-gateway", 0, 5);
if(defgw != null)
{
np.mUseDefaultRoute=true;
checkRedirectParameters(np, defgw);
}
Vector<Vector<String>> redirectPrivate = getAllOption("redirect-private",0,5);
if (redirectPrivate != null)
{
checkRedirectParameters(np,redirectPrivate);
}
Vector<String> dev =getOption("dev",1,1);
Vector<String> devtype =getOption("dev-type",1,1);
if ((devtype != null && devtype.get(1).equals("tun")) ||
(dev != null && dev.get(1).startsWith("tun")) ||
(devtype == null && dev == null)) {
//everything okay
} else {
throw new ConfigParseError("Sorry. Only tun mode is supported. See the FAQ for more detail");
}
Vector<String> mode =getOption("mode",1,1);
if (mode != null){
if(!mode.get(1).equals("p2p"))
throw new ConfigParseError("Invalid mode for --mode specified, need p2p");
}
Vector<String> port = getOption("port", 1,1);
if(port!=null){
np.mServerPort = port.get(1);
}
Vector<String> rport = getOption("rport", 1,1);
if(port!=null){
np.mServerPort = port.get(1);
}
Vector<String> proto = getOption("proto", 1,1);
if(proto!=null){
np.mUseUdp=isUdpProto(proto.get(1));
}
// Parse remote config
Vector<Vector<String>> remotes = getAllOption("remote",1,3);
if(remotes!=null && remotes.size()>=1 ) {
Vector<String> remote = remotes.get(0);
switch (remote.size()) {
case 4:
np.mUseUdp=isUdpProto(remote.get(3));
case 3:
np.mServerPort = remote.get(2);
case 2:
np.mServerName = remote.get(1);
}
}
Vector<Vector<String>> dhcpoptions = getAllOption("dhcp-option", 2, 2);
if(dhcpoptions!=null) {
for(Vector<String> dhcpoption:dhcpoptions) {
String type=dhcpoption.get(1);
String arg = dhcpoption.get(2);
if(type.equals("DOMAIN")) {
np.mSearchDomain=dhcpoption.get(2);
} else if(type.equals("DNS")) {
np.mOverrideDNS=true;
if(np.mDNS1.equals(VpnProfile.DEFAULT_DNS1))
np.mDNS1=arg;
else
np.mDNS2=arg;
}
}
}
Vector<String> ifconfig = getOption("ifconfig", 2, 2);
if(ifconfig!=null) {
try {
CIDRIP cidr = new CIDRIP(ifconfig.get(1), ifconfig.get(2));
np.mIPv4Address=cidr.toString();
} catch (NumberFormatException nfe) {
throw new ConfigParseError("Could not pase ifconfig IP address: " + nfe.getLocalizedMessage());
}
}
if(getOption("remote-random-hostname", 0, 0)!=null)
np.mUseRandomHostname=true;
if(getOption("float", 0, 0)!=null)
np.mUseFloat=true;
if(getOption("comp-lzo", 0, 1)!=null)
np.mUseLzo=true;
Vector<String> cipher = getOption("cipher", 1, 1);
if(cipher!=null)
np.mCipher= cipher.get(1);
Vector<String> auth = getOption("auth", 1, 1);
if(auth!=null)
np.mAuth = auth.get(1);
Vector<String> ca = getOption("ca",1,1);
if(ca!=null){
np.mCaFilename = ca.get(1);
}
Vector<String> cert = getOption("cert",1,1);
if(cert!=null){
np.mClientCertFilename = cert.get(1);
np.mAuthenticationType = VpnProfile.TYPE_CERTIFICATES;
noauthtypeset=false;
}
Vector<String> key= getOption("key",1,1);
if(key!=null)
np.mClientKeyFilename=key.get(1);
Vector<String> pkcs12 = getOption("pkcs12",1,1);
if(pkcs12!=null) {
np.mPKCS12Filename = pkcs12.get(1);
np.mAuthenticationType = VpnProfile.TYPE_KEYSTORE;
noauthtypeset=false;
}
Vector<String> compatnames = getOption("compat-names",1,2);
Vector<String> nonameremapping = getOption("no-name-remapping",1,1);
Vector<String> tlsremote = getOption("tls-remote",1,1);
if(tlsremote!=null){
np.mRemoteCN = tlsremote.get(1);
np.mCheckRemoteCN=true;
np.mX509AuthType = VpnProfile.X509_VERIFY_TLSREMOTE;
if((compatnames!=null && compatnames.size() > 2) ||
(nonameremapping!=null))
np.mX509AuthType = VpnProfile.X509_VERIFY_TLSREMOTE_COMPAT_NOREMAPPING;
}
Vector<String> verifyx509name = getOption("verify-x509-name",1,2);
if(verifyx509name!=null){
np.mRemoteCN = verifyx509name.get(1);
np.mCheckRemoteCN=true;
if(verifyx509name.size()>2) {
if (verifyx509name.get(2).equals("name"))
np.mX509AuthType=VpnProfile.X509_VERIFY_TLSREMOTE_RDN;
else if (verifyx509name.get(2).equals("name-prefix"))
np.mX509AuthType=VpnProfile.X509_VERIFY_TLSREMOTE_RDN_PREFIX;
else
throw new ConfigParseError("Unknown parameter to x509-verify-name: " + verifyx509name.get(2) );
} else {
np.mX509AuthType = VpnProfile.X509_VERIFY_TLSREMOTE_DN;
}
}
Vector<String> verb = getOption("verb",1,1);
if(verb!=null){
np.mVerb=verb.get(1);
}
if(getOption("nobind", 0, 0) != null)
np.mNobind=true;
if(getOption("persist-tun", 0,0) != null)
np.mPersistTun=true;
Vector<String> connectretry = getOption("connect-retry", 1, 1);
if(connectretry!=null)
np.mConnectRetry =connectretry.get(1);
Vector<String> connectretrymax = getOption("connect-retry-max", 1, 1);
if(connectretrymax!=null)
np.mConnectRetryMax =connectretrymax.get(1);
Vector<Vector<String>> remotetls = getAllOption("remote-cert-tls", 1, 1);
if(remotetls!=null)
if(remotetls.get(0).get(1).equals("server"))
np.mExpectTLSCert=true;
else
options.put("remotetls",remotetls);
Vector<String> authuser = getOption("auth-user-pass",0,1);
if(authuser !=null){
if(noauthtypeset) {
np.mAuthenticationType=VpnProfile.TYPE_USERPASS;
} else if(np.mAuthenticationType==VpnProfile.TYPE_CERTIFICATES) {
np.mAuthenticationType=VpnProfile.TYPE_USERPASS_CERTIFICATES;
} else if(np.mAuthenticationType==VpnProfile.TYPE_KEYSTORE) {
np.mAuthenticationType=VpnProfile.TYPE_USERPASS_KEYSTORE;
}
if(authuser.size()>1) {
// Set option value to password get to get cance to embed later.
np.mUsername=null;
np.mPassword=authuser.get(1);
useEmbbedUserAuth(np,authuser.get(1));
}
}
// Parse OpenVPN Access Server extra
Vector<String> friendlyname = meta.get("FRIENDLY_NAME");
if(friendlyname !=null && friendlyname.size() > 1)
np.mName=friendlyname.get(1);
Vector<String> ocusername = meta.get("USERNAME");
if(ocusername !=null && ocusername.size() > 1)
np.mUsername=ocusername.get(1);
// Check the other options
if(remotes !=null && remotes.size()>1 && extraRemotesAsCustom) {
// first is already added
remotes.remove(0);
np.mCustomConfigOptions += getOptionStrings(remotes);
np.mUseCustomConfig=true;
}
checkIgnoreAndInvalidOptions(np);
fixup(np);
return np;
}
private void checkRedirectParameters(VpnProfile np, Vector<Vector<String>> defgw) {
for (Vector<String> redirect: defgw)
for (int i=1;i<redirect.size();i++){
if (redirect.get(i).equals("block-local"))
np.mAllowLocalLAN=false;
else if (redirect.get(i).equals("unblock-local"))
np.mAllowLocalLAN=true;
}
}
public void useExtraRemotesAsCustom(boolean b) {
this.extraRemotesAsCustom = b;
}
private boolean isUdpProto(String proto) throws ConfigParseError {
boolean isudp;
if(proto.equals("udp") || proto.equals("udp6"))
isudp=true;
else if (proto.equals("tcp-client") ||
proto.equals("tcp") ||
proto.equals("tcp6") ||
proto.endsWith("tcp6-client"))
isudp =false;
else
throw new ConfigParseError("Unsupported option to --proto " + proto);
return isudp;
}
static public void useEmbbedUserAuth(VpnProfile np,String inlinedata)
{
String data = VpnProfile.getEmbeddedContent(inlinedata);
String[] parts = data.split("\n");
if(parts.length >= 2) {
np.mUsername=parts[0];
np.mPassword=parts[1];
}
}
private void checkIgnoreAndInvalidOptions(VpnProfile np) throws ConfigParseError {
for(String option:unsupportedOptions)
if(options.containsKey(option))
throw new ConfigParseError(String.format("Unsupported Option %s encountered in config file. Aborting",option));
for(String option:ignoreOptions)
// removing an item which is not in the map is no error
options.remove(option);
if(options.size()> 0) {
np.mCustomConfigOptions += "# These Options were found in the config file do not map to config settings:\n";
for(Vector<Vector<String>> option:options.values()) {
np.mCustomConfigOptions += getOptionStrings(option);
}
np.mUseCustomConfig=true;
}
}
boolean ignoreThisOption(Vector<String> option) {
for (String[] ignoreOption : ignoreOptionsWithArg) {
if (option.size() < ignoreOption.length)
continue;
boolean ignore = true;
for (int i = 0; i < ignoreOption.length; i++) {
if (!ignoreOption[i].equals(option.get(i)))
ignore = false;
}
if (ignore)
return true;
}
return false;
}
private String getOptionStrings(Vector<Vector<String>> option) {
String custom = "";
for (Vector<String> optionsline : option) {
if (!ignoreThisOption(optionsline)) {
for (String arg : optionsline)
custom += VpnProfile.openVpnEscape(arg) + " ";
custom += "\n";
}
}
return custom;
}
private void fixup(VpnProfile np) {
if(np.mRemoteCN.equals(np.mServerName)) {
np.mRemoteCN="";
}
}
private Vector<String> getOption(String option, int minarg, int maxarg) throws ConfigParseError {
Vector<Vector<String>> alloptions = getAllOption(option, minarg, maxarg);
if(alloptions==null)
return null;
else
return alloptions.lastElement();
}
private Vector<Vector<String>> getAllOption(String option, int minarg, int maxarg) throws ConfigParseError {
Vector<Vector<String>> args = options.get(option);
if(args==null)
return null;
for(Vector<String> optionline:args)
if(optionline.size()< (minarg+1) || optionline.size() > maxarg+1) {
String err = String.format(Locale.getDefault(),"Option %s has %d parameters, expected between %d and %d",
option,optionline.size()-1,minarg,maxarg );
throw new ConfigParseError(err);
}
options.remove(option);
return args;
}
}
| Java |
package de.blinkt.openvpn.fragments;
import java.io.File;
import java.util.ArrayList;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.core.VpnStatus;
public class SendDumpFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_senddump, container, false);
v.findViewById(R.id.senddump).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
emailMiniDumps();
}
});
return v;
}
public void emailMiniDumps()
{
//need to "send multiple" to get more than one attachment
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
emailIntent.setType("*/*");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
new String[]{"Arne Schwabe <arne@rfc2549.org>"});
String version;
String name="ics-openvpn";
try {
PackageInfo packageinfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
version = packageinfo.versionName;
name = packageinfo.applicationInfo.name;
} catch (NameNotFoundException e) {
version = "error fetching version";
}
emailIntent.putExtra(Intent.EXTRA_SUBJECT, String.format("%s %s Minidump",name,version));
emailIntent.putExtra(Intent.EXTRA_TEXT, "Please describe the issue you have experienced");
ArrayList<Uri> uris = new ArrayList<Uri>();
File ldump = getLastestDump(getActivity());
if(ldump==null) {
VpnStatus.logError("No Minidump found!");
}
uris.add(Uri.parse("content://de.blinkt.openvpn.FileProvider/" + ldump.getName()));
uris.add(Uri.parse("content://de.blinkt.openvpn.FileProvider/" + ldump.getName() + ".log"));
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
startActivity(emailIntent);
}
static public File getLastestDump(Context c) {
long newestDumpTime=0;
File newestDumpFile=null;
for(File f:c.getCacheDir().listFiles()) {
if(!f.getName().endsWith(".dmp"))
continue;
if (newestDumpTime < f.lastModified()) {
newestDumpTime = f.lastModified();
newestDumpFile=f;
}
}
// Ignore old dumps
//if(System.currentTimeMillis() - 48 * 60 * 1000 > newestDumpTime )
//return null;
return newestDumpFile;
}
}
| Java |
package de.blinkt.openvpn.fragments;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
import de.blinkt.openvpn.core.ProfileManager;
public abstract class OpenVpnPreferencesFragment extends PreferenceFragment {
protected VpnProfile mProfile;
protected abstract void loadSettings();
protected abstract void saveSettings();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String profileUUID = getArguments().getString(getActivity().getPackageName() + ".profileUUID");
mProfile = ProfileManager.get(getActivity(),profileUUID);
getActivity().setTitle(getString(R.string.edit_profile_title, mProfile.getName()));
}
@Override
public void onPause() {
super.onPause();
saveSettings();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState!=null) {
String profileUUID=savedInstanceState.getString(VpnProfile.EXTRA_PROFILEUUID);
mProfile = ProfileManager.get(getActivity(),profileUUID);
loadSettings();
}
}
@Override
public void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
saveSettings();
outState.putString(VpnProfile.EXTRA_PROFILEUUID, mProfile.getUUIDString());
}
}
| Java |
package de.blinkt.openvpn.fragments;
import android.app.Fragment;
import android.app.PendingIntent;
import android.content.*;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;
import com.android.vending.billing.IInAppBillingService;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.core.VpnStatus;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
public class AboutFragment extends Fragment implements View.OnClickListener {
public static final String INAPPITEM_TYPE_INAPP = "inapp";
public static final String RESPONSE_CODE = "RESPONSE_CODE";
private static final int DONATION_CODE = 12;
private static final int BILLING_RESPONSE_RESULT_OK = 0;
private static final String RESPONSE_BUY_INTENT = "BUY_INTENT";
private static final String[] donationSkus = { "donation1eur", "donation2eur", "donation5eur", "donation10eur",
"donation1337eur","donation23eur","donation25eur",};
IInAppBillingService mService;
Hashtable<View, String> viewToProduct = new Hashtable<View, String>();
ServiceConnection mServiceConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
@Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
initGooglePlayDonation();
}
};
private void initGooglePlayDonation() {
new Thread("queryGMSInApp") {
@Override
public void run() {
initGMSDonateOptions();
}
}.start();
}
private TextView gmsTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().bindService(new
Intent("com.android.vending.billing.InAppBillingService.BIND"),
mServiceConn, Context.BIND_AUTO_CREATE);
}
@Override
public void onDestroy() {
super.onDestroy();
if (mServiceConn != null) {
getActivity().unbindService(mServiceConn);
}
}
private void initGMSDonateOptions() {
try {
int billingSupported = mService.isBillingSupported(3, getActivity().getPackageName(), INAPPITEM_TYPE_INAPP);
if (billingSupported != BILLING_RESPONSE_RESULT_OK) {
Log.i("OpenVPN", "Play store billing not supported");
return;
}
ArrayList skuList = new ArrayList();
Collections.addAll(skuList, donationSkus);
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle ownedItems = mService.getPurchases(3, getActivity().getPackageName(), INAPPITEM_TYPE_INAPP, null);
if (ownedItems.getInt(RESPONSE_CODE) != BILLING_RESPONSE_RESULT_OK)
return;
final ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
Bundle skuDetails = mService.getSkuDetails(3, getActivity().getPackageName(), INAPPITEM_TYPE_INAPP, querySkus);
if (skuDetails.getInt(RESPONSE_CODE) != BILLING_RESPONSE_RESULT_OK)
return;
final ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
createPlayBuyOptions(ownedSkus, responseList);
}
});
}
} catch (RemoteException e) {
VpnStatus.logException(e);
}
}
private static class SkuResponse {
String title;
String price;
SkuResponse(String p, String t)
{
title=t;
price=p;
}
}
private void createPlayBuyOptions(ArrayList<String> ownedSkus, ArrayList<String> responseList) {
try {
Vector<Pair<String,String>> gdonation = new Vector<Pair<String, String>>();
gdonation.add(new Pair<String, String>(getString(R.string.donatePlayStore),null));
HashMap<String, SkuResponse> responseMap = new HashMap<String, SkuResponse>();
for (String thisResponse : responseList) {
JSONObject object = new JSONObject(thisResponse);
responseMap.put(
object.getString("productId"),
new SkuResponse(
object.getString("price"),
object.getString("title")));
}
for (String sku: donationSkus)
if (responseMap.containsKey(sku))
gdonation.add(getSkuTitle(sku,
responseMap.get(sku).title, responseMap.get(sku).price, ownedSkus));
String gmsTextString="";
for(int i=0;i<gdonation.size();i++) {
if(i==1)
gmsTextString+= " ";
else if(i>1)
gmsTextString+= ", ";
gmsTextString+=gdonation.elementAt(i).first;
}
SpannableString gmsText = new SpannableString(gmsTextString);
int lStart = 0;
int lEnd=0;
for(Pair<String, String> item:gdonation){
lEnd = lStart + item.first.length();
if (item.second!=null) {
final String mSku = item.second;
ClickableSpan cspan = new ClickableSpan()
{
@Override
public void onClick(View widget) {
triggerBuy(mSku);
}
};
gmsText.setSpan(cspan,lStart,lEnd,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
lStart = lEnd+2; // Account for ", " between items
}
if(gmsTextView !=null) {
gmsTextView.setText(gmsText);
gmsTextView.setMovementMethod(LinkMovementMethod.getInstance());
gmsTextView.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
VpnStatus.logException("Parsing Play Store IAP",e);
}
}
private Pair<String,String> getSkuTitle(final String sku, String title, String price, ArrayList<String> ownedSkus) {
String text;
if (ownedSkus.contains(sku))
return new Pair<String,String>(getString(R.string.thanks_for_donation, price),null);
if (price.contains("€")|| price.contains("\u20ac")) {
text= title;
} else {
text = String.format(Locale.getDefault(), "%s (%s)", title, price);
}
//return text;
return new Pair<String,String>(price, sku);
}
private void triggerBuy(String sku) {
try {
Bundle buyBundle
= mService.getBuyIntent(3, getActivity().getPackageName(),
sku, INAPPITEM_TYPE_INAPP, "Thanks for the donation! :)");
if (buyBundle.getInt(RESPONSE_CODE) == BILLING_RESPONSE_RESULT_OK) {
PendingIntent buyIntent = buyBundle.getParcelable(RESPONSE_BUY_INTENT);
getActivity().startIntentSenderForResult(buyIntent.getIntentSender(), DONATION_CODE, new Intent(),
0, 0, 0);
}
} catch (RemoteException e) {
VpnStatus.logException(e);
} catch (IntentSender.SendIntentException e) {
VpnStatus.logException(e);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.about, container, false);
TextView ver = (TextView) v.findViewById(R.id.version);
String version;
String name = "Openvpn";
try {
PackageInfo packageinfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
version = packageinfo.versionName;
name = getString(R.string.app);
} catch (NameNotFoundException e) {
version = "error fetching version";
}
ver.setText(getString(R.string.version_info, name, version));
TextView paypal = (TextView) v.findViewById(R.id.donatestring);
String donatetext = getActivity().getString(R.string.donatewithpaypal);
Spanned htmltext = Html.fromHtml(donatetext);
paypal.setText(htmltext);
paypal.setMovementMethod(LinkMovementMethod.getInstance());
gmsTextView = (TextView) v.findViewById(R.id.donategms);
/* recreating view without onCreate/onDestroy cycle */
if (mService!=null)
initGooglePlayDonation();
TextView translation = (TextView) v.findViewById(R.id.translation);
// Don't print a text for myself
if (getString(R.string.translationby).contains("Arne Schwabe"))
translation.setText("");
else
translation.setText(R.string.translationby);
WebView wv = (WebView)v.findViewById(R.id.webView);
wv.loadUrl("file:///android_asset/full_licenses.html");
return v;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (mService!=null)
initGooglePlayDonation();
}
@Override
public void onClick(View v) {
}
}
| Java |
package de.blinkt.openvpn.fragments;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.TreeMap;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import de.blinkt.openvpn.activities.FileSelect;
import de.blinkt.openvpn.R;
public class FileSelectionFragment extends ListFragment {
private static final String ITEM_KEY = "key";
private static final String ITEM_IMAGE = "image";
private static final String ROOT = "/";
private List<String> path = null;
private TextView myPath;
private ArrayList<HashMap<String, Object>> mList;
private Button selectButton;
private String parentPath;
private String currentPath = ROOT;
private String[] formatFilter = null;
private File selectedFile;
private HashMap<String, Integer> lastPositions = new HashMap<String, Integer>();
private String mStartPath;
private CheckBox mInlineImport;
private Button mClearButton;
private boolean mHideImport=false;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.file_dialog_main, container,false);
myPath = (TextView) v.findViewById(R.id.path);
mInlineImport = (CheckBox) v.findViewById(R.id.doinline);
if(mHideImport) {
mInlineImport.setVisibility(View.GONE);
mInlineImport.setChecked(false);
}
selectButton = (Button) v.findViewById(R.id.fdButtonSelect);
selectButton.setEnabled(false);
selectButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (selectedFile != null) {
if(mInlineImport.isChecked())
((FileSelect) getActivity()).importFile(selectedFile.getPath());
else
((FileSelect) getActivity()).setFile(selectedFile.getPath());
}
}
});
mClearButton = (Button) v.findViewById(R.id.fdClear);
mClearButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((FileSelect) getActivity()).clearData();
}
});
if(!((FileSelect) getActivity()).showClear()) {
mClearButton.setVisibility(View.GONE);
mClearButton.setEnabled(false);
}
return v;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mStartPath = ((FileSelect) getActivity()).getSelectPath();
getDir(mStartPath);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void getDir(String dirPath) {
boolean useAutoSelection = dirPath.length() < currentPath.length();
Integer position = lastPositions.get(parentPath);
getDirImpl(dirPath);
if (position != null && useAutoSelection) {
getListView().setSelection(position);
}
}
/**
* Monta a estrutura de arquivos e diretorios filhos do diretorio fornecido.
*
* @param dirPath
* Diretorio pai.
*/
private void getDirImpl(final String dirPath) {
currentPath = dirPath;
final List<String> item = new ArrayList<String>();
path = new ArrayList<String>();
mList = new ArrayList<HashMap<String, Object>>();
File f = new File(currentPath);
File[] files = f.listFiles();
if (files == null) {
currentPath = ROOT;
f = new File(currentPath);
files = f.listFiles();
}
myPath.setText(getText(R.string.location) + ": " + currentPath);
if (!currentPath.equals(ROOT)) {
item.add(ROOT);
addItem(ROOT, R.drawable.ic_root_folder_am);
path.add(ROOT);
item.add("../");
addItem("../", R.drawable.ic_root_folder_am);
path.add(f.getParent());
parentPath = f.getParent();
}
TreeMap<String, String> dirsMap = new TreeMap<String, String>();
TreeMap<String, String> dirsPathMap = new TreeMap<String, String>();
TreeMap<String, String> filesMap = new TreeMap<String, String>();
TreeMap<String, String> filesPathMap = new TreeMap<String, String>();
for (File file : files) {
if (file.isDirectory()) {
String dirName = file.getName();
dirsMap.put(dirName, dirName);
dirsPathMap.put(dirName, file.getPath());
} else {
final String fileName = file.getName();
final String fileNameLwr = fileName.toLowerCase(Locale.getDefault());
// se ha um filtro de formatos, utiliza-o
if (formatFilter != null) {
boolean contains = false;
for (String aFormatFilter : formatFilter) {
final String formatLwr = aFormatFilter.toLowerCase(Locale.getDefault());
if (fileNameLwr.endsWith(formatLwr)) {
contains = true;
break;
}
}
if (contains) {
filesMap.put(fileName, fileName);
filesPathMap.put(fileName, file.getPath());
}
// senao, adiciona todos os arquivos
} else {
filesMap.put(fileName, fileName);
filesPathMap.put(fileName, file.getPath());
}
}
}
item.addAll(dirsMap.tailMap("").values());
item.addAll(filesMap.tailMap("").values());
path.addAll(dirsPathMap.tailMap("").values());
path.addAll(filesPathMap.tailMap("").values());
SimpleAdapter fileList = new SimpleAdapter(getActivity(), mList, R.layout.file_dialog_row, new String[] {
ITEM_KEY, ITEM_IMAGE }, new int[] { R.id.fdrowtext, R.id.fdrowimage });
for (String dir : dirsMap.tailMap("").values()) {
addItem(dir, R.drawable.ic_root_folder_am);
}
for (String file : filesMap.tailMap("").values()) {
addItem(file, R.drawable.ic_doc_generic_am);
}
fileList.notifyDataSetChanged();
setListAdapter(fileList);
}
private void addItem(String fileName, int imageId) {
HashMap<String, Object> item = new HashMap<String, Object>();
item.put(ITEM_KEY, fileName);
item.put(ITEM_IMAGE, imageId);
mList.add(item);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(path.get(position));
if (file.isDirectory()) {
selectButton.setEnabled(false);
if (file.canRead()) {
lastPositions.put(currentPath, position);
getDir(path.get(position));
} else {
new AlertDialog.Builder(getActivity()).setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "] " + getText(R.string.cant_read_folder))
.setPositiveButton("OK", null).show();
}
} else {
selectedFile = file;
v.setSelected(true);
selectButton.setEnabled(true);
}
}
public void setNoInLine() {
mHideImport=true;
}
}
| Java |
package de.blinkt.openvpn.fragments;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.SwitchPreference;
import android.util.Pair;
import de.blinkt.openvpn.activities.FileSelect;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.core.VpnStatus;
import de.blinkt.openvpn.views.RemoteCNPreference;
import de.blinkt.openvpn.VpnProfile;
import java.io.IOException;
public class Settings_Authentication extends OpenVpnPreferencesFragment implements OnPreferenceChangeListener, OnPreferenceClickListener {
private static final int SELECT_TLS_FILE = 23223232;
private static final int SELECT_TLS_FILE_KITKAT = SELECT_TLS_FILE +1;
private CheckBoxPreference mExpectTLSCert;
private CheckBoxPreference mCheckRemoteCN;
private RemoteCNPreference mRemoteCN;
private ListPreference mTLSAuthDirection;
private Preference mTLSAuthFile;
private SwitchPreference mUseTLSAuth;
private EditTextPreference mCipher;
private String mTlsAuthFileData;
private EditTextPreference mAuth;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.vpn_authentification);
mExpectTLSCert = (CheckBoxPreference) findPreference("remoteServerTLS");
mCheckRemoteCN = (CheckBoxPreference) findPreference("checkRemoteCN");
mRemoteCN = (RemoteCNPreference) findPreference("remotecn");
mRemoteCN.setOnPreferenceChangeListener(this);
mUseTLSAuth = (SwitchPreference) findPreference("useTLSAuth" );
mTLSAuthFile = findPreference("tlsAuthFile");
mTLSAuthDirection = (ListPreference) findPreference("tls_direction");
mTLSAuthFile.setOnPreferenceClickListener(this);
mCipher =(EditTextPreference) findPreference("cipher");
mCipher.setOnPreferenceChangeListener(this);
mAuth =(EditTextPreference) findPreference("auth");
mAuth.setOnPreferenceChangeListener(this);
loadSettings();
}
@Override
protected void loadSettings() {
mExpectTLSCert.setChecked(mProfile.mExpectTLSCert);
mCheckRemoteCN.setChecked(mProfile.mCheckRemoteCN);
mRemoteCN.setDN(mProfile.mRemoteCN);
mRemoteCN.setAuthType(mProfile.mX509AuthType);
onPreferenceChange(mRemoteCN,
new Pair<Integer, String>(mProfile.mX509AuthType, mProfile.mRemoteCN));
mUseTLSAuth.setChecked(mProfile.mUseTLSAuth);
mTlsAuthFileData= mProfile.mTLSAuthFilename;
setTlsAuthSummary(mTlsAuthFileData);
mTLSAuthDirection.setValue(mProfile.mTLSAuthDirection);
mCipher.setText(mProfile.mCipher);
onPreferenceChange(mCipher, mProfile.mCipher);
mAuth.setText(mProfile.mAuth);
onPreferenceChange(mAuth, mProfile.mAuth);
if (mProfile.mAuthenticationType == VpnProfile.TYPE_STATICKEYS) {
mExpectTLSCert.setEnabled(false);
mCheckRemoteCN.setEnabled(false);
mUseTLSAuth.setChecked(true);
} else {
mExpectTLSCert.setEnabled(true);
mCheckRemoteCN.setEnabled(true);
}
}
@Override
protected void saveSettings() {
mProfile.mExpectTLSCert=mExpectTLSCert.isChecked();
mProfile.mCheckRemoteCN=mCheckRemoteCN.isChecked();
mProfile.mRemoteCN=mRemoteCN.getCNText();
mProfile.mX509AuthType=mRemoteCN.getAuthtype();
mProfile.mUseTLSAuth = mUseTLSAuth.isChecked();
mProfile.mTLSAuthFilename = mTlsAuthFileData;
if(mTLSAuthDirection.getValue()==null)
mProfile.mTLSAuthDirection=null;
else
mProfile.mTLSAuthDirection = mTLSAuthDirection.getValue();
if(mCipher.getText()==null)
mProfile.mCipher=null;
else
mProfile.mCipher = mCipher.getText();
if(mAuth.getText()==null)
mProfile.mAuth = null;
else
mProfile.mAuth = mAuth.getText();
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(preference==mRemoteCN) {
@SuppressWarnings("unchecked")
int authtype = ((Pair<Integer, String>) newValue).first;
@SuppressWarnings("unchecked")
String dn = ((Pair<Integer, String>) newValue).second;
if ("".equals(dn))
preference.setSummary(getX509String(VpnProfile.X509_VERIFY_TLSREMOTE_RDN, mProfile.mServerName));
else
preference.setSummary(getX509String(authtype,dn));
} else if (preference == mCipher || preference == mAuth) {
preference.setSummary((CharSequence) newValue);
}
return true;
}
private CharSequence getX509String(int authtype, String dn) {
String ret ="";
switch (authtype) {
case VpnProfile.X509_VERIFY_TLSREMOTE:
case VpnProfile.X509_VERIFY_TLSREMOTE_COMPAT_NOREMAPPING:
ret+="tls-remote ";
break;
case VpnProfile.X509_VERIFY_TLSREMOTE_DN:
ret="dn: ";
break;
case VpnProfile.X509_VERIFY_TLSREMOTE_RDN:
ret="rdn: ";
break;
case VpnProfile.X509_VERIFY_TLSREMOTE_RDN_PREFIX:
ret="rdn prefix: ";
break;
}
return ret + dn;
}
void startFileDialog() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent startFC = Utils.getFilePickerIntent (Utils.FileType.TLS_AUTH_FILE);
startActivityForResult(startFC, SELECT_TLS_FILE_KITKAT);
} else {
Intent startFC = new Intent(getActivity(), FileSelect.class);
startFC.putExtra(FileSelect.START_DATA, mTlsAuthFileData);
startFC.putExtra(FileSelect.WINDOW_TITLE, R.string.tls_auth_file);
startActivityForResult(startFC, SELECT_TLS_FILE);
}
}
@Override
public boolean onPreferenceClick(Preference preference) {
startFileDialog();
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==SELECT_TLS_FILE && resultCode == Activity.RESULT_OK){
String result = data.getStringExtra(FileSelect.RESULT_DATA);
mTlsAuthFileData=result;
setTlsAuthSummary(result);
} else if (requestCode == SELECT_TLS_FILE_KITKAT && resultCode == Activity.RESULT_OK) {
try {
mTlsAuthFileData= Utils.getFilePickerResult(Utils.FileType.TLS_AUTH_FILE,data,getActivity());
setTlsAuthSummary(mTlsAuthFileData);
} catch (IOException e) {
VpnStatus.logException(e);
}
}
}
private void setTlsAuthSummary(String result) {
if(result==null)
result = getString(R.string.no_certificate);
if(result.startsWith(VpnProfile.INLINE_TAG))
mTLSAuthFile.setSummary(R.string.inline_file_data);
else if (result.startsWith(VpnProfile.DISPLAYNAME_TAG))
mExpectTLSCert.setSummary(getString(R.string.imported_from_file, VpnProfile.getDisplayName(result)));
else
mTLSAuthFile.setSummary(result);
}
} | Java |
package de.blinkt.openvpn.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import de.blinkt.openvpn.activities.FileSelect;
import de.blinkt.openvpn.R;
public class InlineFileTab extends Fragment
{
private static final int MENU_SAVE = 0;
private EditText mInlineData;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mInlineData.setText(((FileSelect)getActivity()).getInlineData());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.file_dialog_inline, container, false);
mInlineData =(EditText) v.findViewById(R.id.inlineFileData);
return v;
}
public void setData(String data) {
if(mInlineData!=null)
mInlineData.setText(data);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.add(0, MENU_SAVE, 0, "Use inline data")
.setIcon(android.R.drawable.ic_menu_save)
.setAlphabeticShortcut('u')
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==MENU_SAVE){
((FileSelect)getActivity()).saveInlineData(null, mInlineData.getText().toString());
return true;
}
return super.onOptionsItemSelected(item);
}
} | Java |
package de.blinkt.openvpn.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import de.blinkt.openvpn.R;
public class FaqFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.faq, container, false);
insertHtmlEntry(v,R.id.broken_images_faq,R.string.broken_images_faq);
insertHtmlEntry(v,R.id.faq_howto,R.string.faq_howto);
insertHtmlEntry(v, R.id.baterry_consumption, R.string.baterry_consumption);
insertHtmlEntry(v, R.id.faq_tethering, R.string.faq_tethering);
insertHtmlEntry(v, R.id.faq_vpndialog43, R.string.faq_vpndialog43);
insertHtmlEntry(v, R.id.faq_system_dialog_xposed, R.string.faq_system_dialog_xposed);
return v;
}
private void insertHtmlEntry (View v, int viewId, int stringId) {
TextView faqitem = (TextView) v.findViewById(viewId);
faqitem.setText(Html.fromHtml(getActivity().getString(stringId)));
faqitem.setMovementMethod(LinkMovementMethod.getInstance());
}
}
| Java |
package de.blinkt.openvpn.fragments;
import java.io.File;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.api.ExternalAppDatabase;
public class GeneralSettings extends PreferenceFragment implements OnPreferenceClickListener, OnClickListener {
private ExternalAppDatabase mExtapp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.general_settings);
PreferenceCategory devHacks = (PreferenceCategory) findPreference("device_hacks");
Preference loadtun = findPreference("loadTunModule");
if(!isTunModuleAvailable()) {
loadtun.setEnabled(false);
devHacks.removePreference(loadtun);
}
CheckBoxPreference cm9hack = (CheckBoxPreference) findPreference("useCM9Fix");
if (!cm9hack.isChecked() && (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1)) {
devHacks.removePreference(cm9hack);
}
mExtapp = new ExternalAppDatabase(getActivity());
Preference clearapi = findPreference("clearapi");
clearapi.setOnPreferenceClickListener(this);
if(devHacks.getPreferenceCount()==0)
getPreferenceScreen().removePreference(devHacks);
setClearApiSummary();
}
private void setClearApiSummary() {
Preference clearapi = findPreference("clearapi");
if(mExtapp.getExtAppList().isEmpty()) {
clearapi.setEnabled(false);
clearapi.setSummary(R.string.no_external_app_allowed);
} else {
clearapi.setEnabled(true);
clearapi.setSummary(getString(R.string.allowed_apps,getExtAppList(", ")));
}
}
private String getExtAppList(String delim) {
ApplicationInfo app;
PackageManager pm = getActivity().getPackageManager();
String applist=null;
for (String packagename : mExtapp.getExtAppList()) {
try {
app = pm.getApplicationInfo(packagename, 0);
if (applist==null)
applist = "";
else
applist += delim;
applist+=app.loadLabel(pm);
} catch (NameNotFoundException e) {
// App not found. Remove it from the list
mExtapp.removeApp(packagename);
}
}
return applist;
}
private boolean isTunModuleAvailable() {
// Check if the tun module exists on the file system
return new File("/system/lib/modules/tun.ko").length() > 10;
}
@Override
public boolean onPreferenceClick(Preference preference) {
if(preference.getKey().equals("clearapi")){
Builder builder = new AlertDialog.Builder(getActivity());
builder.setPositiveButton(R.string.clear, this);
builder.setNegativeButton(android.R.string.cancel, null);
builder.setMessage(getString(R.string.clearappsdialog,getExtAppList("\n")));
builder.show();
}
return true;
}
@Override
public void onClick(DialogInterface dialog, int which) {
if( which == Dialog.BUTTON_POSITIVE){
mExtapp.clearAllApiApps();
setClearApiSummary();
}
}
} | Java |
package de.blinkt.openvpn.fragments;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import de.blinkt.openvpn.R;
public class Settings_Routing extends OpenVpnPreferencesFragment implements OnPreferenceChangeListener {
private EditTextPreference mCustomRoutes;
private CheckBoxPreference mUseDefaultRoute;
private EditTextPreference mCustomRoutesv6;
private CheckBoxPreference mUseDefaultRoutev6;
private CheckBoxPreference mRouteNoPull;
private CheckBoxPreference mLocalVPNAccess;
private EditTextPreference mExcludedRoutes;
private EditTextPreference mExcludedRoutesv6;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.vpn_routing);
mCustomRoutes = (EditTextPreference) findPreference("customRoutes");
mUseDefaultRoute = (CheckBoxPreference) findPreference("useDefaultRoute");
mCustomRoutesv6 = (EditTextPreference) findPreference("customRoutesv6");
mUseDefaultRoutev6 = (CheckBoxPreference) findPreference("useDefaultRoutev6");
mExcludedRoutes = (EditTextPreference) findPreference("excludedRoutes");
mExcludedRoutesv6 = (EditTextPreference) findPreference("excludedRoutesv6");
mRouteNoPull = (CheckBoxPreference) findPreference("routenopull");
mLocalVPNAccess = (CheckBoxPreference) findPreference("unblockLocal");
mCustomRoutes.setOnPreferenceChangeListener(this);
mCustomRoutesv6.setOnPreferenceChangeListener(this);
loadSettings();
}
@Override
protected void loadSettings() {
mUseDefaultRoute.setChecked(mProfile.mUseDefaultRoute);
mUseDefaultRoutev6.setChecked(mProfile.mUseDefaultRoutev6);
mCustomRoutes.setText(mProfile.mCustomRoutes);
mCustomRoutesv6.setText(mProfile.mCustomRoutesv6);
mExcludedRoutes.setText(mProfile.mExcludedRoutes);
mExcludedRoutes.setText(mProfile.mExcludedRoutesv6);
mRouteNoPull.setChecked(mProfile.mRoutenopull);
mLocalVPNAccess.setChecked(mProfile.mAllowLocalLAN);
// Sets Summary
onPreferenceChange(mCustomRoutes, mCustomRoutes.getText());
onPreferenceChange(mCustomRoutesv6, mCustomRoutesv6.getText());
mRouteNoPull.setEnabled(mProfile.mUsePull);
}
@Override
protected void saveSettings() {
mProfile.mUseDefaultRoute = mUseDefaultRoute.isChecked();
mProfile.mUseDefaultRoutev6 = mUseDefaultRoutev6.isChecked();
mProfile.mCustomRoutes = mCustomRoutes.getText();
mProfile.mCustomRoutesv6 = mCustomRoutesv6.getText();
mProfile.mRoutenopull = mRouteNoPull.isChecked();
mProfile.mAllowLocalLAN =mLocalVPNAccess.isChecked();
mProfile.mExcludedRoutes = mExcludedRoutes.getText();
mProfile.mExcludedRoutesv6 = mExcludedRoutesv6.getText();
}
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if( preference == mCustomRoutes || preference == mCustomRoutesv6
|| preference == mExcludedRoutes || preference == mExcludedRoutesv6)
preference.setSummary((String)newValue);
saveSettings();
return true;
}
} | Java |
package de.blinkt.openvpn.fragments;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.*;
import android.content.*;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.IBinder;
import android.os.Message;
import android.text.SpannableString;
import android.text.format.DateFormat;
import android.text.style.ImageSpan;
import android.view.*;
import android.widget.*;
import android.widget.AdapterView.OnItemLongClickListener;
import de.blinkt.openvpn.*;
import de.blinkt.openvpn.activities.DisconnectVPN;
import de.blinkt.openvpn.activities.MainActivity;
import de.blinkt.openvpn.activities.VPNPreferences;
import de.blinkt.openvpn.core.OpenVPNManagement;
import de.blinkt.openvpn.core.VpnStatus;
import de.blinkt.openvpn.core.VpnStatus.ConnectionStatus;
import de.blinkt.openvpn.core.VpnStatus.LogItem;
import de.blinkt.openvpn.core.VpnStatus.LogListener;
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 org.jetbrains.annotations.Nullable;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Locale;
import java.util.Vector;
import static de.blinkt.openvpn.core.OpenVpnService.humanReadableByteCount;
public class LogFragment extends ListFragment implements StateListener, SeekBar.OnSeekBarChangeListener, RadioGroup.OnCheckedChangeListener, VpnStatus.ByteCountListener {
private static final String LOGTIMEFORMAT = "logtimeformat";
private static final int START_VPN_CONFIG = 0;
private static final String VERBOSITYLEVEL = "verbositylevel";
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
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mService =null;
}
};
private SeekBar mLogLevelSlider;
private LinearLayout mOptionsLayout;
private RadioGroup mTimeRadioGroup;
private TextView mUpStatus;
private TextView mDownStatus;
private TextView mConnectStatus;
private boolean mShowOptionsLayout;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
ladapter.setLogLevel(progress+1);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radioISO:
ladapter.setTimeFormat(LogWindowListAdapter.TIME_FORMAT_ISO);
break;
case R.id.radioNone:
ladapter.setTimeFormat(LogWindowListAdapter.TIME_FORMAT_NONE);
break;
case R.id.radioShort:
ladapter.setTimeFormat(LogWindowListAdapter.TIME_FORMAT_SHORT);
break;
}
}
@Override
public void updateByteCount(long in, long out, long diffIn, long diffOut) {
//%2$s/s %1$s - ↑%4$s/s %3$s
final String down = String.format("%2$s/s %1$s", humanReadableByteCount(in, false), humanReadableByteCount(diffIn / OpenVPNManagement.mBytecountInterval, true));
final String up = String.format("%2$s/s %1$s", humanReadableByteCount(out, false), humanReadableByteCount(diffOut / OpenVPNManagement.mBytecountInterval, true));
if (mUpStatus != null && mDownStatus != null) {
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
mUpStatus.setText(up);
mDownStatus.setText(down);
}
});
}
}
}
class LogWindowListAdapter implements ListAdapter, LogListener, Callback {
private static final int MESSAGE_NEWLOG = 0;
private static final int MESSAGE_CLEARLOG = 1;
private static final int MESSAGE_NEWTS = 2;
private static final int MESSAGE_NEWLOGLEVEL = 3;
public static final int TIME_FORMAT_NONE = 0;
public static final int TIME_FORMAT_SHORT = 1;
public static final int TIME_FORMAT_ISO = 2;
private static final int MAX_STORED_LOG_ENTRIES = 1000;
private Vector<LogItem> allEntries=new Vector<LogItem>();
private Vector<LogItem> currentLevelEntries=new Vector<LogItem>();
private Handler mHandler;
private Vector<DataSetObserver> observers=new Vector<DataSetObserver>();
private int mTimeFormat=0;
private int mLogLevel=3;
public LogWindowListAdapter() {
initLogBuffer();
if (mHandler == null) {
mHandler = new Handler(this);
}
VpnStatus.addLogListener(this);
}
private void initLogBuffer() {
allEntries.clear();
Collections.addAll(allEntries, VpnStatus.getlogbuffer());
initCurrentMessages();
}
String getLogStr() {
String str = "";
for(LogItem entry:allEntries) {
str+=getTime(entry, TIME_FORMAT_ISO) + entry.getString(getActivity()) + '\n';
}
return str;
}
private void shareLog() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, getLogStr());
shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.ics_openvpn_log_file));
shareIntent.setType("text/plain");
startActivity(Intent.createChooser(shareIntent, "Send Logfile"));
}
@Override
public void registerDataSetObserver(DataSetObserver observer) {
observers.add(observer);
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
observers.remove(observer);
}
@Override
public int getCount() {
return currentLevelEntries.size();
}
@Override
public Object getItem(int position) {
return currentLevelEntries.get(position);
}
@Override
public long getItemId(int position) {
return ((Object)currentLevelEntries.get(position)).hashCode();
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView v;
if(convertView==null)
v = new TextView(getActivity());
else
v = (TextView) convertView;
LogItem le = currentLevelEntries.get(position);
String msg = le.getString(getActivity());
String time = getTime(le, mTimeFormat);
msg = time + msg;
int spanStart = time.length();
SpannableString t = new SpannableString(msg);
//t.setSpan(getSpanImage(le,(int)v.getTextSize()),spanStart,spanStart+1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
v.setText(t);
return v;
}
private String getTime(LogItem le, int time) {
if (time != TIME_FORMAT_NONE) {
Date d = new Date(le.getLogtime());
java.text.DateFormat timeformat;
if (time== TIME_FORMAT_ISO)
timeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
else
timeformat = DateFormat.getTimeFormat(getActivity());
return timeformat.format(d) + " ";
} else {
return "";
}
}
private ImageSpan getSpanImage(LogItem li, int imageSize) {
int imageRes = android.R.drawable.ic_menu_call;
switch (li.getLogLevel()) {
case ERROR:
imageRes = android.R.drawable.ic_notification_clear_all;
break;
case INFO:
imageRes = android.R.drawable.ic_menu_compass;
break;
case VERBOSE:
imageRes = android.R.drawable.ic_menu_info_details;
break;
case WARNING:
imageRes = android.R.drawable.ic_menu_camera;
break;
}
Drawable d = getResources().getDrawable(imageRes);
//d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
d.setBounds(0, 0, imageSize, imageSize);
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM);
return span;
}
@Override
public int getItemViewType(int position) {
return 0;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public boolean isEmpty() {
return currentLevelEntries.isEmpty();
}
@Override
public boolean areAllItemsEnabled() {
return true;
}
@Override
public boolean isEnabled(int position) {
return true;
}
@Override
public void newLog(LogItem logMessage) {
Message msg = Message.obtain();
assert (msg!=null);
msg.what=MESSAGE_NEWLOG;
Bundle bundle=new Bundle();
bundle.putParcelable("logmessage", logMessage);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
@Override
public boolean handleMessage(Message msg) {
// We have been called
if(msg.what==MESSAGE_NEWLOG) {
LogItem logMessage = msg.getData().getParcelable("logmessage");
if(addLogMessage(logMessage))
for (DataSetObserver observer : observers) {
observer.onChanged();
}
} else if (msg.what == MESSAGE_CLEARLOG) {
for (DataSetObserver observer : observers) {
observer.onInvalidated();
}
initLogBuffer();
} else if (msg.what == MESSAGE_NEWTS) {
for (DataSetObserver observer : observers) {
observer.onInvalidated();
}
} else if (msg.what == MESSAGE_NEWLOGLEVEL) {
initCurrentMessages();
for (DataSetObserver observer: observers) {
observer.onChanged();
}
}
return true;
}
private void initCurrentMessages() {
currentLevelEntries.clear();
for(LogItem li: allEntries) {
if (li.getVerbosityLevel() <= mLogLevel ||
mLogLevel == VpnProfile.MAXLOGLEVEL)
currentLevelEntries.add(li);
}
}
/**
*
* @param logmessage
* @return True if the current entries have changed
*/
private boolean addLogMessage(LogItem logmessage) {
allEntries.add(logmessage);
if (allEntries.size() > MAX_STORED_LOG_ENTRIES) {
Vector<LogItem> oldAllEntries = allEntries;
allEntries = new Vector<LogItem>(allEntries.size());
for (int i=50;i<oldAllEntries.size();i++) {
allEntries.add(oldAllEntries.elementAt(i));
}
initCurrentMessages();
return true;
} else {
if (logmessage.getVerbosityLevel() <= mLogLevel) {
currentLevelEntries.add(logmessage);
return true;
} else {
return false;
}
}
}
void clearLog() {
// Actually is probably called from GUI Thread as result of the user
// pressing a button. But better safe than sorry
VpnStatus.clearLog();
VpnStatus.logInfo(R.string.logCleared);
mHandler.sendEmptyMessage(MESSAGE_CLEARLOG);
}
public void setTimeFormat(int newTimeFormat) {
mTimeFormat= newTimeFormat;
mHandler.sendEmptyMessage(MESSAGE_NEWTS);
}
public void setLogLevel(int logLevel) {
mLogLevel = logLevel;
mHandler.sendEmptyMessage(MESSAGE_NEWLOGLEVEL);
}
}
private LogWindowListAdapter ladapter;
private TextView mSpeedView;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.clearlog) {
ladapter.clearLog();
return true;
} else if(item.getItemId()==R.id.cancel){
Intent intent = new Intent(getActivity(),DisconnectVPN.class);
startActivity(intent);
return true;
} else if(item.getItemId()==R.id.send) {
ladapter.shareLog();
} else if(item.getItemId()==R.id.edit_vpn) {
VpnProfile lastConnectedprofile = ProfileManager.getLastConnectedVpn();
if(lastConnectedprofile!=null) {
Intent vprefintent = new Intent(getActivity(),VPNPreferences.class)
.putExtra(VpnProfile.EXTRA_PROFILEUUID,lastConnectedprofile.getUUIDString());
startActivityForResult(vprefintent,START_VPN_CONFIG);
} else {
Toast.makeText(getActivity(), R.string.log_no_last_vpn, Toast.LENGTH_LONG).show();
}
} else if(item.getItemId() == R.id.toggle_time) {
showHideOptionsPanel();
} else if(item.getItemId() == android.R.id.home) {
// This is called when the Home (Up) button is pressed
// in the Action Bar.
Intent parentActivityIntent = new Intent(getActivity(), MainActivity.class);
parentActivityIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(parentActivityIntent);
getActivity().finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void showHideOptionsPanel() {
boolean optionsVisible = (mOptionsLayout.getVisibility() != View.GONE);
ObjectAnimator anim;
if (optionsVisible) {
anim = ObjectAnimator.ofFloat(mOptionsLayout,"alpha",1.0f, 0f);
anim.addListener(collapseListener);
} else {
mOptionsLayout.setVisibility(View.VISIBLE);
anim = ObjectAnimator.ofFloat(mOptionsLayout,"alpha", 0f, 1.0f);
//anim = new TranslateAnimation(0.0f, 0.0f, mOptionsLayout.getHeight(), 0.0f);
}
//anim.setInterpolator(new AccelerateInterpolator(1.0f));
//anim.setDuration(300);
//mOptionsLayout.startAnimation(anim);
anim.start();
}
AnimatorListenerAdapter collapseListener = new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animator) {
mOptionsLayout.setVisibility(View.GONE);
}
};
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.logmenu, menu);
if (getResources().getBoolean(R.bool.logSildersAlwaysVisible))
menu.removeItem(R.id.toggle_time);
}
@Override
public void onResume() {
super.onResume();
VpnStatus.addStateListener(this);
VpnStatus.addByteCountListener(this);
Intent intent = new Intent(getActivity(), OpenVpnService.class);
intent.setAction(OpenVpnService.START_SERVICE);
getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == START_VPN_CONFIG && resultCode== Activity.RESULT_OK) {
String configuredVPN = data.getStringExtra(VpnProfile.EXTRA_PROFILEUUID);
final VpnProfile profile = ProfileManager.get(getActivity(),configuredVPN);
ProfileManager.getInstance(getActivity()).saveProfile(getActivity(), profile);
// Name could be modified, reset List adapter
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setTitle(R.string.configuration_changed);
dialog.setMessage(R.string.restart_vpn_after_change);
dialog.setPositiveButton(R.string.restart,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getActivity(), LaunchVPN.class);
intent.putExtra(LaunchVPN.EXTRA_KEY, profile.getUUIDString());
intent.setAction(Intent.ACTION_MAIN);
startActivity(intent);
}
});
dialog.setNegativeButton(R.string.ignore, null);
dialog.create().show();
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onStop() {
super.onStop();
VpnStatus.removeStateListener(this);
VpnStatus.removeByteCountListener(this);
if(mService!=null)
getActivity().unbindService(mConnection);
getActivity().getPreferences(0).edit().putInt(LOGTIMEFORMAT, ladapter.mTimeFormat)
.putInt(VERBOSITYLEVEL, ladapter.mLogLevel).apply();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView lv = getListView();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ClipboardManager clipboard = (ClipboardManager)
getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Log Entry",((TextView) view).getText());
clipboard.setPrimaryClip(clip);
Toast.makeText(getActivity(), R.string.copied_entry, Toast.LENGTH_SHORT).show();
return true;
}
});
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.log_fragment, container, false);
setHasOptionsMenu(true);
ladapter = new LogWindowListAdapter();
ladapter.mTimeFormat = getActivity().getPreferences(0).getInt(LOGTIMEFORMAT, 0);
int logLevel = getActivity().getPreferences(0).getInt(VERBOSITYLEVEL, 0);
ladapter.setLogLevel(logLevel);
setListAdapter(ladapter);
mTimeRadioGroup = (RadioGroup) v.findViewById(R.id.timeFormatRadioGroup);
mTimeRadioGroup.setOnCheckedChangeListener(this);
if(ladapter.mTimeFormat== LogWindowListAdapter.TIME_FORMAT_ISO) {
mTimeRadioGroup.check(R.id.radioISO);
} else if (ladapter.mTimeFormat == LogWindowListAdapter.TIME_FORMAT_NONE) {
mTimeRadioGroup.check(R.id.radioNone);
} else if (ladapter.mTimeFormat == LogWindowListAdapter.TIME_FORMAT_SHORT) {
mTimeRadioGroup.check(R.id.radioShort);
}
mSpeedView = (TextView) v.findViewById(R.id.speed);
mOptionsLayout = (LinearLayout) v.findViewById(R.id.logOptionsLayout);
mLogLevelSlider = (SeekBar) v.findViewById(R.id.LogLevelSlider);
mLogLevelSlider.setMax(VpnProfile.MAXLOGLEVEL-1);
mLogLevelSlider.setProgress(logLevel-1);
mLogLevelSlider.setOnSeekBarChangeListener(this);
if(getResources().getBoolean(R.bool.logSildersAlwaysVisible))
mOptionsLayout.setVisibility(View.VISIBLE);
mUpStatus = (TextView) v.findViewById(R.id.speedUp);
mDownStatus = (TextView) v.findViewById(R.id.speedDown);
mConnectStatus = (TextView) v.findViewById(R.id.speedStatus);
if (mShowOptionsLayout)
mOptionsLayout.setVisibility(View.VISIBLE);
return v;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if(getResources().getBoolean(R.bool.logSildersAlwaysVisible)) {
mShowOptionsLayout=true;
if (mOptionsLayout!= null)
mOptionsLayout.setVisibility(View.VISIBLE);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public void updateState(final String status, final String logMessage, final int resId, final ConnectionStatus level) {
if (isAdded()) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
String prefix = getString(resId) + ":";
if (status.equals("BYTECOUNT") || status.equals("NOPROCESS"))
prefix = "";
if (resId == R.string.unknown_state)
prefix += status;
if (mSpeedView != null)
mSpeedView.setText(prefix + logMessage);
if (mConnectStatus != null)
mConnectStatus.setText(getString(resId));
}
});
}
}
@Override
public void onDestroy() {
VpnStatus.removeLogListener(ladapter);
super.onDestroy();
}
}
| Java |
package de.blinkt.openvpn.fragments;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import de.blinkt.openvpn.R;
public class Settings_Obscure extends OpenVpnPreferencesFragment implements OnPreferenceChangeListener {
private CheckBoxPreference mUseRandomHostName;
private CheckBoxPreference mUseFloat;
private CheckBoxPreference mUseCustomConfig;
private EditTextPreference mCustomConfig;
private ListPreference mLogverbosity;
private CheckBoxPreference mPersistent;
private ListPreference mConnectretrymax;
private EditTextPreference mConnectretry;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.vpn_obscure);
mUseRandomHostName = (CheckBoxPreference) findPreference("useRandomHostname");
mUseFloat = (CheckBoxPreference) findPreference("useFloat");
mUseCustomConfig = (CheckBoxPreference) findPreference("enableCustomOptions");
mCustomConfig = (EditTextPreference) findPreference("customOptions");
mPersistent = (CheckBoxPreference) findPreference("usePersistTun");
mConnectretrymax = (ListPreference) findPreference("connectretrymax");
mConnectretry = (EditTextPreference) findPreference("connectretry");
mConnectretrymax.setOnPreferenceChangeListener(this);
mConnectretrymax.setSummary("%s");
mConnectretry.setOnPreferenceChangeListener(this);
loadSettings();
}
protected void loadSettings() {
mUseRandomHostName.setChecked(mProfile.mUseRandomHostname);
mUseFloat.setChecked(mProfile.mUseFloat);
mUseCustomConfig.setChecked(mProfile.mUseCustomConfig);
mCustomConfig.setText(mProfile.mCustomConfigOptions);
mPersistent.setChecked(mProfile.mPersistTun);
mConnectretrymax.setValue(mProfile.mConnectRetryMax);
onPreferenceChange(mConnectretrymax, mProfile.mConnectRetryMax);
mConnectretry.setText(mProfile.mConnectRetry);
onPreferenceChange(mConnectretry, mProfile.mConnectRetry);
}
protected void saveSettings() {
mProfile.mUseRandomHostname = mUseRandomHostName.isChecked();
mProfile.mUseFloat = mUseFloat.isChecked();
mProfile.mUseCustomConfig = mUseCustomConfig.isChecked();
mProfile.mCustomConfigOptions = mCustomConfig.getText();
mProfile.mConnectRetryMax = mConnectretrymax.getValue();
mProfile.mPersistTun = mPersistent.isChecked();
mProfile.mConnectRetry = mConnectretry.getText();
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == mConnectretrymax) {
if(newValue==null) {
newValue="5";
}
mConnectretrymax.setDefaultValue(newValue);
for(int i=0;i<mConnectretrymax.getEntryValues().length;i++){
if(mConnectretrymax.getEntryValues().equals(newValue))
mConnectretrymax.setSummary(mConnectretrymax.getEntries()[i]);
}
} else if (preference == mConnectretry) {
if(newValue==null || newValue=="")
newValue="5";
mConnectretry.setSummary(String.format("%s s" , newValue));
}
return true;
}
} | Java |
package de.blinkt.openvpn.fragments;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
import de.blinkt.openvpn.core.ProfileManager;
public class ShowConfigFragment extends Fragment {
private String configtext;
public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
String profileUUID = getArguments().getString(getActivity().getPackageName() + ".profileUUID");
final VpnProfile vp = ProfileManager.get(getActivity(),profileUUID);
View v=inflater.inflate(R.layout.viewconfig, container,false);
final TextView cv = (TextView) v.findViewById(R.id.configview);
int check=vp.checkProfile(getActivity());
if(check!=R.string.no_error_found) {
cv.setText(check);
configtext = getString(check);
}
else {
// Run in own Thread since Keystore does not like to be queried from the main thread
cv.setText("Generating config...");
startGenConfig(vp, cv);
}
return v;
}
private void startGenConfig(final VpnProfile vp, final TextView cv) {
new Thread() {
public void run() {
final String cfg=vp.getConfigFile(getActivity(),false);
configtext= cfg;
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
cv.setText(cfg);
}
});
}
}.start();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.configmenu, menu);
}
private void shareConfig() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, configtext);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.export_config_title));
shareIntent.setType("text/plain");
startActivity(Intent.createChooser(shareIntent, "Export Configfile"));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int itemId = item.getItemId();
if (itemId == R.id.sendConfig) {
shareConfig();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
}
| Java |
package de.blinkt.openvpn.fragments;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceManager;
import android.preference.SwitchPreference;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
public class Settings_IP extends OpenVpnPreferencesFragment implements OnPreferenceChangeListener {
private EditTextPreference mIPv4;
private EditTextPreference mIPv6;
private SwitchPreference mUsePull;
private CheckBoxPreference mOverrideDNS;
private EditTextPreference mSearchdomain;
private EditTextPreference mDNS1;
private EditTextPreference mDNS2;
private CheckBoxPreference mNobind;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
PreferenceManager.setDefaultValues(getActivity(),
R.xml.vpn_ipsettings, false);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.vpn_ipsettings);
mIPv4 = (EditTextPreference) findPreference("ipv4_address");
mIPv6 = (EditTextPreference) findPreference("ipv6_address");
mUsePull = (SwitchPreference) findPreference("usePull");
mOverrideDNS = (CheckBoxPreference) findPreference("overrideDNS");
mSearchdomain =(EditTextPreference) findPreference("searchdomain");
mDNS1 = (EditTextPreference) findPreference("dns1");
mDNS2 = (EditTextPreference) findPreference("dns2");
mNobind = (CheckBoxPreference) findPreference("nobind");
mIPv4.setOnPreferenceChangeListener(this);
mIPv6.setOnPreferenceChangeListener(this);
mDNS1.setOnPreferenceChangeListener(this);
mDNS2.setOnPreferenceChangeListener(this);
mUsePull.setOnPreferenceChangeListener(this);
mOverrideDNS.setOnPreferenceChangeListener(this);
mSearchdomain.setOnPreferenceChangeListener(this);
loadSettings();
}
@Override
protected void loadSettings() {
mUsePull.setChecked(mProfile.mUsePull);
mIPv4.setText(mProfile.mIPv4Address);
mIPv6.setText(mProfile.mIPv6Address);
mDNS1.setText(mProfile.mDNS1);
mDNS2.setText(mProfile.mDNS2);
mOverrideDNS.setChecked(mProfile.mOverrideDNS);
mSearchdomain.setText(mProfile.mSearchDomain);
mNobind.setChecked(mProfile.mNobind);
if (mProfile.mAuthenticationType == VpnProfile.TYPE_STATICKEYS)
mUsePull.setChecked(false);
// Sets Summary
onPreferenceChange(mIPv4, mIPv4.getText());
onPreferenceChange(mIPv6, mIPv6.getText());
onPreferenceChange(mDNS1, mDNS1.getText());
onPreferenceChange(mDNS2, mDNS2.getText());
onPreferenceChange(mSearchdomain, mSearchdomain.getText());
setDNSState();
}
@Override
protected void saveSettings() {
mProfile.mUsePull = mUsePull.isChecked();
mProfile.mIPv4Address = mIPv4.getText();
mProfile.mIPv6Address = mIPv6.getText();
mProfile.mDNS1 = mDNS1.getText();
mProfile.mDNS2 = mDNS2.getText();
mProfile.mOverrideDNS = mOverrideDNS.isChecked();
mProfile.mSearchDomain = mSearchdomain.getText();
mProfile.mNobind = mNobind.isChecked();
}
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if(preference==mIPv4 || preference == mIPv6
|| preference==mDNS1 || preference == mDNS2
|| preference == mSearchdomain
)
preference.setSummary((String)newValue);
if(preference== mUsePull || preference == mOverrideDNS)
if(preference==mOverrideDNS) {
// Set so the function gets the right value
mOverrideDNS.setChecked((Boolean) newValue);
}
setDNSState();
saveSettings();
return true;
}
private void setDNSState() {
boolean enabled;
mOverrideDNS.setEnabled(mUsePull.isChecked());
if(!mUsePull.isChecked())
enabled =true;
else
enabled = mOverrideDNS.isChecked();
mDNS1.setEnabled(enabled);
mDNS2.setEnabled(enabled);
mSearchdomain.setEnabled(enabled);
}
} | Java |
package de.blinkt.openvpn.fragments;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.OpenableColumns;
import android.util.Base64;
import android.util.Log;
import android.webkit.MimeTypeMap;
import de.blinkt.openvpn.VpnProfile;
import junit.framework.Assert;
import java.io.*;
import java.util.TreeSet;
import java.util.Vector;
public class Utils {
@TargetApi(Build.VERSION_CODES.KITKAT)
public static Intent getFilePickerIntent(FileType fileType) {
Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
TreeSet<String> supportedMimeTypes = new TreeSet<String>();
Vector<String> extensions = new Vector<String>();
switch (fileType) {
case PKCS12:
i.setType("application/x-pkcs12");
supportedMimeTypes.add("application/x-pkcs12");
extensions.add("p12");
extensions.add("pfx");
break;
case CLIENT_CERTIFICATE:
case CA_CERTIFICATE:
i.setType("application/x-pem-file");
supportedMimeTypes.add("application/x-x509-ca-cert");
supportedMimeTypes.add("application/x-x509-user-cert");
supportedMimeTypes.add("application/x-pem-file");
supportedMimeTypes.add("text/plain");
extensions.add("pem");
extensions.add("crt");
break;
case KEYFILE:
i.setType("application/x-pem-file");
supportedMimeTypes.add("application/x-pem-file");
supportedMimeTypes.add("application/pkcs8");
// Google drive ....
supportedMimeTypes.add("application/x-iwork-keynote-sffkey");
extensions.add("key");
break;
case TLS_AUTH_FILE:
i.setType("text/plain");
// Backup ....
supportedMimeTypes.add("application/pkcs8");
// Google Drive is kind of crazy .....
supportedMimeTypes.add("application/x-iwork-keynote-sffkey");
extensions.add("txt");
extensions.add("key");
break;
case OVPN_CONFIG:
i.setType("application/x-openvpn-profile");
supportedMimeTypes.add("application/x-openvpn-profile");
supportedMimeTypes.add("application/openvpn-profile");
supportedMimeTypes.add("application/ovpn");
supportedMimeTypes.add("text/plain");
extensions.add("ovpn");
extensions.add("conf");
break;
case USERPW_FILE:
i.setType("text/plain");
supportedMimeTypes.add("text/plain");
break;
}
MimeTypeMap mtm = MimeTypeMap.getSingleton();
for (String ext : extensions) {
String mimeType = mtm.getMimeTypeFromExtension(ext);
if (mimeType != null)
supportedMimeTypes.add(mimeType);
}
// Always add this as fallback
supportedMimeTypes.add("application/octet-stream");
i.putExtra(Intent.EXTRA_MIME_TYPES, supportedMimeTypes.toArray(new String[supportedMimeTypes.size()]));
return i;
}
public enum FileType {
PKCS12(0),
CLIENT_CERTIFICATE(1),
CA_CERTIFICATE(2),
OVPN_CONFIG(3),
KEYFILE(4),
TLS_AUTH_FILE(5),
USERPW_FILE(6);
private int value;
FileType(int i) {
value = i;
}
public static FileType getFileTypeByValue(int value) {
switch (value) {
case 0:
return PKCS12;
case 1:
return CLIENT_CERTIFICATE;
case 2:
return CA_CERTIFICATE;
case 3:
return OVPN_CONFIG;
case 4:
return KEYFILE;
case 5:
return TLS_AUTH_FILE;
case 6:
return USERPW_FILE;
default:
return null;
}
}
public int getValue() {
return value;
}
}
static private byte[] readBytesFromStream(InputStream input) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = input.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
input.close();
return buffer.toByteArray();
}
public static String getFilePickerResult(FileType ft, Intent result, Context c) throws IOException {
Uri uri = result.getData();
if (uri == null)
return null;
byte[] fileData = readBytesFromStream(c.getContentResolver().openInputStream(uri));
String newData = null;
Cursor cursor = c.getContentResolver().query(uri, null, null, null, null);
String prefix = "";
try {
if (cursor!=null && cursor.moveToFirst()) {
int cidx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (cidx != -1) {
String displayName = cursor.getString(cidx);
if (!displayName.contains(VpnProfile.INLINE_TAG) && !displayName.contains(VpnProfile.DISPLAYNAME_TAG))
prefix = VpnProfile.DISPLAYNAME_TAG + displayName;
}
}
} finally {
if(cursor!=null)
cursor.close();
}
switch (ft) {
case PKCS12:
newData = Base64.encodeToString(fileData, Base64.DEFAULT);
break;
default:
newData = new String(fileData, "UTF-8");
break;
}
return prefix + VpnProfile.INLINE_TAG + newData;
}
}
| Java |
package de.blinkt.openvpn.fragments;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Fragment;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.security.KeyChain;
import android.security.KeyChainAliasCallback;
import android.security.KeyChainException;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ToggleButton;
import de.blinkt.openvpn.views.FileSelectLayout;
import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
import de.blinkt.openvpn.R.id;
import de.blinkt.openvpn.core.ProfileManager;
import de.blinkt.openvpn.core.X509Utils;
import java.security.cert.X509Certificate;
public class Settings_Basic extends Fragment implements View.OnClickListener, OnItemSelectedListener, Callback, FileSelectLayout.FileSelectCallback {
private static final int CHOOSE_FILE_OFFSET = 1000;
private static final int UPDATE_ALIAS = 20;
private TextView mServerAddress;
private TextView mServerPort;
private FileSelectLayout mClientCert;
private FileSelectLayout mCaCert;
private FileSelectLayout mClientKey;
private TextView mAliasName;
private TextView mAliasCertificate;
private CheckBox mUseLzo;
private ToggleButton mTcpUdp;
private Spinner mType;
private FileSelectLayout mpkcs12;
private TextView mPKCS12Password;
private Handler mHandler;
private EditText mUserName;
private EditText mPassword;
private View mView;
private VpnProfile mProfile;
private EditText mProfileName;
private EditText mKeyPassword;
private SparseArray<FileSelectLayout> fileselects = new SparseArray<FileSelectLayout>();
private void addFileSelectLayout (FileSelectLayout fsl, Utils.FileType type) {
int i = fileselects.size() + CHOOSE_FILE_OFFSET;
fileselects.put(i, fsl);
fsl.setCaller(this, i, type);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String profileUuid = getArguments().getString(getActivity().getPackageName() + ".profileUUID");
mProfile=ProfileManager.get(getActivity(),profileUuid);
getActivity().setTitle(getString(R.string.edit_profile_title, mProfile.getName()));
}
private void setKeystoreCertficate()
{
new Thread() {
public void run() {
String certstr="";
try {
X509Certificate cert = KeyChain.getCertificateChain(getActivity(), mProfile.mAlias)[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
{
if (isInHardwareKeystore())
certstr+=getString(R.string.hwkeychain);
}
}
certstr+=X509Utils.getCertificateFriendlyName(cert);
} catch (Exception e) {
certstr="Could not get certificate from Keystore: " +e.getLocalizedMessage();
}
final String certStringCopy=certstr;
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
mAliasCertificate.setText(certStringCopy);
}
});
}
}.start();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private boolean isInHardwareKeystore() throws KeyChainException, InterruptedException {
String algorithm = KeyChain.getPrivateKey(getActivity(), mProfile.mAlias).getAlgorithm();
return KeyChain.isBoundKeyAlgorithm(algorithm);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.basic_settings,container,false);
mProfileName = (EditText) mView.findViewById(R.id.profilename);
mServerAddress = (TextView) mView.findViewById(R.id.address);
mServerPort = (TextView) mView.findViewById(R.id.port);
mClientCert = (FileSelectLayout) mView.findViewById(R.id.certselect);
mClientKey = (FileSelectLayout) mView.findViewById(R.id.keyselect);
mCaCert = (FileSelectLayout) mView.findViewById(R.id.caselect);
mpkcs12 = (FileSelectLayout) mView.findViewById(R.id.pkcs12select);
mUseLzo = (CheckBox) mView.findViewById(R.id.lzo);
mTcpUdp = (ToggleButton) mView.findViewById(id.tcpudp);
mType = (Spinner) mView.findViewById(R.id.type);
mPKCS12Password = (TextView) mView.findViewById(R.id.pkcs12password);
mAliasName = (TextView) mView.findViewById(R.id.aliasname);
mAliasCertificate = (TextView) mView.findViewById(id.alias_certificate);
mUserName = (EditText) mView.findViewById(R.id.auth_username);
mPassword = (EditText) mView.findViewById(R.id.auth_password);
mKeyPassword = (EditText) mView.findViewById(R.id.key_password);
addFileSelectLayout(mCaCert, Utils.FileType.CA_CERTIFICATE);
addFileSelectLayout(mClientCert, Utils.FileType.CLIENT_CERTIFICATE);
addFileSelectLayout(mClientKey, Utils.FileType.KEYFILE);
addFileSelectLayout(mpkcs12, Utils.FileType.PKCS12);
mCaCert.setShowClear();
mType.setOnItemSelectedListener(this);
mView.findViewById(R.id.select_keystore_button).setOnClickListener(this);
if (mHandler == null) {
mHandler = new Handler(this);
}
return mView;
}
@Override
public void onStart() {
super.onStart();
String profileUuid =getArguments().getString(getActivity().getPackageName() + ".profileUUID");
mProfile=ProfileManager.get(getActivity(),profileUuid);
loadPreferences();
}
@Override
public void onActivityResult(int request, int result, Intent data) {
if (result == Activity.RESULT_OK && request >= CHOOSE_FILE_OFFSET) {
FileSelectLayout fsl = fileselects.get(request);
fsl.parseResponse(data, getActivity());
savePreferences();
// Private key files may result in showing/hiding the private key password dialog
if(fsl==mClientKey) {
changeType(mType.getSelectedItemPosition());
}
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent == mType) {
changeType(position);
}
}
@Override
public void onPause() {
super.onPause();
savePreferences();
}
private void changeType(int type){
// hide everything
mView.findViewById(R.id.pkcs12).setVisibility(View.GONE);
mView.findViewById(R.id.certs).setVisibility(View.GONE);
mView.findViewById(R.id.statickeys).setVisibility(View.GONE);
mView.findViewById(R.id.keystore).setVisibility(View.GONE);
mView.findViewById(R.id.cacert).setVisibility(View.GONE);
mView.findViewById(R.id.userpassword).setVisibility(View.GONE);
mView.findViewById(R.id.key_password_layout).setVisibility(View.GONE);
// Fall through are by design
switch(type) {
case VpnProfile.TYPE_USERPASS_CERTIFICATES:
mView.findViewById(R.id.userpassword).setVisibility(View.VISIBLE);
case VpnProfile.TYPE_CERTIFICATES:
mView.findViewById(R.id.certs).setVisibility(View.VISIBLE);
mView.findViewById(R.id.cacert).setVisibility(View.VISIBLE);
if(mProfile.requireTLSKeyPassword())
mView.findViewById(R.id.key_password_layout).setVisibility(View.VISIBLE);
break;
case VpnProfile.TYPE_USERPASS_PKCS12:
mView.findViewById(R.id.userpassword).setVisibility(View.VISIBLE);
case VpnProfile.TYPE_PKCS12:
mView.findViewById(R.id.pkcs12).setVisibility(View.VISIBLE);
break;
case VpnProfile.TYPE_STATICKEYS:
mView.findViewById(R.id.statickeys).setVisibility(View.VISIBLE);
break;
case VpnProfile.TYPE_USERPASS_KEYSTORE:
mView.findViewById(R.id.userpassword).setVisibility(View.VISIBLE);
case VpnProfile.TYPE_KEYSTORE:
mView.findViewById(R.id.keystore).setVisibility(View.VISIBLE);
mView.findViewById(R.id.cacert).setVisibility(View.VISIBLE);
break;
case VpnProfile.TYPE_USERPASS:
mView.findViewById(R.id.userpassword).setVisibility(View.VISIBLE);
mView.findViewById(R.id.cacert).setVisibility(View.VISIBLE);
break;
}
}
private void loadPreferences() {
mProfileName.setText(mProfile.mName);
mClientCert.setData(mProfile.mClientCertFilename, getActivity());
mClientKey.setData(mProfile.mClientKeyFilename, getActivity());
mCaCert.setData(mProfile.mCaFilename, getActivity());
mUseLzo.setChecked(mProfile.mUseLzo);
mServerPort.setText(mProfile.mServerPort);
mServerAddress.setText(mProfile.mServerName);
mTcpUdp.setChecked(mProfile.mUseUdp);
mType.setSelection(mProfile.mAuthenticationType);
mpkcs12.setData(mProfile.mPKCS12Filename, getActivity());
mPKCS12Password.setText(mProfile.mPKCS12Password);
mUserName.setText(mProfile.mUsername);
mPassword.setText(mProfile.mPassword);
mKeyPassword.setText(mProfile.mKeyPassword);
setAlias();
}
void savePreferences() {
mProfile.mName = mProfileName.getText().toString();
mProfile.mCaFilename = mCaCert.getData();
mProfile.mClientCertFilename = mClientCert.getData();
mProfile.mClientKeyFilename = mClientKey.getData();
mProfile.mUseLzo = mUseLzo.isChecked();
mProfile.mServerPort =mServerPort.getText().toString();
mProfile.mServerName = mServerAddress.getText().toString();
mProfile.mUseUdp = mTcpUdp.isChecked();
mProfile.mAuthenticationType = mType.getSelectedItemPosition();
mProfile.mPKCS12Filename = mpkcs12.getData();
mProfile.mPKCS12Password = mPKCS12Password.getText().toString();
mProfile.mPassword = mPassword.getText().toString();
mProfile.mUsername = mUserName.getText().toString();
mProfile.mKeyPassword = mKeyPassword.getText().toString();
}
private void setAlias() {
if(mProfile.mAlias == null) {
mAliasName.setText(R.string.client_no_certificate);
mAliasCertificate.setText("");
} else {
mAliasCertificate.setText("Loading certificate from Keystore...");
mAliasName.setText(mProfile.mAlias);
setKeystoreCertficate();
}
}
public void showCertDialog () {
try {
KeyChain.choosePrivateKeyAlias(getActivity(),
new KeyChainAliasCallback() {
public void alias(String alias) {
// Credential alias selected. Remember the alias selection for future use.
mProfile.mAlias=alias;
mHandler.sendEmptyMessage(UPDATE_ALIAS);
}
},
new String[] {"RSA"}, // List of acceptable key types. null for any
null, // issuer, null for any
mProfile.mServerName, // host name of server requesting the cert, null if unavailable
-1, // port of server requesting the cert, -1 if unavailable
mProfile.mAlias); // alias to preselect, null if unavailable
} catch (ActivityNotFoundException anf) {
Builder ab = new AlertDialog.Builder(getActivity());
ab.setTitle(R.string.broken_image_cert_title);
ab.setMessage(R.string.broken_image_cert);
ab.setPositiveButton(android.R.string.ok, null);
ab.show();
}
}
@Override
public void onClick(View v) {
if (v == mView.findViewById(R.id.select_keystore_button)) {
showCertDialog();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
savePreferences();
if(mProfile!=null) {
outState.putString(getActivity().getPackageName() + "profileUUID", mProfile.getUUID().toString());
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public boolean handleMessage(Message msg) {
setAlias();
return true;
}
}
| Java |
package de.blinkt.openvpn.fragments;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.view.*;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import de.blinkt.openvpn.*;
import de.blinkt.openvpn.activities.ConfigConverter;
import de.blinkt.openvpn.activities.FileSelect;
import de.blinkt.openvpn.activities.VPNPreferences;
import de.blinkt.openvpn.core.ProfileManager;
import java.util.Collection;
import java.util.Comparator;
import java.util.TreeSet;
public class VPNProfileList extends ListFragment {
public final static int RESULT_VPN_DELETED = Activity.RESULT_FIRST_USER;
private static final int MENU_ADD_PROFILE = Menu.FIRST;
private static final int START_VPN_CONFIG = 92;
private static final int SELECT_PROFILE = 43;
private static final int IMPORT_PROFILE = 231;
private static final int FILE_PICKER_RESULT = 392;
private static final int MENU_IMPORT_PROFILE = Menu.FIRST +1;
class VPNArrayAdapter extends ArrayAdapter<VpnProfile> {
public VPNArrayAdapter(Context context, int resource,
int textViewResourceId) {
super(context, resource, textViewResourceId);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
View titleview = v.findViewById(R.id.vpn_list_item_left);
titleview.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
VpnProfile profile =(VpnProfile) getListAdapter().getItem(position);
startVPN(profile);
}
});
View settingsview = v.findViewById(R.id.quickedit_settings);
settingsview.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
VpnProfile editProfile = (VpnProfile) getListAdapter().getItem(position);
editVPN(editProfile);
}
});
return v;
}
}
private ArrayAdapter<VpnProfile> mArrayadapter;
protected VpnProfile mEditProfile=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
class MiniImageGetter implements ImageGetter {
@Override
public Drawable getDrawable(String source) {
Drawable d=null;
if ("ic_menu_add".equals(source))
d = getActivity().getResources().getDrawable(android.R.drawable.ic_menu_add);
else if("ic_menu_archive".equals(source))
d = getActivity().getResources().getDrawable(R.drawable.ic_menu_archive);
if(d!=null) {
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
}else{
return null;
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.vpn_profile_list, container,false);
TextView newvpntext = (TextView) v.findViewById(R.id.add_new_vpn_hint);
TextView importvpntext = (TextView) v.findViewById(R.id.import_vpn_hint);
newvpntext.setText(Html.fromHtml(getString(R.string.add_new_vpn_hint),new MiniImageGetter(),null));
importvpntext.setText(Html.fromHtml(getString(R.string.vpn_import_hint),new MiniImageGetter(),null));
return v;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter();
}
static class VpnProfileNameComparator implements Comparator<VpnProfile> {
@Override
public int compare(VpnProfile lhs, VpnProfile rhs) {
if (lhs == rhs)
// Catches also both null
return 0;
if (lhs == null)
return -1;
if (rhs == null)
return 1;
if (lhs.mName == null)
return -1;
if (rhs.mName == null)
return 1;
return lhs.mName.compareTo(rhs.mName);
}
}
private void setListAdapter() {
mArrayadapter = new VPNArrayAdapter(getActivity(),R.layout.vpn_list_item,R.id.vpn_item_title);
Collection<VpnProfile> allvpn = getPM().getProfiles();
TreeSet<VpnProfile> sortedset = new TreeSet<VpnProfile>(new VpnProfileNameComparator());
sortedset.addAll(allvpn);
mArrayadapter.addAll(sortedset);
setListAdapter(mArrayadapter);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.add(0, MENU_ADD_PROFILE, 0 , R.string.menu_add_profile)
.setIcon(android.R.drawable.ic_menu_add)
.setAlphabeticShortcut('a')
.setTitleCondensed(getActivity().getString(R.string.add))
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
menu.add(0, MENU_IMPORT_PROFILE, 0, R.string.menu_import)
.setIcon(R.drawable.ic_menu_archive)
.setAlphabeticShortcut('i')
.setTitleCondensed(getActivity().getString(R.string.menu_import_short))
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT );
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int itemId = item.getItemId();
if (itemId == MENU_ADD_PROFILE) {
onAddProfileClicked();
return true;
} else if (itemId == MENU_IMPORT_PROFILE) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
startFilePicker();
else
startImportConfig();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private void startFilePicker() {
Intent i = Utils.getFilePickerIntent(Utils.FileType.OVPN_CONFIG);
startActivityForResult(i, FILE_PICKER_RESULT);
}
private void startImportConfig() {
Intent intent = new Intent(getActivity(),FileSelect.class);
intent.putExtra(FileSelect.NO_INLINE_SELECTION, true);
intent.putExtra(FileSelect.WINDOW_TITLE, R.string.import_configuration_file);
startActivityForResult(intent, SELECT_PROFILE);
}
private void onAddProfileClicked() {
Context context = getActivity();
if (context != null) {
final EditText entry = new EditText(context);
entry.setSingleLine();
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(R.string.menu_add_profile);
dialog.setMessage(R.string.add_profile_name_prompt);
dialog.setView(entry);
dialog.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String name = entry.getText().toString();
if (getPM().getProfileByName(name)==null) {
VpnProfile profile = new VpnProfile(name);
addProfile(profile);
editVPN(profile);
} else {
Toast.makeText(getActivity(), R.string.duplicate_profile_name, Toast.LENGTH_LONG).show();
}
}
});
dialog.setNegativeButton(android.R.string.cancel, null);
dialog.create().show();
}
}
private void addProfile(VpnProfile profile) {
getPM().addProfile(profile);
getPM().saveProfileList(getActivity());
getPM().saveProfile(getActivity(),profile);
mArrayadapter.add(profile);
}
private ProfileManager getPM() {
return ProfileManager.getInstance(getActivity());
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_VPN_DELETED){
if(mArrayadapter != null && mEditProfile !=null)
mArrayadapter.remove(mEditProfile);
}
if(resultCode != Activity.RESULT_OK)
return;
if (requestCode == START_VPN_CONFIG) {
String configuredVPN = data.getStringExtra(VpnProfile.EXTRA_PROFILEUUID);
VpnProfile profile = ProfileManager.get(getActivity(),configuredVPN);
getPM().saveProfile(getActivity(), profile);
// Name could be modified, reset List adapter
setListAdapter();
} else if(requestCode== SELECT_PROFILE) {
String fileData = data.getStringExtra(FileSelect.RESULT_DATA);
Uri uri = new Uri.Builder().path(fileData).scheme("file").build();
startConfigImport(uri);
} else if(requestCode == IMPORT_PROFILE) {
String profileUUID = data.getStringExtra(VpnProfile.EXTRA_PROFILEUUID);
mArrayadapter.add(ProfileManager.get(getActivity(), profileUUID));
} else if(requestCode == FILE_PICKER_RESULT) {
if (data != null) {
Uri uri = data.getData();
startConfigImport(uri);
}
}
}
private void startConfigImport(Uri uri) {
Intent startImport = new Intent(getActivity(),ConfigConverter.class);
startImport.setAction(ConfigConverter.IMPORT_PROFILE);
startImport.setData(uri);
startActivityForResult(startImport, IMPORT_PROFILE);
}
private void editVPN(VpnProfile profile) {
mEditProfile =profile;
Intent vprefintent = new Intent(getActivity(),VPNPreferences.class)
.putExtra(getActivity().getPackageName() + ".profileUUID", profile.getUUID().toString());
startActivityForResult(vprefintent,START_VPN_CONFIG);
}
private void startVPN(VpnProfile profile) {
getPM().saveProfile(getActivity(), profile);
Intent intent = new Intent(getActivity(),LaunchVPN.class);
intent.putExtra(LaunchVPN.EXTRA_KEY, profile.getUUID().toString());
intent.setAction(Intent.ACTION_MAIN);
startActivity(intent);
}
}
| Java |
package de.blinkt.openvpn;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.VpnService;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.*;
import de.blinkt.openvpn.activities.LogWindow;
import de.blinkt.openvpn.core.VpnStatus;
import de.blinkt.openvpn.core.VpnStatus.ConnectionStatus;
import de.blinkt.openvpn.core.ProfileManager;
import de.blinkt.openvpn.core.VPNLaunchHelper;
/**
* 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 LaunchVPN extends Activity {
public static final String EXTRA_KEY = "de.blinkt.openvpn.shortcutProfileUUID";
public static final String EXTRA_NAME = "de.blinkt.openvpn.shortcutProfileName";
public static final String EXTRA_HIDELOG = "de.blinkt.openvpn.showNoLogWindow";
private static final int START_VPN_PROFILE= 70;
private ProfileManager mPM;
private VpnProfile mSelectedProfile;
private boolean mhideLog=false;
private boolean mCmfixed=false;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mPM =ProfileManager.getInstance(this);
}
@Override
protected void onStart() {
super.onStart();
// Resolve the intent
final Intent intent = getIntent();
final String action = intent.getAction();
// If the intent is a request to create a shortcut, we'll do that and exit
if(Intent.ACTION_MAIN.equals(action)) {
// we got called to be the starting point, most likely a shortcut
String shortcutUUID = intent.getStringExtra( EXTRA_KEY);
String shortcutName = intent.getStringExtra( EXTRA_NAME);
mhideLog = intent.getBooleanExtra(EXTRA_HIDELOG, false);
VpnProfile profileToConnect = ProfileManager.get(this,shortcutUUID);
if(shortcutName != null && profileToConnect ==null)
profileToConnect = ProfileManager.getInstance(this).getProfileByName(shortcutName);
if(profileToConnect ==null) {
VpnStatus.logError(R.string.shortcut_profile_notfound);
// show Log window to display error
showLogWindow();
finish();
return;
}
mSelectedProfile = profileToConnect;
launchVPN();
}
}
private void askForPW(final int type) {
final EditText entry = new EditText(this);
final View userpwlayout = getLayoutInflater().inflate(R.layout.userpass, null);
entry.setSingleLine();
entry.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
entry.setTransformationMethod(new PasswordTransformationMethod());
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Need " + getString(type));
dialog.setMessage("Enter the password for profile " + mSelectedProfile.mName);
if (type == R.string.password) {
((EditText)userpwlayout.findViewById(R.id.username)).setText(mSelectedProfile.mUsername);
((EditText)userpwlayout.findViewById(R.id.password)).setText(mSelectedProfile.mPassword);
((CheckBox)userpwlayout.findViewById(R.id.save_password)).setChecked(!TextUtils.isEmpty(mSelectedProfile.mPassword));
((CheckBox)userpwlayout.findViewById(R.id.show_password)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
((EditText)userpwlayout.findViewById(R.id.password)).setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
else
((EditText)userpwlayout.findViewById(R.id.password)).setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
});
dialog.setView(userpwlayout);
} else {
dialog.setView(entry);
}
AlertDialog.Builder builder = dialog.setPositiveButton(android.R.string.ok,
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (type == R.string.password) {
mSelectedProfile.mUsername = ((EditText) userpwlayout.findViewById(R.id.username)).getText().toString();
String pw = ((EditText) userpwlayout.findViewById(R.id.password)).getText().toString();
if (((CheckBox) userpwlayout.findViewById(R.id.save_password)).isChecked()) {
mSelectedProfile.mPassword=pw;
} else {
mSelectedProfile.mPassword=null;
mSelectedProfile.mTransientPW = pw;
}
} else {
mSelectedProfile.mTransientPCKS12PW = entry.getText().toString();
}
onActivityResult(START_VPN_PROFILE, Activity.RESULT_OK, null);
}
});
dialog.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
VpnStatus.updateStateString("USER_VPN_PASSWORD_CANCELLED", "", R.string.state_user_vpn_password_cancelled,
ConnectionStatus.LEVEL_NOTCONNECTED);
finish();
}
});
dialog.create().show();
}
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==START_VPN_PROFILE) {
if(resultCode == Activity.RESULT_OK) {
int needpw = mSelectedProfile.needUserPWInput();
if(needpw !=0) {
VpnStatus.updateStateString("USER_VPN_PASSWORD", "", R.string.state_user_vpn_password,
ConnectionStatus.LEVEL_WAITING_FOR_USER_INPUT);
askForPW(needpw);
} else {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean showlogwindow = prefs.getBoolean("showlogwindow", true);
if(!mhideLog && showlogwindow)
showLogWindow();
new startOpenVpnThread().start();
}
} else if (resultCode == Activity.RESULT_CANCELED) {
// User does not want us to start, so we just vanish
VpnStatus.updateStateString("USER_VPN_PERMISSION_CANCELLED", "", R.string.state_user_vpn_permission_cancelled,
ConnectionStatus.LEVEL_NOTCONNECTED);
finish();
}
}
}
void showLogWindow() {
Intent startLW = new Intent(getBaseContext(),LogWindow.class);
startLW.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(startLW);
}
void showConfigErrorDialog(int vpnok) {
AlertDialog.Builder d = new AlertDialog.Builder(this);
d.setTitle(R.string.config_error_found);
d.setMessage(vpnok);
d.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
d.show();
}
void launchVPN () {
int vpnok = mSelectedProfile.checkProfile(this);
if(vpnok!= R.string.no_error_found) {
showConfigErrorDialog(vpnok);
return;
}
Intent intent = VpnService.prepare(this);
// Check if we want to fix /dev/tun
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean usecm9fix = prefs.getBoolean("useCM9Fix", false);
boolean loadTunModule = prefs.getBoolean("loadTunModule", false);
if(loadTunModule)
execeuteSUcmd("insmod /system/lib/modules/tun.ko");
if(usecm9fix && !mCmfixed ) {
execeuteSUcmd("chown system /dev/tun");
}
if (intent != null) {
VpnStatus.updateStateString("USER_VPN_PERMISSION", "", R.string.state_user_vpn_permission,
ConnectionStatus.LEVEL_WAITING_FOR_USER_INPUT);
// Start the query
try {
startActivityForResult(intent, START_VPN_PROFILE);
} catch (ActivityNotFoundException ane) {
// Shame on you Sony! At least one user reported that
// an official Sony Xperia Arc S image triggers this exception
VpnStatus.logError(R.string.no_vpn_support_image);
showLogWindow();
}
} else {
onActivityResult(START_VPN_PROFILE, Activity.RESULT_OK, null);
}
}
private void execeuteSUcmd(String command) {
ProcessBuilder pb = new ProcessBuilder("su","-c",command);
try {
Process p = pb.start();
int ret = p.waitFor();
if(ret ==0)
mCmfixed=true;
} catch (InterruptedException e) {
VpnStatus.logException("SU command", e);
} catch (IOException e) {
VpnStatus.logException("SU command", e);
}
}
private class startOpenVpnThread extends Thread {
@Override
public void run() {
VPNLaunchHelper.startOpenVpn(mSelectedProfile, getBaseContext());
finish();
}
}
}
| Java |
package com.app.service.impl;
import com.app.service.CalculeService;
public class CalculeServiceImpl implements CalculeService{
@Override
public int somme(int num1, int num2) {
int som=num1+num2;
return som;
}
}
| Java |
package pl.wroc.pwr.psi.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.psi.entity.ElementPlanu;
import pl.wroc.pwr.psi.repository.ElementPlanuRepository;
@Service
public class ElementPlanuService {
@Autowired
private ElementPlanuRepository elementPlanuRepository;
public List<ElementPlanu> findAllElementPlanu() {
return elementPlanuRepository.findAll();
}
}
| Java |
package pl.wroc.pwr.psi.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.psi.entity.Synonim;
import pl.wroc.pwr.psi.repository.SlowoKluczoweRepository;
import pl.wroc.pwr.psi.repository.SynonimRepository;
/**
*
* @author wposlednicka
*
*/
@Service
public class SynonimService {
@Autowired
private SynonimRepository synonimRepository;
@Autowired
private SlowoKluczoweRepository slowoKluczoweRepository;
public Synonim findSynonimById(Integer id){
return synonimRepository.findOne(id);
}
public void deleteSynonimById(Integer id){
Synonim synonim = synonimRepository.findOne(id);
synonim.setSlowoKluczowe(null);
synonimRepository.save(synonim);
synonimRepository.delete(id);
}
}
| Java |
package pl.wroc.pwr.psi.service;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.psi.entity.PytanieOtwarte;
import pl.wroc.pwr.psi.entity.SlowoKluczowe;
import pl.wroc.pwr.psi.entity.SlowoKluczoweToPytanieOtwarte;
import pl.wroc.pwr.psi.entity.Szablon;
import pl.wroc.pwr.psi.repository.SlowoKluczoweToPytanieOtwarteRepository;
import pl.wroc.pwr.psi.repository.SzablonRepository;
@Service
public class SzablonService {
@Autowired
private SzablonRepository szablonRepository;
@Autowired
private SlowoKluczoweToPytanieOtwarteRepository slowoKluczoweToPytanieOtwarteRepository;
@Autowired
private DefinicjaSynonimowService definicjaSynonimowService;
@Autowired
private PytanieOtwarteService pytanieOtwarteService;
public List<Szablon> findAllSzablon() {
return szablonRepository.findAll();
}
public Szablon findSzablonById(Integer id)
{
return szablonRepository.findOne(id);
}
public Set<SlowoKluczowe> findSlowoKluczoweByPytanie(Integer idPytania) {
PytanieOtwarte pytanieOtwarte = pytanieOtwarteService.findPytanieOtwarteById(idPytania);
Set<SlowoKluczoweToPytanieOtwarte> slowoKluczowePytanie = pytanieOtwarte.getSlowoKluczowes();
Set<SlowoKluczowe> solwaKluczowe = new HashSet<SlowoKluczowe>();
for (SlowoKluczoweToPytanieOtwarte skp : slowoKluczowePytanie) {
solwaKluczowe.add(skp.getSlowoKluczowe());
}
return solwaKluczowe;
}
public SlowoKluczowe dodajSlowoKluczoweToPytanie(Integer pytanieId, Integer skId) {
SlowoKluczowe sk = definicjaSynonimowService.findSlowoKluczoweById(skId);
PytanieOtwarte po = pytanieOtwarteService.findPytanieOtwarteById(pytanieId);
SlowoKluczoweToPytanieOtwarte skp = new SlowoKluczoweToPytanieOtwarte();
skp.setSlowoKluczowe(sk);
skp.setPytanieOtwarte(po);
slowoKluczoweToPytanieOtwarteRepository.save(skp);
return skp.getSlowoKluczowe();
}
public void usunSlowoKluczoweToPytanie(Integer pytanieId, Integer skId) {
PytanieOtwarte pytanieOtwarte = pytanieOtwarteService.findPytanieOtwarteById(pytanieId);
Set<SlowoKluczoweToPytanieOtwarte> slowoKluszowePytanie = pytanieOtwarte.getSlowoKluczowes();
SlowoKluczoweToPytanieOtwarte skpToRemove = getSlowoKluczoweToPytanieOtwarteBySlowoKluczowe(slowoKluszowePytanie, skId);
skpToRemove.setPytanieOtwarte(null);
skpToRemove.setSlowoKluczowe(null);
slowoKluczoweToPytanieOtwarteRepository.save(skpToRemove);
slowoKluczoweToPytanieOtwarteRepository.delete(skpToRemove);
}
private SlowoKluczoweToPytanieOtwarte getSlowoKluczoweToPytanieOtwarteBySlowoKluczowe(Set<SlowoKluczoweToPytanieOtwarte> slowoKluszowePytanie, Integer skId) {
for (SlowoKluczoweToPytanieOtwarte skp : slowoKluszowePytanie) {
if(skp.getSlowoKluczowe().getId().equals(skId)) {
return skp;
}
}
return null;
}
}
| Java |
package pl.wroc.pwr.psi.service;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.psi.entity.SlowoKluczowe;
import pl.wroc.pwr.psi.entity.Synonim;
import pl.wroc.pwr.psi.repository.SlowoKluczoweRepository;
import pl.wroc.pwr.psi.repository.SynonimRepository;
/**
*
* @author wposlednicka
*
*/
@Service
public class DefinicjaSynonimowService {
@Autowired
private SlowoKluczoweRepository slowoKluczoweRepository;
@Autowired
private SynonimRepository synonimRepository;
public SlowoKluczowe findSlowoKluczoweById(Integer id){
return slowoKluczoweRepository.findOne(id);
}
public List<SlowoKluczowe> findAllSlowoKluczowe() {
return slowoKluczoweRepository.findAll();
}
public Integer utworzNoweSlowoKluczowe(String nazwa, List<String> synonimy) {
SlowoKluczowe slowoKluczowe = new SlowoKluczowe();
slowoKluczowe.setNazwa(nazwa);
SlowoKluczowe save = slowoKluczoweRepository.save(slowoKluczowe);
for (String synonimStr : synonimy) {
Synonim synonim = new Synonim();
synonim.setSynonim(synonimStr);
synonim.setSlowoKluczowe(slowoKluczowe);
saveSynonim(synonim);
}
return save.getId();
}
public void deleteSlowoKluczoweById(Integer id){
slowoKluczoweRepository.delete(id);
}
public Collection<SlowoKluczowe> findSlowaKluczowe() {
return slowoKluczoweRepository.findAll();
}
public Integer saveSynonim(Synonim synonim) {
Synonim save = synonimRepository.save(synonim);
return save.getId();
}
public boolean istniejeSlowoKluczowe(String sk) {
List<SlowoKluczowe> allSKs = slowoKluczoweRepository.findAll();
for (SlowoKluczowe slowoKluczowe : allSKs) {
if(sk.equals(slowoKluczowe.getNazwa())) {
return true;
}
}
return false;
}
public void updateSlowoKluczowe(SlowoKluczowe sk) {
slowoKluczoweRepository.saveAndFlush(sk);
}
public void zmienNazweSlowoKluczowe(Integer skId, String nowaNazwa) {
SlowoKluczowe sk = slowoKluczoweRepository.findOne(skId);
sk.setNazwa(nowaNazwa);
slowoKluczoweRepository.save(sk);
}
}
| Java |
package pl.wroc.pwr.psi.service;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.psi.entity.PytanieOtwarte;
import pl.wroc.pwr.psi.repository.PytanieOtwarteRepository;
/**
*
* @author wposlednicka
*
*/
@Service
public class PytanieOtwarteService {
@Autowired
private PytanieOtwarteRepository pytanieOtwarteRepository;
public PytanieOtwarte findPytanieOtwarteById(Integer id) {
return pytanieOtwarteRepository.findOne(id);
}
public Integer savePytanieOtwarte(PytanieOtwarte pytanieOtwarte) {
PytanieOtwarte save = pytanieOtwarteRepository.save(pytanieOtwarte);
return save.getId();
}
public void deletePytanieOtwarteById(Integer id) {
pytanieOtwarteRepository.delete(id);
}
public List<PytanieOtwarte> findAllPytanieOtwarte() {
return pytanieOtwarteRepository.findAll();
}
}
| Java |
package pl.wroc.pwr.psi.service;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.TreeMap;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.psi.entity.Opcja;
import pl.wroc.pwr.psi.entity.PytanieOtwarte;
import pl.wroc.pwr.psi.entity.PytanieOtwarteToSzablon;
import pl.wroc.pwr.psi.entity.PytanieToSzablon;
import pl.wroc.pwr.psi.entity.PytanieZamkniete;
import pl.wroc.pwr.psi.entity.PytanieZamknieteToSzablon;
import pl.wroc.pwr.psi.entity.Szablon;
import pl.wroc.pwr.psi.repository.OpcjaRepository;
import pl.wroc.pwr.psi.repository.PytanieOtwarteRepository;
import pl.wroc.pwr.psi.repository.PytanieOtwarteToSzablonRepository;
import pl.wroc.pwr.psi.repository.PytanieToSzablonRepository;
import pl.wroc.pwr.psi.repository.PytanieZamknieteRepository;
import pl.wroc.pwr.psi.repository.PytanieZamknieteToSzablonRepository;
import pl.wroc.pwr.psi.repository.SzablonRepository;
@Service
public class TworzenieSzablonuService {
@Autowired
private SzablonRepository szablonRepository;
@Autowired
private PytanieZamknieteRepository pytanieZamknieteRepository;
@Autowired
private PytanieOtwarteRepository pytanieOtwarteRepository;
@Autowired
private PytanieToSzablonRepository pytanieToSzablonRepository;
@Autowired
private PytanieZamknieteToSzablonRepository pytanieZamknieteToSzablonRepository;
@Autowired
private PytanieOtwarteToSzablonRepository pytanieOtwarteToSzablonRepository;
@Autowired
private OpcjaRepository opcjaRepository;
public int dodajSzablon(String nazwa) {
Szablon szablon = new Szablon();
szablon.setNazwa(nazwa);
szablonRepository.save(szablon);
return szablon.getId();
}
public Szablon findSzablonById(int id) {
return szablonRepository.findOne(id);
}
public Szablon findSzablonByName(String name) {
Szablon sz = new Szablon();
List<Szablon> szablony = szablonRepository.findAll();
for(Szablon szablon: szablony){
if(szablon.getNazwa().equals(name)){
sz= szablon;
}
}
return sz;
}
public PytanieZamkniete findPytanieZamknieteById(int id) {
return pytanieZamknieteRepository.findOne(id);
}
public PytanieOtwarte findPytanieOtwarteById(int id) {
return pytanieOtwarteRepository.findOne(id);
}
public PytanieOtwarteToSzablon findPytanieOtwarteFromSzablon(int idSzablonu, int idPytania) {
Set<PytanieOtwarteToSzablon> pytania = szablonRepository.findOne(
idSzablonu).getPytaniaOtwarte();
PytanieOtwarteToSzablon pots =new PytanieOtwarteToSzablon();
for (PytanieOtwarteToSzablon pytanie : pytania) {
if(pytanie.getSzablon().getId().intValue()==idSzablonu && pytanie.getPytanieOtwarte().getId().intValue()==idPytania){
pots = pytanie;
}
}
return pots;
}
public PytanieZamknieteToSzablon findPytanieZamknieteFromSzablon(int idSzablonu, int idPytania) {
Set<PytanieZamknieteToSzablon> pytania = szablonRepository.findOne(
idSzablonu).getPytaniaZamkniete();
PytanieZamknieteToSzablon pzts =new PytanieZamknieteToSzablon();
for (PytanieZamknieteToSzablon pytanie : pytania) {
if(pytanie.getSzablon().getId().intValue()==idSzablonu && pytanie.getPytanieZamkniete().getId().intValue()==idPytania){
pzts = pytanie;
}
}
return pzts;
}
public void dodajPytanieZamknieteDoSzablonu(int pytanieId,
int szablonId) {
Szablon szablon = findSzablonById(szablonId);
PytanieZamkniete pytanieZamkniete = findPytanieZamknieteById(pytanieId);
PytanieZamknieteToSzablon pzts = new PytanieZamknieteToSzablon();
pzts.setSzablon(szablon);
pzts.setPytanieZamkniete(pytanieZamkniete);
pytanieZamknieteToSzablonRepository.save(pzts);
PytanieToSzablon pts = new PytanieToSzablon();
pts.setSzablon(szablon);
pts.setPytanieZamkniete(pytanieZamkniete);
pytanieToSzablonRepository.save(pts);
}
public void dodajPytanieOtwarteDoSzablonu(int pytanieId,
int szablonId) {
Szablon szablon = findSzablonById(szablonId);
PytanieOtwarte pytanieOtwarte = findPytanieOtwarteById(pytanieId);
PytanieOtwarteToSzablon pots = new PytanieOtwarteToSzablon();
pots.setSzablon(szablon);
pots.setPytanieOtwarte(pytanieOtwarte);
pytanieOtwarteToSzablonRepository.save(pots);
PytanieToSzablon pts = new PytanieToSzablon();
pts.setSzablon(szablon);
pts.setPytanieOtwarte(pytanieOtwarte);
pytanieToSzablonRepository.save(pts);
}
public int dodajPytanieZamkniete(String tresc) {
PytanieZamkniete pytanie = new PytanieZamkniete();
pytanie.setTresc(tresc);
pytanieZamknieteRepository.save(pytanie);
return pytanie.getId();
}
public int dodajPytanieOtwarte(String tresc) {
PytanieOtwarte pytanie = new PytanieOtwarte();
pytanie.setTresc(tresc);
pytanieOtwarteRepository.save(pytanie);
return pytanie.getId();
}
public void dodajOpcje(int pytanieZamknieteId, String[] opcje) {
PytanieZamkniete pytanieZamkniete = (PytanieZamkniete) findPytanieZamknieteById(pytanieZamknieteId);
pytanieZamknieteRepository.save(pytanieZamkniete);
Opcja opcja;
Set<Opcja> opcjeSet = new HashSet<Opcja>();
for (String tresc : opcje) {
opcja = new Opcja();
opcja.setTresc(tresc);
opcjeSet.add(opcja);
}
for (Opcja op : opcjeSet) {
op.setPytanieZamkniete(pytanieZamkniete);
opcjaRepository.save(op);
}
pytanieZamkniete.setOpcjas(opcjeSet);
pytanieZamknieteRepository.save(pytanieZamkniete);
}
public void usunPytanieZamknieteById(int idPytania) {
pytanieZamknieteRepository.delete(idPytania);
}
public void usunPytanieOtwarteById(int id) {
pytanieOtwarteRepository.delete(id);
}
public void usunPytanieOtwarteToSzablonById(int idSzablonu, int idPytania) {
pytanieOtwarteToSzablonRepository.delete(findPytanieOtwarteFromSzablon(idSzablonu, idPytania).getId());
}
public void usunPytanieZamknieteToSzablonById(int idSzablonu, int idPytania) {
pytanieZamknieteToSzablonRepository.delete(findPytanieZamknieteFromSzablon(idSzablonu, idPytania).getId());
}
public void usunPytanieZamkniete(int idPytania, int idSzablonu,int numerPytaniaToSzablon) {
usunPytanieZamknieteToSzablonById(idSzablonu, idPytania);
usunPytanieToSzablonById(numerPytaniaToSzablon);
usunPytanieZamknieteById(idPytania);
}
public void usunPytanieOtwarte(int idPytania, int idSzablonu, int numerPytaniaToSzablon) {
usunPytanieOtwarteToSzablonById(idSzablonu, idPytania);
usunPytanieToSzablonById(numerPytaniaToSzablon);
usunPytanieOtwarteById(idPytania);
}
public List<PytanieZamkniete> findAllPytanieZamkniete() {
return pytanieZamknieteRepository.findAll();
}
public List<Szablon> findAllSzablon() {
return szablonRepository.findAll();
}
public List<String> findAllSzablonNames() {
List<String> szablonNames = new ArrayList<String>();
for(Szablon szablon : szablonRepository.findAll())
{
szablonNames.add(szablon.getNazwa());
}
return szablonNames;
}
public TreeMap<Integer,String> findIdPytanFromSzablon(int idSzablonu) {
TreeMap<Integer,String> idPytan = new TreeMap<Integer,String>();
List<PytanieToSzablon> pytania = pytanieToSzablonRepository.findAll();
for(PytanieToSzablon pytanie:pytania){
int aktualneIdSzablonu = pytanie.getSzablon().getId().intValue();
if(aktualneIdSzablonu==idSzablonu){
if(pytanie.getPytanieOtwarte()!=null){
idPytan.put(pytanie.getPytanieOtwarte().getId(),"otwarte");
}
else
{
if(pytanie.getPytanieZamkniete()!=null)
{
idPytan.put(pytanie.getPytanieZamkniete().getId(),"zamkniete");
}
}
}
}
return idPytan;
}
public Set<PytanieZamkniete> findPytaniaZamknieteFromSzablon(int idSzablonu) {
Set<PytanieZamknieteToSzablon> pytania = szablonRepository.findOne(
idSzablonu).getPytaniaZamkniete();
Set<PytanieZamkniete> pytaniaZamkniete = new HashSet<PytanieZamkniete>();
for (PytanieZamknieteToSzablon pytanie : pytania) {
pytaniaZamkniete.add(pytanie.getPytanieZamkniete());
}
return pytaniaZamkniete;
}
public Set<PytanieOtwarte> findPytaniaOtwarteFromSzablon(int idSzablonu) {
Set<PytanieOtwarteToSzablon> pytania = szablonRepository.findOne(
idSzablonu).getPytaniaOtwarte();
Set<PytanieOtwarte> pytaniaOtwarte = new HashSet<PytanieOtwarte>();
for (PytanieOtwarteToSzablon pytanie : pytania) {
pytaniaOtwarte.add(pytanie.getPytanieOtwarte());
}
return pytaniaOtwarte;
}
public void usunSzablonById(int id) {
szablonRepository.delete(id);
}
public int findOstatniNumerPytaniaWSzablonie(int szablonId) {
List<PytanieToSzablon> pytania = pytanieToSzablonRepository.findAll();
int max=0;
for(PytanieToSzablon pytanie:pytania){
int aktualneIdSzablonu = pytanie.getSzablon().getId().intValue();
if(aktualneIdSzablonu==szablonId){
max++;
}
}
return max;
}
public int findNumerPytaniaWSzablonie(int szablonId, int pytanieId) {
List<PytanieToSzablon> pytania = pytanieToSzablonRepository.findAll();
int numer=0;
for(PytanieToSzablon pytanie:pytania){
int aktualneIdSzablonu = pytanie.getSzablon().getId().intValue();
if(aktualneIdSzablonu==szablonId){
numer++;
if(pytanie.getPytanieOtwarte()!=null){
if(pytanie.getPytanieOtwarte().getId().intValue()==pytanieId){
return numer;
}
}
else{
if(pytanie.getPytanieZamkniete().getId().intValue()==pytanieId){
return numer;
}
}
}
}
return numer;
}
public int findMaxLiczbaOpcji(Set<PytanieZamkniete> pytaniaZamkniete) {
int maxLiczbaOpcji = 1;
for(PytanieZamkniete pytanie : pytaniaZamkniete)
{
int liczbaOpcji = 0;
for(Opcja opcja : pytanie.getOpcjas())
{
String[] opcje = opcja.getTresc().split(",");
liczbaOpcji = opcje.length;
}
if(maxLiczbaOpcji<liczbaOpcji)
{
maxLiczbaOpcji = liczbaOpcji;
}
}
return maxLiczbaOpcji;
}
public List<PytanieToSzablon> findAllPytanieToSzablon() {
return pytanieToSzablonRepository.findAll();
}
public PytanieToSzablon findPytanieToSzablonById(int id) {
return pytanieToSzablonRepository.findOne(id);
}
public void usunPytanieToSzablonById(int id) {
pytanieToSzablonRepository.delete(id);
}
}
| Java |
package pl.wroc.pwr.psi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.psi.entity.PytanieZamkniete;
public interface PytanieZamknieteRepository extends JpaRepository<PytanieZamkniete, Integer>{
}
| Java |
package pl.wroc.pwr.psi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.psi.entity.PytanieOtwarte;
/**
*
* @author wposlednicka
*
*/
public interface PytanieOtwarteRepository extends JpaRepository<PytanieOtwarte, Integer> {
}
| Java |
package pl.wroc.pwr.psi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.psi.entity.PytanieOtwarteToSzablon;
public interface PytanieOtwarteToSzablonRepository extends JpaRepository<PytanieOtwarteToSzablon, Integer> {
}
| Java |
package pl.wroc.pwr.psi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.psi.entity.PytanieZamknieteToSzablon;
public interface PytanieZamknieteToSzablonRepository extends JpaRepository<PytanieZamknieteToSzablon, Integer> {
}
| Java |
package pl.wroc.pwr.psi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.psi.entity.PytanieOtwarteToSzablon;
import pl.wroc.pwr.psi.entity.PytanieToSzablon;
public interface PytanieToSzablonRepository extends JpaRepository<PytanieToSzablon, Integer> {
}
| Java |
package pl.wroc.pwr.psi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.psi.entity.ElementPlanu;
public interface ElementPlanuRepository extends JpaRepository<ElementPlanu, Integer> {
}
| Java |
package pl.wroc.pwr.psi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.psi.entity.SlowoKluczoweToPytanieOtwarte;
import pl.wroc.pwr.psi.entity.Szablon;
public interface SlowoKluczoweToPytanieOtwarteRepository extends JpaRepository<SlowoKluczoweToPytanieOtwarte, Integer> {
}
| Java |
package pl.wroc.pwr.psi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.psi.entity.Synonim;
public interface SynonimRepository extends JpaRepository<Synonim, Integer> {
}
| Java |
package pl.wroc.pwr.psi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.psi.entity.SlowoKluczowe;
/**
*
* @author wposlednicka
*
*/
public interface SlowoKluczoweRepository extends JpaRepository<SlowoKluczowe, Integer> {
}
| Java |
package pl.wroc.pwr.psi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.psi.entity.Opcja;
public interface OpcjaRepository extends JpaRepository<Opcja, Integer> {
}
| Java |
package pl.wroc.pwr.psi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.psi.entity.Szablon;
public interface SzablonRepository extends JpaRepository<Szablon, Integer> {
}
| Java |
package pl.wroc.pwr.psi.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import pl.wroc.pwr.psi.entity.Szablon;
import pl.wroc.pwr.psi.service.PytanieOtwarteService;
import pl.wroc.pwr.psi.service.SynonimService;
import pl.wroc.pwr.psi.service.SzablonService;
@Controller
public class IndexController {
@Autowired
private SzablonService szablonService;
@Autowired
private PytanieOtwarteService pytanieOtwarteService;
@RequestMapping("/index")
public String showIndex(Model model){
return "redirect:" + "szablony/";
}
@ModelAttribute("szablons")
public List<Szablon> pokazSzablony(Model model) {
return szablonService.findAllSzablon();
}
}
| Java |
package pl.wroc.pwr.psi.controller;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import pl.wroc.pwr.psi.entity.ElementPlanu;
import pl.wroc.pwr.psi.entity.PytanieOtwarte;
import pl.wroc.pwr.psi.entity.SlowoKluczowe;
import pl.wroc.pwr.psi.entity.SlowoKluczoweToPytanieOtwarte;
import pl.wroc.pwr.psi.entity.Szablon;
import pl.wroc.pwr.psi.service.DefinicjaSynonimowService;
import pl.wroc.pwr.psi.service.ElementPlanuService;
import pl.wroc.pwr.psi.service.PytanieOtwarteService;
import pl.wroc.pwr.psi.service.SzablonService;
import com.google.gson.Gson;
@Controller
public class PytaniaOtwarteDefinicjaSynonimowController {
@Autowired
private PytanieOtwarteService pytaniaOtwarteService;
@Autowired
private SzablonService szablonService;
@Autowired
private DefinicjaSynonimowService definicjaSynonimowService;
@Autowired
private ElementPlanuService elementPlanuService;
@RequestMapping("/szablony/usunskp")
public @ResponseBody String usunSlowoKluczoweZPytania(@RequestParam Integer skId, @RequestParam Integer pId) {
System.out.println("Usuwa sk: " + skId + " z pytania " + pId);
szablonService.usunSlowoKluczoweToPytanie(pId, skId);
return "OK";
}
@RequestMapping("/szablony/pytaniaotwarte")
public String pokazSzablony(Model model) {
List<PytanieOtwarte> pytaniaOtwarte = pytaniaOtwarteService.findAllPytanieOtwarte();
List<SlowoKluczowe> slowoKluczowes = definicjaSynonimowService.findAllSlowoKluczowe();
List<ElementPlanu> elementPlanu = elementPlanuService.findAllElementPlanu();
List<Szablon> szablony = szablonService.findAllSzablon();
sortuj(pytaniaOtwarte);
model.addAttribute("elementplanu", elementPlanu);
model.addAttribute("pytaniaotwarte", pytaniaOtwarte);
model.addAttribute("slowakluczowe", slowoKluczowes);
model.addAttribute("szablony", szablony);
model.addAttribute("szablons", szablonService.findAllSzablon());
return "pytaniaotwarte";
}
private void sortuj(List<PytanieOtwarte> pytaniaOtwarte) {
Collections.sort(pytaniaOtwarte, new Comparator<PytanieOtwarte>() {
@Override
public int compare(PytanieOtwarte o1, PytanieOtwarte o2) {
return o1.getTresc().compareTo(o2.getTresc());
}
});
}
@RequestMapping("/szablony/dodajskdopytania")
public @ResponseBody String dodajSlowoKluczoweDoPytania(@RequestParam Integer newSkId, @RequestParam Integer pId) {
System.out.println("Dodano skId " + newSkId + " pId " + pId);
String skJson = "";
if (czyJuzDodane(newSkId, pId)) {
skJson = new Gson().toJson("error");
} else {
SlowoKluczowe sk = szablonService.dodajSlowoKluczoweToPytanie(pId, newSkId);
SlowoKluczoweTO skTO = new SlowoKluczoweTO();
skTO.setId(sk.getId());
skTO.setNazwa(sk.getNazwa());
skJson = new Gson().toJson(skTO);
System.out.println(skJson);
}
return skJson;
}
private boolean czyJuzDodane(Integer newSkId, Integer pId) {
PytanieOtwarte pytanie = pytaniaOtwarteService.findPytanieOtwarteById(pId);
System.out.println(pId);
System.out.println(pytanie);
System.out.println(pytanie.getSlowoKluczowes());
for (SlowoKluczoweToPytanieOtwarte skpo : pytanie.getSlowoKluczowes()) {
if (skpo.getSlowoKluczowe().getId().equals(newSkId)) {
return true;
}
}
return false;
}
private class SlowoKluczoweTO {
private Integer id;
private String nazwa;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNazwa() {
return nazwa;
}
public void setNazwa(String nazwa) {
this.nazwa = nazwa;
}
}
}
| Java |
package pl.wroc.pwr.psi.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import pl.wroc.pwr.psi.entity.SlowoKluczowe;
import pl.wroc.pwr.psi.entity.Synonim;
import pl.wroc.pwr.psi.service.DefinicjaSynonimowService;
import pl.wroc.pwr.psi.service.SynonimService;
import pl.wroc.pwr.psi.service.SzablonService;
@Controller
public class DefinicjaSynonimowController {
private static final String usunSKErrorMsg = "Nie moge usunac slowa kluczowego gdyz jest wykorzystywane w pytaniach otwartych.";
@Autowired
private DefinicjaSynonimowService definicjaSynonimowService;
@Autowired
private SynonimService synonimService;
@Autowired
private SzablonService szablonService;
@RequestMapping("/szablony/*")
public String showCreateTemplate(Model model) {
model.addAttribute("szablons", szablonService.findAllSzablon());
return "szablony";
}
@RequestMapping(value="/szablony/dodajsk", method=RequestMethod.POST)
public String zdefiniujNoweSlowoKluczowe(@RequestParam String nazwa, @RequestParam(required=false) String[] synonimy, Model model) {
System.out.println("Dodaje się sk " + nazwa);
if (weryfikacjaSlowaKluczowego(nazwa)) {
List<String> synonimyDoDodania = new ArrayList<String>();
if(synonimy != null) {
synonimyDoDodania.addAll(Arrays.asList(synonimy));
}
Integer newSlowoKluczowe = definicjaSynonimowService.utworzNoweSlowoKluczowe(nazwa, synonimyDoDodania);
System.out.println("Dodano sk o id " + newSlowoKluczowe);
model.addAttribute("errorMsg", false);
} else {
model.addAttribute("errorMsg", true);
model.addAttribute("errorMsgText", nazwa);
}
return pokazSlowaKluczowe(model);
}
@RequestMapping("/szablony/usunsk")
public @ResponseBody String usunSlowoKluczowe(@RequestParam Integer skId, Model model) {
System.out.println("Usuwa sk: " + skId);
try {
definicjaSynonimowService.deleteSlowoKluczoweById(skId);
if(potwierdzenieUsuniecia(skId)) {
return "";
} else {
return usunSKErrorMsg;
}
} catch (Exception e) {
return usunSKErrorMsg;
}
}
private boolean potwierdzenieUsuniecia(Integer skId) {
SlowoKluczowe sk = definicjaSynonimowService.findSlowoKluczoweById(skId);
return sk == null;
}
@RequestMapping("/szablony/edytujsk")
public String edytujSlowoKluczowe(@RequestParam Integer skId, @RequestParam String nowaNazwa, Model model) {
System.out.println("Zmienia nazwę sk: " + skId);
definicjaSynonimowService.zmienNazweSlowoKluczowe(skId, nowaNazwa);
return "redirect:" + "synonimy.html";
}
@RequestMapping("/szablony/usunsynonim")
public @ResponseBody String usunSynonim(@RequestParam Integer synonimId) {
System.out.println("Usuwam synonim: " + synonimId);
synonimService.deleteSynonimById(synonimId);
return "OK";
}
@RequestMapping("/szablony/synonimy")
public String pokazSlowaKluczowe(Model model) {
System.out.println("showSlowoKluszowes");
Collection<SlowoKluczowe> slowoKluczowes = definicjaSynonimowService.findSlowaKluczowe();
System.out.println("slowoKluczowes.size(): " + slowoKluczowes.size());
ArrayList<SlowoKluczowe> slowaKluczowe = new ArrayList<SlowoKluczowe>(slowoKluczowes);
Collections.sort(slowaKluczowe, getSlowoKluczoweComparator());
model.addAttribute("slowakluczowe", slowaKluczowe);
model.addAttribute("szablons", szablonService.findAllSzablon());
return "synonimy";
}
private Comparator<SlowoKluczowe> getSlowoKluczoweComparator() {
return new Comparator<SlowoKluczowe>(){
@Override
public int compare(SlowoKluczowe o1, SlowoKluczowe o2) {
return o1.getNazwa().compareTo(o2.getNazwa());
}
};
}
@RequestMapping("/szablony/dodajsynonim")
public @ResponseBody String addSynonim(@RequestParam Integer skId, @RequestParam String synonim) {
System.out.println("Do sk o id " + skId + " dodano synonim " + synonim);
SlowoKluczowe sk = definicjaSynonimowService.findSlowoKluczoweById(skId);
Synonim newSynonim = new Synonim();
newSynonim.setSynonim(synonim);
newSynonim.setSlowoKluczowe(sk);
Integer savedSynonimId = definicjaSynonimowService.saveSynonim(newSynonim);
System.out.println("Dodano synonim o id " + savedSynonimId);
Synonim synonimTO = new Synonim();
synonimTO.setId(savedSynonimId);
synonimTO.setSynonim(synonim);
String synonimJson = new Gson().toJson(synonimTO);
return synonimJson;
}
private boolean weryfikacjaSlowaKluczowego(String sk) {
if (sk == null) {
return false;
}
if (sk.trim().length() == 0) {
return false;
}
if(definicjaSynonimowService.istniejeSlowoKluczowe(sk)) {
return false;
}
return true;
}
}
| Java |
/*-
* Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.bouncycastle.crypto;
/**
* all parameter classes implement this.
*/
public interface CipherParameters
{
}
| Java |
/*-
* Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.bouncycastle.crypto.macs;
import java.util.Hashtable;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.ExtendedDigest;
import org.bouncycastle.crypto.Mac;
import org.bouncycastle.crypto.params.KeyParameter;
/**
* HMAC implementation based on RFC2104
*
* H(K XOR opad, H(K XOR ipad, text))
*/
public class HMac
implements Mac
{
private final static byte IPAD = (byte)0x36;
private final static byte OPAD = (byte)0x5C;
private Digest digest;
private int digestSize;
private int blockLength;
private byte[] inputPad;
private byte[] outputPad;
private static Hashtable blockLengths;
static
{
blockLengths = new Hashtable();
blockLengths.put("GOST3411", new Integer(32));
blockLengths.put("MD2", new Integer(16));
blockLengths.put("MD4", new Integer(64));
blockLengths.put("MD5", new Integer(64));
blockLengths.put("RIPEMD128", new Integer(64));
blockLengths.put("RIPEMD160", new Integer(64));
blockLengths.put("SHA-1", new Integer(64));
blockLengths.put("SHA-224", new Integer(64));
blockLengths.put("SHA-256", new Integer(64));
blockLengths.put("SHA-384", new Integer(128));
blockLengths.put("SHA-512", new Integer(128));
blockLengths.put("Tiger", new Integer(64));
blockLengths.put("Whirlpool", new Integer(64));
}
private static int getByteLength(
Digest digest)
{
if (digest instanceof ExtendedDigest)
{
return ((ExtendedDigest)digest).getByteLength();
}
Integer b = (Integer)blockLengths.get(digest.getAlgorithmName());
if (b == null)
{
throw new IllegalArgumentException("unknown digest passed: " + digest.getAlgorithmName());
}
return b.intValue();
}
/**
* Base constructor for one of the standard digest algorithms that the
* byteLength of the algorithm is know for.
*
* @param digest the digest.
*/
public HMac(
Digest digest)
{
this(digest, getByteLength(digest));
}
private HMac(
Digest digest,
int byteLength)
{
this.digest = digest;
digestSize = digest.getDigestSize();
this.blockLength = byteLength;
inputPad = new byte[blockLength];
outputPad = new byte[blockLength];
}
public String getAlgorithmName()
{
return digest.getAlgorithmName() + "/HMAC";
}
public Digest getUnderlyingDigest()
{
return digest;
}
public void init(
CipherParameters params)
{
digest.reset();
byte[] key = ((KeyParameter)params).getKey();
if (key.length > blockLength)
{
digest.update(key, 0, key.length);
digest.doFinal(inputPad, 0);
for (int i = digestSize; i < inputPad.length; i++)
{
inputPad[i] = 0;
}
}
else
{
System.arraycopy(key, 0, inputPad, 0, key.length);
for (int i = key.length; i < inputPad.length; i++)
{
inputPad[i] = 0;
}
}
outputPad = new byte[inputPad.length];
System.arraycopy(inputPad, 0, outputPad, 0, inputPad.length);
for (int i = 0; i < inputPad.length; i++)
{
inputPad[i] ^= IPAD;
}
for (int i = 0; i < outputPad.length; i++)
{
outputPad[i] ^= OPAD;
}
digest.update(inputPad, 0, inputPad.length);
}
public int getMacSize()
{
return digestSize;
}
public void update(
byte in)
{
digest.update(in);
}
public void update(
byte[] in,
int inOff,
int len)
{
digest.update(in, inOff, len);
}
public int doFinal(
byte[] out,
int outOff)
{
byte[] tmp = new byte[digestSize];
digest.doFinal(tmp, 0);
digest.update(outputPad, 0, outputPad.length);
digest.update(tmp, 0, tmp.length);
int len = digest.doFinal(out, outOff);
reset();
return len;
}
/**
* Reset the mac generator.
*/
public void reset()
{
/*
* reset the underlying digest.
*/
digest.reset();
/*
* reinitialize the digest.
*/
digest.update(inputPad, 0, inputPad.length);
}
}
| Java |
/*-
* Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.bouncycastle.crypto;
/**
* the foundation class for the exceptions thrown by the crypto packages.
*/
public class RuntimeCryptoException
extends RuntimeException
{
/**
* base constructor.
*/
public RuntimeCryptoException()
{
}
/**
* create a RuntimeCryptoException with the given message.
*
* @param message the message to be carried with the exception.
*/
public RuntimeCryptoException(
String message)
{
super(message);
}
}
| Java |
/*-
* Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.bouncycastle.crypto;
/**
* The base interface for implementations of message authentication codes (MACs).
*/
public interface Mac
{
/**
* Initialise the MAC.
*
* @param params the key and other data required by the MAC.
* @exception IllegalArgumentException if the params argument is
* inappropriate.
*/
public void init(CipherParameters params)
throws IllegalArgumentException;
/**
* Return the name of the algorithm the MAC implements.
*
* @return the name of the algorithm the MAC implements.
*/
public String getAlgorithmName();
/**
* Return the block size for this MAC (in bytes).
*
* @return the block size for this MAC in bytes.
*/
public int getMacSize();
/**
* add a single byte to the mac for processing.
*
* @param in the byte to be processed.
* @exception IllegalStateException if the MAC is not initialised.
*/
public void update(byte in)
throws IllegalStateException;
/**
* @param in the array containing the input.
* @param inOff the index in the array the data begins at.
* @param len the length of the input starting at inOff.
* @exception IllegalStateException if the MAC is not initialised.
* @exception DataLengthException if there isn't enough data in in.
*/
public void update(byte[] in, int inOff, int len)
throws DataLengthException, IllegalStateException;
/**
* Compute the final stage of the MAC writing the output to the out
* parameter.
* <p>
* doFinal leaves the MAC in the same state it was after the last init.
*
* @param out the array the MAC is to be output to.
* @param outOff the offset into the out buffer the output is to start at.
* @exception DataLengthException if there isn't enough space in out.
* @exception IllegalStateException if the MAC is not initialised.
*/
public int doFinal(byte[] out, int outOff)
throws DataLengthException, IllegalStateException;
/**
* Reset the MAC. At the end of resetting the MAC should be in the
* in the same state it was after the last init (if there was one).
*/
public void reset();
}
| Java |
/*-
* Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.bouncycastle.crypto;
/**
* this exception is thrown if a buffer that is meant to have output
* copied into it turns out to be too short, or if we've been given
* insufficient input. In general this exception will get thrown rather
* than an ArrayOutOfBounds exception.
*/
public class DataLengthException
extends RuntimeCryptoException
{
/**
* base constructor.
*/
public DataLengthException()
{
}
/**
* create a DataLengthException with the given message.
*
* @param message the message to be carried with the exception.
*/
public DataLengthException(
String message)
{
super(message);
}
}
| Java |
/*-
* Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.bouncycastle.crypto.params;
import org.bouncycastle.crypto.CipherParameters;
public class KeyParameter
implements CipherParameters
{
private byte[] key;
public KeyParameter(
byte[] key)
{
this(key, 0, key.length);
}
public KeyParameter(
byte[] key,
int keyOff,
int keyLen)
{
this.key = new byte[keyLen];
System.arraycopy(key, keyOff, this.key, 0, keyLen);
}
public byte[] getKey()
{
return key;
}
}
| Java |
/*-
* Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.bouncycastle.crypto;
public interface ExtendedDigest
extends Digest
{
/**
* Return the size in bytes of the internal buffer the digest applies it's compression
* function to.
*
* @return byte length of the digests internal buffer.
*/
public int getByteLength();
}
| Java |
/*-
* Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.bouncycastle.crypto.digests;
import org.bouncycastle.crypto.ExtendedDigest;
/**
* base implementation of MD4 family style digest as outlined in
* "Handbook of Applied Cryptography", pages 344 - 347.
*/
public abstract class GeneralDigest
implements ExtendedDigest
{
private static final int BYTE_LENGTH = 64;
private byte[] xBuf;
private int xBufOff;
private long byteCount;
/**
* Standard constructor
*/
protected GeneralDigest()
{
xBuf = new byte[4];
xBufOff = 0;
}
/**
* Copy constructor. We are using copy constructors in place
* of the Object.clone() interface as this interface is not
* supported by J2ME.
*/
protected GeneralDigest(GeneralDigest t)
{
xBuf = new byte[t.xBuf.length];
System.arraycopy(t.xBuf, 0, xBuf, 0, t.xBuf.length);
xBufOff = t.xBufOff;
byteCount = t.byteCount;
}
public void update(
byte in)
{
xBuf[xBufOff++] = in;
if (xBufOff == xBuf.length)
{
processWord(xBuf, 0);
xBufOff = 0;
}
byteCount++;
}
public void update(
byte[] in,
int inOff,
int len)
{
//
// fill the current word
//
while ((xBufOff != 0) && (len > 0))
{
update(in[inOff]);
inOff++;
len--;
}
//
// process whole words.
//
while (len > xBuf.length)
{
processWord(in, inOff);
inOff += xBuf.length;
len -= xBuf.length;
byteCount += xBuf.length;
}
//
// load in the remainder.
//
while (len > 0)
{
update(in[inOff]);
inOff++;
len--;
}
}
public void finish()
{
long bitLength = (byteCount << 3);
//
// add the pad bytes.
//
update((byte)128);
while (xBufOff != 0)
{
update((byte)0);
}
processLength(bitLength);
processBlock();
}
public void reset()
{
byteCount = 0;
xBufOff = 0;
for (int i = 0; i < xBuf.length; i++)
{
xBuf[i] = 0;
}
}
public int getByteLength()
{
return BYTE_LENGTH;
}
protected abstract void processWord(byte[] in, int inOff);
protected abstract void processLength(long bitLength);
protected abstract void processBlock();
}
| Java |
/*-
* Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.bouncycastle.crypto.digests;
import org.bouncycastle.crypto.util.Pack;
/**
* implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349.
*
* It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5
* is the "endienness" of the word processing!
*/
public class SHA1Digest
extends GeneralDigest
{
private static final int DIGEST_LENGTH = 20;
private int H1, H2, H3, H4, H5;
private int[] X = new int[80];
private int xOff;
/**
* Standard constructor
*/
public SHA1Digest()
{
reset();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public SHA1Digest(SHA1Digest t)
{
super(t);
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
H5 = t.H5;
System.arraycopy(t.X, 0, X, 0, t.X.length);
xOff = t.xOff;
}
public String getAlgorithmName()
{
return "SHA-1";
}
public int getDigestSize()
{
return DIGEST_LENGTH;
}
protected void processWord(
byte[] in,
int inOff)
{
// Note: Inlined for performance
// X[xOff] = Pack.bigEndianToInt(in, inOff);
int n = in[ inOff] << 24;
n |= (in[++inOff] & 0xff) << 16;
n |= (in[++inOff] & 0xff) << 8;
n |= (in[++inOff] & 0xff);
X[xOff] = n;
if (++xOff == 16)
{
processBlock();
}
}
protected void processLength(
long bitLength)
{
if (xOff > 14)
{
processBlock();
}
X[14] = (int)(bitLength >>> 32);
X[15] = (int)(bitLength & 0xffffffff);
}
public int doFinal(
byte[] out,
int outOff)
{
finish();
Pack.intToBigEndian(H1, out, outOff);
Pack.intToBigEndian(H2, out, outOff + 4);
Pack.intToBigEndian(H3, out, outOff + 8);
Pack.intToBigEndian(H4, out, outOff + 12);
Pack.intToBigEndian(H5, out, outOff + 16);
reset();
return DIGEST_LENGTH;
}
/**
* reset the chaining variables
*/
public void reset()
{
super.reset();
H1 = 0x67452301;
H2 = 0xefcdab89;
H3 = 0x98badcfe;
H4 = 0x10325476;
H5 = 0xc3d2e1f0;
xOff = 0;
for (int i = 0; i != X.length; i++)
{
X[i] = 0;
}
}
//
// Additive constants
//
private static final int Y1 = 0x5a827999;
private static final int Y2 = 0x6ed9eba1;
private static final int Y3 = 0x8f1bbcdc;
private static final int Y4 = 0xca62c1d6;
private int f(
int u,
int v,
int w)
{
return ((u & v) | ((~u) & w));
}
private int h(
int u,
int v,
int w)
{
return (u ^ v ^ w);
}
private int g(
int u,
int v,
int w)
{
return ((u & v) | (u & w) | (v & w));
}
protected void processBlock()
{
//
// expand 16 word block into 80 word block.
//
for (int i = 16; i < 80; i++)
{
int t = X[i - 3] ^ X[i - 8] ^ X[i - 14] ^ X[i - 16];
X[i] = t << 1 | t >>> 31;
}
//
// set up working variables.
//
int A = H1;
int B = H2;
int C = H3;
int D = H4;
int E = H5;
//
// round 1
//
int idx = 0;
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + f(B, C, D) + E + X[idx++] + Y1
// B = rotateLeft(B, 30)
E += (A << 5 | A >>> 27) + f(B, C, D) + X[idx++] + Y1;
B = B << 30 | B >>> 2;
D += (E << 5 | E >>> 27) + f(A, B, C) + X[idx++] + Y1;
A = A << 30 | A >>> 2;
C += (D << 5 | D >>> 27) + f(E, A, B) + X[idx++] + Y1;
E = E << 30 | E >>> 2;
B += (C << 5 | C >>> 27) + f(D, E, A) + X[idx++] + Y1;
D = D << 30 | D >>> 2;
A += (B << 5 | B >>> 27) + f(C, D, E) + X[idx++] + Y1;
C = C << 30 | C >>> 2;
}
//
// round 2
//
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + h(B, C, D) + E + X[idx++] + Y2
// B = rotateLeft(B, 30)
E += (A << 5 | A >>> 27) + h(B, C, D) + X[idx++] + Y2;
B = B << 30 | B >>> 2;
D += (E << 5 | E >>> 27) + h(A, B, C) + X[idx++] + Y2;
A = A << 30 | A >>> 2;
C += (D << 5 | D >>> 27) + h(E, A, B) + X[idx++] + Y2;
E = E << 30 | E >>> 2;
B += (C << 5 | C >>> 27) + h(D, E, A) + X[idx++] + Y2;
D = D << 30 | D >>> 2;
A += (B << 5 | B >>> 27) + h(C, D, E) + X[idx++] + Y2;
C = C << 30 | C >>> 2;
}
//
// round 3
//
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + g(B, C, D) + E + X[idx++] + Y3
// B = rotateLeft(B, 30)
E += (A << 5 | A >>> 27) + g(B, C, D) + X[idx++] + Y3;
B = B << 30 | B >>> 2;
D += (E << 5 | E >>> 27) + g(A, B, C) + X[idx++] + Y3;
A = A << 30 | A >>> 2;
C += (D << 5 | D >>> 27) + g(E, A, B) + X[idx++] + Y3;
E = E << 30 | E >>> 2;
B += (C << 5 | C >>> 27) + g(D, E, A) + X[idx++] + Y3;
D = D << 30 | D >>> 2;
A += (B << 5 | B >>> 27) + g(C, D, E) + X[idx++] + Y3;
C = C << 30 | C >>> 2;
}
//
// round 4
//
for (int j = 0; j <= 3; j++)
{
// E = rotateLeft(A, 5) + h(B, C, D) + E + X[idx++] + Y4
// B = rotateLeft(B, 30)
E += (A << 5 | A >>> 27) + h(B, C, D) + X[idx++] + Y4;
B = B << 30 | B >>> 2;
D += (E << 5 | E >>> 27) + h(A, B, C) + X[idx++] + Y4;
A = A << 30 | A >>> 2;
C += (D << 5 | D >>> 27) + h(E, A, B) + X[idx++] + Y4;
E = E << 30 | E >>> 2;
B += (C << 5 | C >>> 27) + h(D, E, A) + X[idx++] + Y4;
D = D << 30 | D >>> 2;
A += (B << 5 | B >>> 27) + h(C, D, E) + X[idx++] + Y4;
C = C << 30 | C >>> 2;
}
H1 += A;
H2 += B;
H3 += C;
H4 += D;
H5 += E;
//
// reset start of the buffer.
//
xOff = 0;
for (int i = 0; i < 16; i++)
{
X[i] = 0;
}
}
}
| Java |
/*-
* Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.bouncycastle.crypto.util;
public abstract class Pack
{
public static int bigEndianToInt(byte[] bs, int off)
{
int n = bs[ off] << 24;
n |= (bs[++off] & 0xff) << 16;
n |= (bs[++off] & 0xff) << 8;
n |= (bs[++off] & 0xff);
return n;
}
public static void intToBigEndian(int n, byte[] bs, int off)
{
bs[ off] = (byte)(n >>> 24);
bs[++off] = (byte)(n >>> 16);
bs[++off] = (byte)(n >>> 8);
bs[++off] = (byte)(n );
}
public static long bigEndianToLong(byte[] bs, int off)
{
int hi = bigEndianToInt(bs, off);
int lo = bigEndianToInt(bs, off + 4);
return ((long)(hi & 0xffffffffL) << 32) | (long)(lo & 0xffffffffL);
}
public static void longToBigEndian(long n, byte[] bs, int off)
{
intToBigEndian((int)(n >>> 32), bs, off);
intToBigEndian((int)(n & 0xffffffffL), bs, off + 4);
}
}
| Java |
/*-
* Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.bouncycastle.crypto;
/**
* interface that a message digest conforms to.
*/
public interface Digest
{
/**
* return the algorithm name
*
* @return the algorithm name
*/
public String getAlgorithmName();
/**
* return the size, in bytes, of the digest produced by this message digest.
*
* @return the size, in bytes, of the digest produced by this message digest.
*/
public int getDigestSize();
/**
* update the message digest with a single byte.
*
* @param in the input byte to be entered.
*/
public void update(byte in);
/**
* update the message digest with a block of bytes.
*
* @param in the byte array containing the data.
* @param inOff the offset into the byte array where the data starts.
* @param len the length of the data.
*/
public void update(byte[] in, int inOff, int len);
/**
* close the digest, producing the final digest value. The doFinal
* call leaves the digest reset.
*
* @param out the array the digest is to be copied into.
* @param outOff the offset into the out array the digest is to start at.
*/
public int doFinal(byte[] out, int outOff);
/**
* reset the digest back to it's initial state.
*/
public void reset();
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.Clipboard;
import net.rim.device.api.ui.ContextMenu;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import com.google.authenticator.blackberry.resource.AuthenticatorResource;
/**
* BlackBerry port of {@code PinListAdapter}.
*/
public class PinListField extends ListField implements AuthenticatorResource {
private static ResourceBundle sResources = ResourceBundle.getBundle(
BUNDLE_ID, BUNDLE_NAME);
/**
* {@inheritDoc}
*/
public int moveFocus(int amount, int status, int time) {
invalidate(getSelectedIndex());
return super.moveFocus(amount, status, time);
}
/**
* {@inheritDoc}
*/
public void onUnfocus() {
super.onUnfocus();
invalidate();
}
/**
* {@inheritDoc}
*/
protected void makeContextMenu(ContextMenu contextMenu) {
super.makeContextMenu(contextMenu);
ListFieldCallback callback = getCallback();
final int selectedIndex = getSelectedIndex();
final PinInfo item = (PinInfo) callback.get(this, selectedIndex);
if (item.mIsHotp) {
MenuItem hotpItem = new MenuItem(sResources, COUNTER_PIN, 0, 0) {
public void run() {
AuthenticatorScreen screen = (AuthenticatorScreen) getScreen();
String user = item.mUser;
String pin = screen.computeAndDisplayPin(user, selectedIndex, true);
item.mPin = pin;
invalidate(selectedIndex);
}
};
contextMenu.addItem(hotpItem);
}
MenuItem copyItem = new MenuItem(sResources, COPY_TO_CLIPBOARD, 0, 0) {
public void run() {
Clipboard clipboard = Clipboard.getClipboard();
clipboard.put(item.mPin);
String message = sResources.getString(COPIED);
Dialog.inform(message);
}
};
MenuItem deleteItem = new MenuItem(sResources, DELETE, 0, 0) {
public void run() {
String message = (sResources.getString(DELETE_MESSAGE) + "\n" + item.mUser);
int defaultChoice = Dialog.NO;
if (Dialog.ask(Dialog.D_YES_NO, message, defaultChoice) == Dialog.YES) {
AccountDb.delete(item.mUser);
AuthenticatorScreen screen = (AuthenticatorScreen) getScreen();
screen.refreshUserList();
}
}
};
contextMenu.addItem(copyItem);
if (item.mIsHotp) {
MenuItem checkCodeItem = new MenuItem(sResources, CHECK_CODE_MENU_ITEM, 0, 0) {
public void run() {
pushScreen(new CheckCodeScreen(item.mUser));
}
};
contextMenu.addItem(checkCodeItem);
}
contextMenu.addItem(deleteItem);
}
void pushScreen(Screen s) {
Screen screen = getScreen();
UiApplication app = (UiApplication) screen.getApplication();
app.pushScreen(s);
}
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
import net.rim.device.api.util.AbstractString;
import net.rim.device.api.util.StringPattern;
/**
* Searches for URIs matching one of the following:
*
* <pre>
* https://www.google.com/accounts/KeyProv?user=username#secret
* totp://username@domain#secret
* otpauth://totp/user@example.com?secret=FFF...
* otpauth://hotp/user@example.com?secret=FFF...&counter=123
* </pre>
*
* <strong>Important Note:</strong> HTTP/HTTPS URIs may be ignored by the
* platform because they are already handled by the browser.
*/
public class UriStringPattern extends StringPattern {
/**
* A list of URI prefixes that should be matched.
*/
private static final String[] PREFIXES = {
"https://www.google.com/accounts/KeyProv?", "totp://", "otpauth://totp/",
"otpauth://hotp/" };
public UriStringPattern() {
}
/**
* {@inheritDoc}
*/
public boolean findMatch(AbstractString str, int beginIndex, int maxIndex,
StringPattern.Match match) {
prefixes: for (int i = 0; i < PREFIXES.length; i++) {
String prefix = PREFIXES[i];
if (maxIndex - beginIndex < prefix.length()) {
continue prefixes;
}
characters: for (int a = beginIndex; a < maxIndex; a++) {
for (int b = 0; b < prefix.length(); b++) {
if (str.charAt(a + b) != prefix.charAt(b)) {
continue characters;
}
}
int uriStart = a;
while (a < maxIndex && !isWhitespace(str.charAt(a))) {
a++;
}
int uriEnd = a;
match.id = AuthenticatorApplication.FACTORY_ID;
match.beginIndex = uriStart;
match.endIndex = uriEnd;
match.prefixLength = 0;
return true;
}
}
return false;
}
} | Java |
/*-
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modifications:
* -Changed package name
* -Removed annotations
* -Removed "@since Android 1.0" comments
*/
package com.google.authenticator.blackberry;
import java.io.UnsupportedEncodingException;
/**
* This class is used to encode a string using the format required by
* {@code application/x-www-form-urlencoded} MIME content type.
*/
public class URLEncoder {
static final String digits = "0123456789ABCDEF"; //$NON-NLS-1$
/**
* Prevents this class from being instantiated.
*/
private URLEncoder() {
}
/**
* Encodes a given string {@code s} in a x-www-form-urlencoded string using
* the specified encoding scheme {@code enc}.
* <p>
* All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9')
* and characters '.', '-', '*', '_' are converted into their hexadecimal
* value prepended by '%'. For example: '#' -> %23. In addition, spaces are
* substituted by '+'
* </p>
*
* @param s
* the string to be encoded.
* @return the encoded string.
* @deprecated use {@link #encode(String, String)} instead.
*/
public static String encode(String s) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
|| (ch >= '0' && ch <= '9') || ".-*_".indexOf(ch) > -1) { //$NON-NLS-1$
buf.append(ch);
} else if (ch == ' ') {
buf.append('+');
} else {
byte[] bytes = new String(new char[] { ch }).getBytes();
for (int j = 0; j < bytes.length; j++) {
buf.append('%');
buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));
buf.append(digits.charAt(bytes[j] & 0xf));
}
}
}
return buf.toString();
}
/**
* Encodes the given string {@code s} in a x-www-form-urlencoded string
* using the specified encoding scheme {@code enc}.
* <p>
* All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9')
* and characters '.', '-', '*', '_' are converted into their hexadecimal
* value prepended by '%'. For example: '#' -> %23. In addition, spaces are
* substituted by '+'
* </p>
*
* @param s
* the string to be encoded.
* @param enc
* the encoding scheme to be used.
* @return the encoded string.
* @throws UnsupportedEncodingException
* if the specified encoding scheme is invalid.
*/
public static String encode(String s, String enc)
throws UnsupportedEncodingException {
if (s == null || enc == null) {
throw new NullPointerException();
}
// check for UnsupportedEncodingException
"".getBytes(enc); //$NON-NLS-1$
StringBuffer buf = new StringBuffer();
int start = -1;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
|| (ch >= '0' && ch <= '9') || " .-*_".indexOf(ch) > -1) { //$NON-NLS-1$
if (start >= 0) {
convert(s.substring(start, i), buf, enc);
start = -1;
}
if (ch != ' ') {
buf.append(ch);
} else {
buf.append('+');
}
} else {
if (start < 0) {
start = i;
}
}
}
if (start >= 0) {
convert(s.substring(start, s.length()), buf, enc);
}
return buf.toString();
}
private static void convert(String s, StringBuffer buf, String enc)
throws UnsupportedEncodingException {
byte[] bytes = s.getBytes(enc);
for (int j = 0; j < bytes.length; j++) {
buf.append('%');
buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));
buf.append(digits.charAt(bytes[j] & 0xf));
}
}
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
/**
* Encodes arbitrary byte arrays as case-insensitive base-32 strings using
* the legacy encoding scheme.
*/
public class Base32Legacy extends Base32String {
// 32 alpha-numeric characters. Excluding 0, 1, O, and I
private static final Base32Legacy INSTANCE =
new Base32Legacy("23456789ABCDEFGHJKLMNPQRSTUVWXYZ");
static Base32String getInstance() {
return INSTANCE;
}
protected Base32Legacy(String alphabet) {
super(alphabet);
}
public static byte[] decode(String encoded) throws DecodingException {
return getInstance().decodeInternal(encoded);
}
public static String encode(byte[] data) {
return getInstance().encodeInternal(data);
}
} | Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
/**
* Callback interface for {@link UpdateTask}.
*/
public interface UpdateCallback {
void onUpdate(String version);
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.component.NullField;
/**
* Utility methods for using BlackBerry {@link Field Fields}.
*/
public class FieldUtils {
public static boolean isVisible(Field field) {
return field.getManager() != null;
}
/**
* BlackBerry {@link Field Fields} do not support invisibility, so swap in an
* invisible placeholder to simulate invisibility.
* <p>
* The placeholder field is stored with {@link Field#setCookie(Object)}.
* <p>
* The non-placeholder field must be added to a {@link Manager} before marking
* is as <em>invisible</em> so that the implementation knows where to insert
* the placeholder.
*
* @param field
* the field to toggle.
* @param visible
* the new visibility.
*/
public static void setVisible(Field field, boolean visible) {
NullField peer = (NullField) field.getCookie();
if (visible && !isVisible(field)) {
if (peer == null) {
throw new IllegalStateException("Placeholder missing");
}
Manager manager = peer.getManager();
manager.replace(peer, field);
} else if (!visible && isVisible(field)) {
if (peer == null) {
peer = new NullField();
field.setCookie(peer);
}
Manager manager = field.getManager();
manager.replace(field, peer);
}
}
FieldUtils() {
}
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import org.bouncycastle.crypto.Mac;
/**
* An implementation of the HOTP generator specified by RFC 4226. Generates
* short passcodes that may be used in challenge-response protocols or as
* timeout passcodes that are only valid for a short period.
*
* The default passcode is a 6-digit decimal code and the default timeout
* period is 5 minutes.
*/
public class PasscodeGenerator {
/** Default decimal passcode length */
private static final int PASS_CODE_LENGTH = 6;
/** Default passcode timeout period (in seconds) */
private static final int INTERVAL = 30;
/** The number of previous and future intervals to check */
private static final int ADJACENT_INTERVALS = 1;
private static final int PIN_MODULO = pow(10, PASS_CODE_LENGTH);
private static final int pow(int a, int b) {
int result = 1;
for (int i = 0; i < b; i++) {
result *= a;
}
return result;
}
private final Signer signer;
private final int codeLength;
private final int intervalPeriod;
/*
* Using an interface to allow us to inject different signature
* implementations.
*/
interface Signer {
byte[] sign(byte[] data);
}
/**
* @param mac A {@link Mac} used to generate passcodes
*/
public PasscodeGenerator(Mac mac) {
this(mac, PASS_CODE_LENGTH, INTERVAL);
}
/**
* @param mac A {@link Mac} used to generate passcodes
* @param passCodeLength The length of the decimal passcode
* @param interval The interval that a passcode is valid for
*/
public PasscodeGenerator(final Mac mac, int passCodeLength, int interval) {
this(new Signer() {
public byte[] sign(byte[] data){
mac.reset();
mac.update(data, 0, data.length);
int length = mac.getMacSize();
byte[] out = new byte[length];
mac.doFinal(out, 0);
mac.reset();
return out;
}
}, passCodeLength, interval);
}
public PasscodeGenerator(Signer signer, int passCodeLength, int interval) {
this.signer = signer;
this.codeLength = passCodeLength;
this.intervalPeriod = interval;
}
private String padOutput(int value) {
String result = Integer.toString(value);
for (int i = result.length(); i < codeLength; i++) {
result = "0" + result;
}
return result;
}
/**
* @return A decimal timeout code
*/
public String generateTimeoutCode() {
return generateResponseCode(clock.getCurrentInterval());
}
/**
* @param challenge A long-valued challenge
* @return A decimal response code
* @throws GeneralSecurityException If a JCE exception occur
*/
public String generateResponseCode(long challenge) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutput dout = new DataOutputStream(out);
try {
dout.writeLong(challenge);
} catch (IOException e) {
// This should never happen with a ByteArrayOutputStream
throw new RuntimeException("Unexpected IOException");
}
byte[] value = out.toByteArray();
return generateResponseCode(value);
}
/**
* @param challenge An arbitrary byte array used as a challenge
* @return A decimal response code
* @throws GeneralSecurityException If a JCE exception occur
*/
public String generateResponseCode(byte[] challenge) {
byte[] hash = signer.sign(challenge);
// Dynamically truncate the hash
// OffsetBits are the low order bits of the last byte of the hash
int offset = hash[hash.length - 1] & 0xF;
// Grab a positive integer value starting at the given offset.
int truncatedHash = hashToInt(hash, offset) & 0x7FFFFFFF;
int pinValue = truncatedHash % PIN_MODULO;
return padOutput(pinValue);
}
/**
* Grabs a positive integer value from the input array starting at
* the given offset.
* @param bytes the array of bytes
* @param start the index into the array to start grabbing bytes
* @return the integer constructed from the four bytes in the array
*/
private int hashToInt(byte[] bytes, int start) {
DataInput input = new DataInputStream(
new ByteArrayInputStream(bytes, start, bytes.length - start));
int val;
try {
val = input.readInt();
} catch (IOException e) {
throw new IllegalStateException(String.valueOf(e));
}
return val;
}
/**
* @param challenge A challenge to check a response against
* @param response A response to verify
* @return True if the response is valid
*/
public boolean verifyResponseCode(long challenge, String response) {
String expectedResponse = generateResponseCode(challenge);
return expectedResponse.equals(response);
}
/**
* Verify a timeout code. The timeout code will be valid for a time
* determined by the interval period and the number of adjacent intervals
* checked.
*
* @param timeoutCode The timeout code
* @return True if the timeout code is valid
*/
public boolean verifyTimeoutCode(String timeoutCode) {
return verifyTimeoutCode(timeoutCode, ADJACENT_INTERVALS,
ADJACENT_INTERVALS);
}
/**
* Verify a timeout code. The timeout code will be valid for a time
* determined by the interval period and the number of adjacent intervals
* checked.
*
* @param timeoutCode The timeout code
* @param pastIntervals The number of past intervals to check
* @param futureIntervals The number of future intervals to check
* @return True if the timeout code is valid
*/
public boolean verifyTimeoutCode(String timeoutCode, int pastIntervals,
int futureIntervals) {
long currentInterval = clock.getCurrentInterval();
String expectedResponse = generateResponseCode(currentInterval);
if (expectedResponse.equals(timeoutCode)) {
return true;
}
for (int i = 1; i <= pastIntervals; i++) {
String pastResponse = generateResponseCode(currentInterval - i);
if (pastResponse.equals(timeoutCode)) {
return true;
}
}
for (int i = 1; i <= futureIntervals; i++) {
String futureResponse = generateResponseCode(currentInterval + i);
if (futureResponse.equals(timeoutCode)) {
return true;
}
}
return false;
}
private IntervalClock clock = new IntervalClock() {
/*
* @return The current interval
*/
public long getCurrentInterval() {
long currentTimeSeconds = System.currentTimeMillis() / 1000;
return currentTimeSeconds / getIntervalPeriod();
}
public int getIntervalPeriod() {
return intervalPeriod;
}
};
// To facilitate injecting a mock clock
interface IntervalClock {
int getIntervalPeriod();
long getCurrentInterval();
}
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import org.bouncycastle.crypto.Mac;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import com.google.authenticator.blackberry.resource.AuthenticatorResource;
/**
* BlackBerry port of {@code CheckCodeActivity}.
*/
public class CheckCodeScreen extends MainScreen implements AuthenticatorResource {
private static final boolean SHOW_INSTRUCTIONS = false;
private static ResourceBundle sResources = ResourceBundle.getBundle(
BUNDLE_ID, BUNDLE_NAME);
private RichTextField mCheckCodeTextView;
private LabelField mCodeTextView;
private LabelField mVersionText;
private Manager mCodeArea;
private String mUser;
static String getCheckCode(String secret)
throws Base32String.DecodingException {
final byte[] keyBytes = Base32String.decode(secret);
Mac mac = new HMac(new SHA1Digest());
mac.init(new KeyParameter(keyBytes));
PasscodeGenerator pcg = new PasscodeGenerator(mac);
return pcg.generateResponseCode(0L);
}
public CheckCodeScreen(String user) {
mUser = user;
setTitle(sResources.getString(CHECK_CODE_TITLE));
mCheckCodeTextView = new RichTextField();
mCheckCodeTextView.setText(sResources.getString(CHECK_CODE));
mCodeArea = new HorizontalFieldManager(FIELD_HCENTER);
Bitmap bitmap = Bitmap.getBitmapResource("ic_lock_lock.png");
BitmapField icon = new BitmapField(bitmap, FIELD_VCENTER);
mCodeTextView = new LabelField("", FIELD_VCENTER);
mCodeArea.add(icon);
mCodeArea.add(mCodeTextView);
ApplicationDescriptor applicationDescriptor = ApplicationDescriptor
.currentApplicationDescriptor();
String version = applicationDescriptor.getVersion();
mVersionText = new LabelField(version, FIELD_RIGHT | FIELD_BOTTOM);
add(mCheckCodeTextView);
add(mCodeArea);
add(mVersionText);
}
/**
* {@inheritDoc}
*/
protected void onDisplay() {
super.onDisplay();
onResume();
}
/**
* {@inheritDoc}
*/
protected void onExposed() {
super.onExposed();
onResume();
}
private void onResume() {
String secret = AuthenticatorScreen.getSecret(mUser);
if (secret == null || secret.length() == 0) {
// If the user started up this app but there is no secret key yet,
// then tell the user to visit a web page to get the secret key.
tellUserToGetSecretKey();
return;
}
String checkCode = null;
String errorMessage = null;
try {
checkCode = getCheckCode(secret);
} catch (RuntimeException e) {
errorMessage = sResources.getString(GENERAL_SECURITY_EXCEPTION);
} catch (Base32String.DecodingException e) {
errorMessage = sResources.getString(DECODING_EXCEPTION);
}
if (errorMessage != null) {
mCheckCodeTextView.setText(errorMessage);
FieldUtils.setVisible(mCheckCodeTextView, true);
FieldUtils.setVisible(mCodeArea, false);
} else {
mCodeTextView.setText(checkCode);
String checkCodeMessage = sResources.getString(CHECK_CODE);
mCheckCodeTextView.setText(checkCodeMessage);
FieldUtils.setVisible(mCheckCodeTextView, SHOW_INSTRUCTIONS);
FieldUtils.setVisible(mCodeArea, true);
}
}
/**
* Tells the user to visit a web page to get a secret key.
*/
private void tellUserToGetSecretKey() {
String message = sResources.getString(NOT_INITIALIZED);
mCheckCodeTextView.setText(message);
FieldUtils.setVisible(mCheckCodeTextView, true);
FieldUtils.setVisible(mCodeArea, false);
}
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.ApplicationManager;
import net.rim.device.api.system.ApplicationManagerException;
import net.rim.device.api.system.CodeModuleManager;
import net.rim.device.api.ui.MenuItem;
import com.google.authenticator.blackberry.resource.AuthenticatorResource;
/**
* A context menu item for shared secret URLs found in other applications (such
* as the SMS app).
*/
public class UriMenuItem extends MenuItem implements AuthenticatorResource {
private static ResourceBundle sResources = ResourceBundle.getBundle(
BUNDLE_ID, BUNDLE_NAME);
private String mUri;
public UriMenuItem(String uri) {
super(sResources, ENTER_KEY_MENU_ITEM, 5, 5);
mUri = uri;
}
/**
* {@inheritDoc}
*/
public void run() {
try {
ApplicationManager manager = ApplicationManager.getApplicationManager();
int moduleHandle = CodeModuleManager
.getModuleHandleForClass(AuthenticatorApplication.class);
String moduleName = CodeModuleManager.getModuleName(moduleHandle);
manager.launch(moduleName + "?uri&" + Uri.encode(mUri));
} catch (ApplicationManagerException e) {
e.printStackTrace();
}
}
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
import net.rim.device.api.ui.component.ActiveFieldContext;
import net.rim.device.api.util.Factory;
/**
* Factory for {@link UriActiveFieldCookie} instances.
*/
public class UriActiveFieldCookieFactory implements Factory {
/**
* {@inheritDoc}
*/
public Object createInstance(Object initialData) {
if (initialData instanceof ActiveFieldContext) {
ActiveFieldContext context = (ActiveFieldContext) initialData;
String data = (String) context.getData();
return new UriActiveFieldCookie(data);
}
return null;
}
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.i18n.Locale;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.system.ApplicationManager;
import net.rim.device.api.system.Branding;
import net.rim.device.api.system.DeviceInfo;
/**
* Checks for software updates and invokes a callback if one is found.
*/
public class UpdateTask extends Thread {
private static String getApplicationVersion() {
ApplicationDescriptor app = ApplicationDescriptor
.currentApplicationDescriptor();
return app.getVersion();
}
private static String getPlatformVersion() {
ApplicationManager manager = ApplicationManager.getApplicationManager();
ApplicationDescriptor[] applications = manager.getVisibleApplications();
for (int i = 0; i < applications.length; i++) {
ApplicationDescriptor application = applications[i];
String moduleName = application.getModuleName();
if (moduleName.equals("net_rim_bb_ribbon_app")) {
return application.getVersion();
}
}
return null;
}
private static String getUserAgent() {
String deviceName = DeviceInfo.getDeviceName();
String version = getPlatformVersion();
String profile = System.getProperty("microedition.profiles");
String configuration = System.getProperty("microedition.configuration");
String applicationVersion = getApplicationVersion();
int vendorId = Branding.getVendorId();
return "BlackBerry" + deviceName + "/" + version + " Profile/" + profile
+ " Configuration/" + configuration + " VendorID/" + vendorId
+ " Application/" + applicationVersion;
}
private static String getLanguage() {
Locale locale = Locale.getDefault();
return locale.getLanguage();
}
private static String getEncoding(HttpConnection c) throws IOException {
String enc = "ISO-8859-1";
String contentType = c.getHeaderField("Content-Type");
if (contentType != null) {
String prefix = "charset=";
int beginIndex = contentType.indexOf(prefix);
if (beginIndex != -1) {
beginIndex += prefix.length();
int endIndex = contentType.indexOf(';', beginIndex);
if (endIndex != -1) {
enc = contentType.substring(beginIndex, endIndex);
} else {
enc = contentType.substring(beginIndex);
}
}
}
return enc.trim();
}
private static HttpConnection connect(String url) throws IOException {
if (DeviceInfo.isSimulator()) {
url += ";deviceside=true";
} else {
url += ";deviceside=false;ConnectionType=mds-public";
}
return (HttpConnection) Connector.open(url);
}
private final UpdateCallback mCallback;
public UpdateTask(UpdateCallback callback) {
if (callback == null) {
throw new NullPointerException();
}
mCallback = callback;
}
private String getMIDletVersion(Reader reader) throws IOException {
BufferedReader r = new BufferedReader(reader);
String prefix = "MIDlet-Version:";
for (String line = r.readLine(); line != null; line = r.readLine()) {
if (line.startsWith(prefix)) {
int beginIndex = prefix.length();
String value = line.substring(beginIndex);
return value.trim();
}
}
return null;
}
/**
* {@inheritDoc}
*/
public void run() {
try {
// Visit the original download URL and read the JAD;
// if the MIDlet-Version has changed, invoke the callback.
String url = Build.DOWNLOAD_URL;
String applicationVersion = getApplicationVersion();
String userAgent = getUserAgent();
String language = getLanguage();
for (int redirectCount = 0; redirectCount < 10; redirectCount++) {
HttpConnection c = null;
InputStream s = null;
try {
c = connect(url);
c.setRequestMethod(HttpConnection.GET);
c.setRequestProperty("User-Agent", userAgent);
c.setRequestProperty("Accept-Language", language);
int responseCode = c.getResponseCode();
if (responseCode == HttpConnection.HTTP_MOVED_PERM
|| responseCode == HttpConnection.HTTP_MOVED_TEMP) {
String location = c.getHeaderField("Location");
if (location != null) {
url = location;
continue;
} else {
throw new IOException("Location header missing");
}
} else if (responseCode != HttpConnection.HTTP_OK) {
throw new IOException("Unexpected response code: " + responseCode);
}
s = c.openInputStream();
String enc = getEncoding(c);
Reader reader = new InputStreamReader(s, enc);
final String version = getMIDletVersion(reader);
if (version == null) {
throw new IOException("MIDlet-Version not found");
} else if (!version.equals(applicationVersion)) {
Application application = Application.getApplication();
application.invokeLater(new Runnable() {
public void run() {
mCallback.onUpdate(version);
}
});
} else {
// Already running latest version
}
} finally {
if (s != null) {
s.close();
}
if (c != null) {
c.close();
}
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
import net.rim.device.api.system.RuntimeStore;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.util.StringPattern;
import net.rim.device.api.util.StringPatternRepository;
/**
* Main entry point.
*/
public class AuthenticatorApplication extends UiApplication {
public static final long FACTORY_ID = 0xdee739761f1b0a72L;
private static boolean sInitialized;
public static void main(String[] args) {
if (args != null && args.length >= 1 && "startup".equals(args[0])) {
// This entry-point is invoked when the device is rebooted.
registerStringPattern();
} else if (args != null && args.length >= 2 && "uri".equals(args[0])) {
// This entry-point is invoked when the user clicks on a URI containing
// the shared secret.
String uriString = Uri.decode(args[1]);
startApplication(Uri.parse(uriString));
} else {
// The default entry point starts the user interface.
startApplication(null);
}
}
/**
* Registers pattern matcher so that this application can handle certain URI
* schemes referenced in other applications.
*/
private static void registerStringPattern() {
if (!sInitialized) {
RuntimeStore runtimeStore = RuntimeStore.getRuntimeStore();
UriActiveFieldCookieFactory factory = new UriActiveFieldCookieFactory();
runtimeStore.put(FACTORY_ID, factory);
StringPattern pattern = new UriStringPattern();
StringPatternRepository.addPattern(pattern);
sInitialized = true;
}
}
private static void startApplication(Uri uri) {
UiApplication app = new AuthenticatorApplication();
AuthenticatorScreen screen = new AuthenticatorScreen();
app.pushScreen(screen);
if (uri != null) {
screen.parseSecret(uri);
screen.refreshUserList();
}
app.enterEventDispatcher();
}
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
import java.util.Hashtable;
/**
* Encodes arbitrary byte arrays as case-insensitive base-32 strings
*/
public class Base32String {
// singleton
private static final Base32String INSTANCE =
new Base32String("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"); // RFC 4668/3548
static Base32String getInstance() {
return INSTANCE;
}
// 32 alpha-numeric characters.
private String ALPHABET;
private char[] DIGITS;
private int MASK;
private int SHIFT;
private Hashtable CHAR_MAP;
static final String SEPARATOR = "-";
protected Base32String(String alphabet) {
this.ALPHABET = alphabet;
DIGITS = ALPHABET.toCharArray();
MASK = DIGITS.length - 1;
SHIFT = numberOfTrailingZeros(DIGITS.length);
CHAR_MAP = new Hashtable();
for (int i = 0; i < DIGITS.length; i++) {
CHAR_MAP.put(new Character(DIGITS[i]), new Integer(i));
}
}
/**
* Counts the number of 1 bits in the specified integer; this is also
* referred to as population count.
*
* @param i
* the integer to examine.
* @return the number of 1 bits in {@code i}.
*/
private static int bitCount(int i) {
i -= ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
i = (((i >> 4) + i) & 0x0F0F0F0F);
i += (i >> 8);
i += (i >> 16);
return (i & 0x0000003F);
}
/**
* Determines the number of trailing zeros in the specified integer after
* the {@link #lowestOneBit(int) lowest one bit}.
*
* @param i
* the integer to examine.
* @return the number of trailing zeros in {@code i}.
*/
private static int numberOfTrailingZeros(int i) {
return bitCount((i & -i) - 1);
}
public static byte[] decode(String encoded) throws DecodingException {
return getInstance().decodeInternal(encoded);
}
private static String canonicalize(String str) {
int length = str.length();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < length; i++) {
char c = str.charAt(i);
if (SEPARATOR.indexOf(c) == -1 && c != ' ') {
buffer.append(Character.toUpperCase(c));
}
}
return buffer.toString().trim();
}
protected byte[] decodeInternal(String encoded) throws DecodingException {
// Remove whitespace and separators
encoded = canonicalize(encoded);
// Canonicalize to all upper case
encoded = encoded.toUpperCase();
if (encoded.length() == 0) {
return new byte[0];
}
int encodedLength = encoded.length();
int outLength = encodedLength * SHIFT / 8;
byte[] result = new byte[outLength];
int buffer = 0;
int next = 0;
int bitsLeft = 0;
for (int i = 0, n = encoded.length(); i < n; i++) {
Character c = new Character(encoded.charAt(i));
if (!CHAR_MAP.containsKey(c)) {
throw new DecodingException("Illegal character: " + c);
}
buffer <<= SHIFT;
buffer |= ((Integer) CHAR_MAP.get(c)).intValue() & MASK;
bitsLeft += SHIFT;
if (bitsLeft >= 8) {
result[next++] = (byte) (buffer >> (bitsLeft - 8));
bitsLeft -= 8;
}
}
// We'll ignore leftover bits for now.
//
// if (next != outLength || bitsLeft >= SHIFT) {
// throw new DecodingException("Bits left: " + bitsLeft);
// }
return result;
}
public static String encode(byte[] data) {
return getInstance().encodeInternal(data);
}
protected String encodeInternal(byte[] data) {
if (data.length == 0) {
return "";
}
// SHIFT is the number of bits per output character, so the length of the
// output is the length of the input multiplied by 8/SHIFT, rounded up.
if (data.length >= (1 << 28)) {
// The computation below will fail, so don't do it.
throw new IllegalArgumentException();
}
int outputLength = (data.length * 8 + SHIFT - 1) / SHIFT;
StringBuffer result = new StringBuffer(outputLength);
int buffer = data[0];
int next = 1;
int bitsLeft = 8;
while (bitsLeft > 0 || next < data.length) {
if (bitsLeft < SHIFT) {
if (next < data.length) {
buffer <<= 8;
buffer |= (data[next++] & 0xff);
bitsLeft += 8;
} else {
int pad = SHIFT - bitsLeft;
buffer <<= pad;
bitsLeft += pad;
}
}
int index = MASK & (buffer >> (bitsLeft - SHIFT));
bitsLeft -= SHIFT;
result.append(DIGITS[index]);
}
return result.toString();
}
static class DecodingException extends Exception {
public DecodingException(String message) {
super(message);
}
}
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
/**
* A tuple of user, OTP value, and type, that represents a particular user.
*/
class PinInfo {
public String mPin; // calculated OTP, or a placeholder if not calculated
public String mUser;
public boolean mIsHotp = false; // used to see if button needs to be displayed
}
/**
* BlackBerry port of {@code PinListAdapter}.
*/
public class PinListFieldCallback implements ListFieldCallback {
private static final int PADDING = 4;
private final Font mUserFont;
private final Font mPinFont;
private final Bitmap mIcon;
private final int mRowHeight;
private final PinInfo[] mItems;
public PinListFieldCallback(PinInfo[] items) {
super();
mItems = items;
mUserFont = Font.getDefault().derive(Font.ITALIC);
mPinFont = Font.getDefault();
mIcon = Bitmap.getBitmapResource("ic_lock_lock.png");
mRowHeight = computeRowHeight();
}
private int computeRowHeight() {
int textHeight = mUserFont.getHeight() + mPinFont.getHeight();
int iconHeight = mIcon.getHeight();
return PADDING + Math.max(textHeight, iconHeight) + PADDING;
}
public int getRowHeight() {
return mRowHeight;
}
/**
* {@inheritDoc}
*/
public void drawListRow(ListField listField, Graphics graphics, int index,
int y, int width) {
PinInfo item = mItems[index];
int iconWidth = mIcon.getWidth();
int iconHeight = mIcon.getHeight();
int iconX = width - PADDING - iconWidth;
int iconY = y + Math.max(0, (mRowHeight - iconHeight) / 2);
graphics.drawBitmap(iconX, iconY, iconWidth, iconHeight, mIcon, 0, 0);
int textWidth = Math.max(0, width - iconWidth - PADDING * 3);
int textX = PADDING;
int textY = y + PADDING;
int flags = Graphics.ELLIPSIS;
Font savedFont = graphics.getFont();
graphics.setFont(mUserFont);
graphics.drawText(item.mUser, textX, textY, flags, textWidth);
textY += mUserFont.getHeight();
graphics.setFont(mPinFont);
graphics.drawText(item.mPin, textX, textY, flags, textWidth);
graphics.setFont(savedFont);
}
/**
* {@inheritDoc}
*/
public Object get(ListField listField, int index) {
return mItems[index];
}
/**
* {@inheritDoc}
*/
public int getPreferredWidth(ListField listField) {
return Integer.MAX_VALUE;
}
/**
* {@inheritDoc}
*/
public int indexOfList(ListField listField, String prefix, int start) {
for (int i = start; i < mItems.length; i++) {
PinInfo item = mItems[i];
// Check if username starts with prefix (ignoring case)
if (item.mUser.regionMatches(true, 0, prefix, 0, prefix.length())) {
return i;
}
}
return -1;
}
}
| Java |
/*-
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modifications:
* -Changed package name
* -Removed "@since Android 1.0" comments
* -Removed logging
* -Removed special error messages
* -Removed annotations
* -Replaced StringBuilder with StringBuffer
*/
package com.google.authenticator.blackberry;
import java.io.IOException;
import java.io.Reader;
/**
* Wraps an existing {@link Reader} and <em>buffers</em> the input. Expensive
* interaction with the underlying reader is minimized, since most (smaller)
* requests can be satisfied by accessing the buffer alone. The drawback is that
* some extra space is required to hold the buffer and that copying takes place
* when filling that buffer, but this is usually outweighed by the performance
* benefits.
*
* <p/>A typical application pattern for the class looks like this:<p/>
*
* <pre>
* BufferedReader buf = new BufferedReader(new FileReader("file.java"));
* </pre>
*
* @see BufferedWriter
*/
public class BufferedReader extends Reader {
private Reader in;
private char[] buf;
private int marklimit = -1;
private int count;
private int markpos = -1;
private int pos;
/**
* Constructs a new BufferedReader on the Reader {@code in}. The
* buffer gets the default size (8 KB).
*
* @param in
* the Reader that is buffered.
*/
public BufferedReader(Reader in) {
super(in);
this.in = in;
buf = new char[8192];
}
/**
* Constructs a new BufferedReader on the Reader {@code in}. The buffer
* size is specified by the parameter {@code size}.
*
* @param in
* the Reader that is buffered.
* @param size
* the size of the buffer to allocate.
* @throws IllegalArgumentException
* if {@code size <= 0}.
*/
public BufferedReader(Reader in, int size) {
super(in);
if (size <= 0) {
throw new IllegalArgumentException();
}
this.in = in;
buf = new char[size];
}
/**
* Closes this reader. This implementation closes the buffered source reader
* and releases the buffer. Nothing is done if this reader has already been
* closed.
*
* @throws IOException
* if an error occurs while closing this reader.
*/
public void close() throws IOException {
synchronized (lock) {
if (!isClosed()) {
in.close();
buf = null;
}
}
}
private int fillbuf() throws IOException {
if (markpos == -1 || (pos - markpos >= marklimit)) {
/* Mark position not set or exceeded readlimit */
int result = in.read(buf, 0, buf.length);
if (result > 0) {
markpos = -1;
pos = 0;
count = result == -1 ? 0 : result;
}
return result;
}
if (markpos == 0 && marklimit > buf.length) {
/* Increase buffer size to accommodate the readlimit */
int newLength = buf.length * 2;
if (newLength > marklimit) {
newLength = marklimit;
}
char[] newbuf = new char[newLength];
System.arraycopy(buf, 0, newbuf, 0, buf.length);
buf = newbuf;
} else if (markpos > 0) {
System.arraycopy(buf, markpos, buf, 0, buf.length - markpos);
}
/* Set the new position and mark position */
pos -= markpos;
count = markpos = 0;
int charsread = in.read(buf, pos, buf.length - pos);
count = charsread == -1 ? pos : pos + charsread;
return charsread;
}
/**
* Indicates whether or not this reader is closed.
*
* @return {@code true} if this reader is closed, {@code false}
* otherwise.
*/
private boolean isClosed() {
return buf == null;
}
/**
* Sets a mark position in this reader. The parameter {@code readlimit}
* indicates how many characters can be read before the mark is invalidated.
* Calling {@code reset()} will reposition the reader back to the marked
* position if {@code readlimit} has not been surpassed.
*
* @param readlimit
* the number of characters that can be read before the mark is
* invalidated.
* @throws IllegalArgumentException
* if {@code readlimit < 0}.
* @throws IOException
* if an error occurs while setting a mark in this reader.
* @see #markSupported()
* @see #reset()
*/
public void mark(int readlimit) throws IOException {
if (readlimit < 0) {
throw new IllegalArgumentException();
}
synchronized (lock) {
if (isClosed()) {
throw new IOException();
}
marklimit = readlimit;
markpos = pos;
}
}
/**
* Indicates whether this reader supports the {@code mark()} and
* {@code reset()} methods. This implementation returns {@code true}.
*
* @return {@code true} for {@code BufferedReader}.
* @see #mark(int)
* @see #reset()
*/
public boolean markSupported() {
return true;
}
/**
* Reads a single character from this reader and returns it with the two
* higher-order bytes set to 0. If possible, BufferedReader returns a
* character from the buffer. If there are no characters available in the
* buffer, it fills the buffer and then returns a character. It returns -1
* if there are no more characters in the source reader.
*
* @return the character read or -1 if the end of the source reader has been
* reached.
* @throws IOException
* if this reader is closed or some other I/O error occurs.
*/
public int read() throws IOException {
synchronized (lock) {
if (isClosed()) {
throw new IOException();
}
/* Are there buffered characters available? */
if (pos < count || fillbuf() != -1) {
return buf[pos++];
}
return -1;
}
}
/**
* Reads at most {@code length} characters from this reader and stores them
* at {@code offset} in the character array {@code buffer}. Returns the
* number of characters actually read or -1 if the end of the source reader
* has been reached. If all the buffered characters have been used, a mark
* has not been set and the requested number of characters is larger than
* this readers buffer size, BufferedReader bypasses the buffer and simply
* places the results directly into {@code buffer}.
*
* @param buffer
* the character array to store the characters read.
* @param offset
* the initial position in {@code buffer} to store the bytes read
* from this reader.
* @param length
* the maximum number of characters to read, must be
* non-negative.
* @return number of characters read or -1 if the end of the source reader
* has been reached.
* @throws IndexOutOfBoundsException
* if {@code offset < 0} or {@code length < 0}, or if
* {@code offset + length} is greater than the size of
* {@code buffer}.
* @throws IOException
* if this reader is closed or some other I/O error occurs.
*/
public int read(char[] buffer, int offset, int length) throws IOException {
synchronized (lock) {
if (isClosed()) {
throw new IOException();
}
if (length == 0) {
return 0;
}
int required;
if (pos < count) {
/* There are bytes available in the buffer. */
int copylength = count - pos >= length ? length : count - pos;
System.arraycopy(buf, pos, buffer, offset, copylength);
pos += copylength;
if (copylength == length || !in.ready()) {
return copylength;
}
offset += copylength;
required = length - copylength;
} else {
required = length;
}
while (true) {
int read;
/*
* If we're not marked and the required size is greater than the
* buffer, simply read the bytes directly bypassing the buffer.
*/
if (markpos == -1 && required >= buf.length) {
read = in.read(buffer, offset, required);
if (read == -1) {
return required == length ? -1 : length - required;
}
} else {
if (fillbuf() == -1) {
return required == length ? -1 : length - required;
}
read = count - pos >= required ? required : count - pos;
System.arraycopy(buf, pos, buffer, offset, read);
pos += read;
}
required -= read;
if (required == 0) {
return length;
}
if (!in.ready()) {
return length - required;
}
offset += read;
}
}
}
/**
* Returns the next line of text available from this reader. A line is
* represented by zero or more characters followed by {@code '\n'},
* {@code '\r'}, {@code "\r\n"} or the end of the reader. The string does
* not include the newline sequence.
*
* @return the contents of the line or {@code null} if no characters were
* read before the end of the reader has been reached.
* @throws IOException
* if this reader is closed or some other I/O error occurs.
*/
public String readLine() throws IOException {
synchronized (lock) {
if (isClosed()) {
throw new IOException();
}
/* Are there buffered characters available? */
if ((pos >= count) && (fillbuf() == -1)) {
return null;
}
for (int charPos = pos; charPos < count; charPos++) {
char ch = buf[charPos];
if (ch > '\r') {
continue;
}
if (ch == '\n') {
String res = new String(buf, pos, charPos - pos);
pos = charPos + 1;
return res;
} else if (ch == '\r') {
String res = new String(buf, pos, charPos - pos);
pos = charPos + 1;
if (((pos < count) || (fillbuf() != -1))
&& (buf[pos] == '\n')) {
pos++;
}
return res;
}
}
char eol = '\0';
StringBuffer result = new StringBuffer(80);
/* Typical Line Length */
result.append(buf, pos, count - pos);
pos = count;
while (true) {
/* Are there buffered characters available? */
if (pos >= count) {
if (eol == '\n') {
return result.toString();
}
// attempt to fill buffer
if (fillbuf() == -1) {
// characters or null.
return result.length() > 0 || eol != '\0' ? result
.toString() : null;
}
}
for (int charPos = pos; charPos < count; charPos++) {
if (eol == '\0') {
if ((buf[charPos] == '\n' || buf[charPos] == '\r')) {
eol = buf[charPos];
}
} else if (eol == '\r' && (buf[charPos] == '\n')) {
if (charPos > pos) {
result.append(buf, pos, charPos - pos - 1);
}
pos = charPos + 1;
return result.toString();
} else if (eol != '\0') {
if (charPos > pos) {
result.append(buf, pos, charPos - pos - 1);
}
pos = charPos;
return result.toString();
}
}
if (eol == '\0') {
result.append(buf, pos, count - pos);
} else {
result.append(buf, pos, count - pos - 1);
}
pos = count;
}
}
}
/**
* Indicates whether this reader is ready to be read without blocking.
*
* @return {@code true} if this reader will not block when {@code read} is
* called, {@code false} if unknown or blocking will occur.
* @throws IOException
* if this reader is closed or some other I/O error occurs.
* @see #read()
* @see #read(char[], int, int)
* @see #readLine()
*/
public boolean ready() throws IOException {
synchronized (lock) {
if (isClosed()) {
throw new IOException();
}
return ((count - pos) > 0) || in.ready();
}
}
/**
* Resets this reader's position to the last {@code mark()} location.
* Invocations of {@code read()} and {@code skip()} will occur from this new
* location.
*
* @throws IOException
* if this reader is closed or no mark has been set.
* @see #mark(int)
* @see #markSupported()
*/
public void reset() throws IOException {
synchronized (lock) {
if (isClosed()) {
throw new IOException();
}
if (markpos == -1) {
throw new IOException();
}
pos = markpos;
}
}
/**
* Skips {@code amount} characters in this reader. Subsequent
* {@code read()}s will not return these characters unless {@code reset()}
* is used. Skipping characters may invalidate a mark if {@code readlimit}
* is surpassed.
*
* @param amount
* the maximum number of characters to skip.
* @return the number of characters actually skipped.
* @throws IllegalArgumentException
* if {@code amount < 0}.
* @throws IOException
* if this reader is closed or some other I/O error occurs.
* @see #mark(int)
* @see #markSupported()
* @see #reset()
*/
public long skip(long amount) throws IOException {
if (amount < 0) {
throw new IllegalArgumentException();
}
synchronized (lock) {
if (isClosed()) {
throw new IOException();
}
if (amount < 1) {
return 0;
}
if (count - pos >= amount) {
pos += amount;
return amount;
}
long read = count - pos;
pos = count;
while (read < amount) {
if (fillbuf() == -1) {
return read;
}
if (count - pos >= amount - read) {
pos += amount - read;
return amount;
}
// Couldn't get all the characters, skip what we read
read += (count - pos);
pos = count;
}
return amount;
}
}
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
import java.util.Hashtable;
import java.util.Vector;
import com.google.authenticator.blackberry.resource.AuthenticatorResource;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.CodeModuleManager;
import net.rim.device.api.system.CodeSigningKey;
import net.rim.device.api.system.ControlledAccess;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
/**
* BlackBerry port of {@code AccountDb}.
*/
public class AccountDb {
private static final String TABLE_NAME = "accounts";
static final String ID_COLUMN = "_id";
static final String EMAIL_COLUMN = "email";
static final String SECRET_COLUMN = "secret";
static final String COUNTER_COLUMN = "counter";
static final String TYPE_COLUMN = "type";
static final Integer TYPE_LEGACY_TOTP = new Integer(-1); // TODO: remove April 2010
private static final long PERSISTENT_STORE_KEY = 0x9f1343901e600bf7L;
static Hashtable sPreferences;
static PersistentObject sPersistentObject;
/**
* Types of secret keys.
*/
public static class OtpType {
private static ResourceBundle sResources = ResourceBundle.getBundle(
AuthenticatorResource.BUNDLE_ID, AuthenticatorResource.BUNDLE_NAME);
public static final OtpType TOTP = new OtpType(0); // time based
public static final OtpType HOTP = new OtpType(1); // counter based
private static final OtpType[] values = { TOTP, HOTP };
public final Integer value; // value as stored in database
OtpType(int value) {
this.value = new Integer(value);
}
public static OtpType getEnum(Integer i) {
for (int index = 0; index < values.length; index++) {
OtpType type = values[index];
if (type.value.intValue() == i.intValue()) {
return type;
}
}
return null;
}
public static OtpType[] values() {
return values;
}
/**
* {@inheritDoc}
*/
public String toString() {
if (this == TOTP) {
return sResources.getString(AuthenticatorResource.TOTP);
} else if (this == HOTP) {
return sResources.getString(AuthenticatorResource.HOTP);
} else {
return super.toString();
}
}
}
private AccountDb() {
// Don't new me
}
static {
sPersistentObject = PersistentStore.getPersistentObject(PERSISTENT_STORE_KEY);
sPreferences = (Hashtable) sPersistentObject.getContents();
if (sPreferences == null) {
sPreferences = new Hashtable();
}
// Use an instance of a class owned by this application
// to easily get the appropriate CodeSigningKey:
Object appObject = new FieldUtils();
// Get the public code signing key
CodeSigningKey codeSigningKey = CodeSigningKey.get(appObject);
if (codeSigningKey == null) {
throw new SecurityException("Code not protected by a signing key");
}
// Ensure that the code has been signed with the corresponding private key
int moduleHandle = CodeModuleManager.getModuleHandleForObject(appObject);
if (!ControlledAccess.verifyCodeModuleSignature(moduleHandle, codeSigningKey)) {
String signerId = codeSigningKey.getSignerId();
throw new SecurityException("Code not signed by " + signerId + " key");
}
Object contents = sPreferences;
// Only allow signed applications to access user data
contents = new ControlledAccess(contents, codeSigningKey);
sPersistentObject.setContents(contents);
sPersistentObject.commit();
}
private static Vector getAccounts() {
Vector accounts = (Vector) sPreferences.get(TABLE_NAME);
if (accounts == null) {
accounts = new Vector(10);
sPreferences.put(TABLE_NAME, accounts);
sPersistentObject.commit();
}
return accounts;
}
private static Hashtable getAccount(String email) {
if (email == null) {
throw new NullPointerException();
}
Vector accounts = getAccounts();
for (int i = 0, n = accounts.size(); i < n; i++) {
Hashtable account = (Hashtable) accounts.elementAt(i);
if (email.equals(account.get(EMAIL_COLUMN))) {
return account;
}
}
return null;
}
static String[] getNames() {
Vector accounts = getAccounts();
int size = accounts.size();
String[] names = new String[size];
for (int i = 0; i < size; i++) {
Hashtable account = (Hashtable) accounts.elementAt(i);
names[i] = (String) account.get(EMAIL_COLUMN);
}
return names;
}
static boolean nameExists(String email) {
Hashtable account = getAccount(email);
return account != null;
}
static String getSecret(String email) {
Hashtable account = getAccount(email);
return account != null ? (String) account.get(SECRET_COLUMN) : null;
}
static Integer getCounter(String email) {
Hashtable account = getAccount(email);
return account != null ? (Integer) account.get(COUNTER_COLUMN) : null;
}
static void incrementCounter(String email) {
Hashtable account = getAccount(email);
if (account != null) {
Integer counter = (Integer) account.get(COUNTER_COLUMN);
counter = new Integer(counter.intValue() + 1);
account.put(COUNTER_COLUMN, counter);
sPersistentObject.commit();
}
}
static OtpType getType(String user) {
Hashtable account = getAccount(user);
if (account != null) {
Integer value = (Integer) account.get(TYPE_COLUMN);
return OtpType.getEnum(value);
} else {
return null;
}
}
static void delete(String email) {
Vector accounts = getAccounts();
boolean modified = false;
for (int index = 0; index < accounts.size();) {
Hashtable account = (Hashtable) accounts.elementAt(index);
if (email.equals(account.get(EMAIL_COLUMN))) {
accounts.removeElementAt(index);
modified = true;
} else {
index++;
}
}
if (modified) {
sPersistentObject.commit();
}
}
/**
* Save key to database, creating a new user entry if necessary.
* @param email the user email address. When editing, the new user email.
* @param secret the secret key.
* @param oldEmail If editing, the original user email, otherwise null.
*/
static void update(String email, String secret, String oldEmail,
AccountDb.OtpType type) {
Hashtable account = oldEmail != null ? getAccount(oldEmail) : null;
if (account == null) {
account = new Hashtable(10);
Vector accounts = getAccounts();
accounts.addElement(account);
}
account.put(EMAIL_COLUMN, email);
account.put(SECRET_COLUMN, secret);
account.put(TYPE_COLUMN, type.value);
if (!account.containsKey(COUNTER_COLUMN)) {
account.put(COUNTER_COLUMN, new Integer(0));
}
sPersistentObject.commit();
}
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
import net.rim.blackberry.api.browser.Browser;
import net.rim.blackberry.api.browser.BrowserSession;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.Alert;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;
import org.bouncycastle.crypto.Mac;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import com.google.authenticator.blackberry.AccountDb.OtpType;
import com.google.authenticator.blackberry.Base32String.DecodingException;
import com.google.authenticator.blackberry.resource.AuthenticatorResource;
/**
* BlackBerry port of {@code AuthenticatorActivity}.
*/
public class AuthenticatorScreen extends MainScreen implements UpdateCallback,
AuthenticatorResource, Runnable {
private static ResourceBundle sResources = ResourceBundle.getBundle(
BUNDLE_ID, BUNDLE_NAME);
private static final int VIBRATE_DURATION = 200;
private static final long REFRESH_INTERVAL = 30 * 1000;
private static final boolean AUTO_REFRESH = true;
private static final String TERMS_URL = "http://www.google.com/accounts/TOS";
private static final String PRIVACY_URL = "http://www.google.com/mobile/privacy.html";
/**
* Computes the one-time PIN given the secret key.
*
* @param secret
* the secret key
* @return the PIN
* @throws GeneralSecurityException
* @throws DecodingException
* If the key string is improperly encoded.
*/
public static String computePin(String secret, Long counter) {
try {
final byte[] keyBytes = Base32String.decode(secret);
Mac mac = new HMac(new SHA1Digest());
mac.init(new KeyParameter(keyBytes));
PasscodeGenerator pcg = new PasscodeGenerator(mac);
if (counter == null) { // time-based totp
return pcg.generateTimeoutCode();
} else { // counter-based hotp
return pcg.generateResponseCode(counter.longValue());
}
} catch (RuntimeException e) {
return "General security exception";
} catch (DecodingException e) {
return "Decoding exception";
}
}
/**
* Parses a secret value from a URI. The format will be:
*
* <pre>
* https://www.google.com/accounts/KeyProv?user=username#secret
* OR
* totp://username@domain#secret
* otpauth://totp/user@example.com?secret=FFF...
* otpauth://hotp/user@example.com?secret=FFF...&counter=123
* </pre>
*
* @param uri The URI containing the secret key
*/
void parseSecret(Uri uri) {
String scheme = uri.getScheme().toLowerCase();
String path = uri.getPath();
String authority = uri.getAuthority();
String user = DEFAULT_USER;
String secret;
AccountDb.OtpType type = AccountDb.OtpType.TOTP;
Integer counter = new Integer(0); // only interesting for HOTP
if (OTP_SCHEME.equals(scheme)) {
if (authority != null && authority.equals(TOTP)) {
type = AccountDb.OtpType.TOTP;
} else if (authority != null && authority.equals(HOTP)) {
type = AccountDb.OtpType.HOTP;
String counterParameter = uri.getQueryParameter(COUNTER_PARAM);
if (counterParameter != null) {
counter = Integer.valueOf(counterParameter);
}
}
if (path != null && path.length() > 1) {
user = path.substring(1); // path is "/user", so remove leading /
}
secret = uri.getQueryParameter(SECRET_PARAM);
// TODO: remove TOTP scheme
} else if (TOTP.equals(scheme)) {
if (authority != null) {
user = authority;
}
secret = uri.getFragment();
} else { // https://www.google.com... URI format
String userParam = uri.getQueryParameter(USER_PARAM);
if (userParam != null) {
user = userParam;
}
secret = uri.getFragment();
}
if (secret == null) {
// Secret key not found in URI
return;
}
// TODO: April 2010 - remove version parameter handling.
String version = uri.getQueryParameter(VERSION_PARAM);
if (version == null) { // version is null for legacy URIs
try {
secret = Base32String.encode(Base32Legacy.decode(secret));
} catch (DecodingException e) {
// Error decoding legacy key from URI
e.printStackTrace();
}
}
if (!secret.equals(getSecret(user)) ||
counter != AccountDb.getCounter(user) ||
type != AccountDb.getType(user)) {
saveSecret(user, secret, null, type);
mStatusText.setText(sResources.getString(SECRET_SAVED));
}
}
static String getSecret(String user) {
return AccountDb.getSecret(user);
}
static void saveSecret(String user, String secret,
String originalUser, AccountDb.OtpType type) {
if (originalUser == null) {
originalUser = user;
}
if (secret != null) {
AccountDb.update(user, secret, originalUser, type);
Alert.startVibrate(VIBRATE_DURATION);
}
}
private LabelField mVersionText;
private LabelField mStatusText;
private RichTextField mEnterPinTextView;
private PinListField mUserList;
private PinListFieldCallback mUserAdapter;
private PinInfo[] mUsers = {};
private boolean mUpdateAvailable;
private int mTimer = -1;
static final String DEFAULT_USER = "Default account";
private static final String OTP_SCHEME = "otpauth";
private static final String TOTP = "totp"; // time-based
private static final String HOTP = "hotp"; // counter-based
private static final String USER_PARAM = "user";
private static final String SECRET_PARAM = "secret";
private static final String VERSION_PARAM = "v";
private static final String COUNTER_PARAM = "counter";
public AuthenticatorScreen() {
setTitle(sResources.getString(APP_NAME));
// LabelField cannot scroll content that is bigger than the screen,
// so use RichTextField instead.
mEnterPinTextView = new RichTextField(sResources.getString(ENTER_PIN));
mUserList = new PinListField();
mUserAdapter = new PinListFieldCallback(mUsers);
setAdapter();
ApplicationDescriptor applicationDescriptor = ApplicationDescriptor
.currentApplicationDescriptor();
String version = applicationDescriptor.getVersion();
mVersionText = new LabelField(version, FIELD_RIGHT | FIELD_BOTTOM);
mStatusText = new LabelField("", FIELD_HCENTER | FIELD_BOTTOM);
add(mEnterPinTextView);
add(mUserList);
add(new LabelField(" ")); // One-line spacer
add(mStatusText);
add(mVersionText);
FieldUtils.setVisible(mEnterPinTextView, false);
UpdateCallback callback = this;
new UpdateTask(callback).start();
}
private void setAdapter() {
int lastIndex = mUserList.getSelectedIndex();
mUserList.setCallback(mUserAdapter);
mUserList.setSize(mUsers.length);
mUserList.setRowHeight(mUserAdapter.getRowHeight());
mUserList.setSelectedIndex(lastIndex);
}
/**
* {@inheritDoc}
*/
protected void onDisplay() {
super.onDisplay();
onResume();
}
/**
* {@inheritDoc}
*/
protected void onExposed() {
super.onExposed();
onResume();
}
/**
* {@inheritDoc}
*/
protected void onObscured() {
onPause();
super.onObscured();
}
private void onResume() {
refreshUserList();
if (AUTO_REFRESH) {
startTimer();
}
}
private void onPause() {
if (isTimerSet()) {
stopTimer();
}
}
private boolean isTimerSet() {
return mTimer != -1;
}
private void startTimer() {
if (isTimerSet()) {
stopTimer();
}
Application application = getApplication();
Runnable runnable = this;
boolean repeat = true;
mTimer = application.invokeLater(runnable, REFRESH_INTERVAL, repeat);
}
private void stopTimer() {
if (isTimerSet()) {
Application application = getApplication();
application.cancelInvokeLater(mTimer);
mTimer = -1;
}
}
/**
* {@inheritDoc}
*/
public void run() {
refreshUserList();
}
void refreshUserList() {
String[] cursor = AccountDb.getNames();
if (cursor.length > 0) {
if (mUsers.length != cursor.length) {
mUsers = new PinInfo[cursor.length];
}
for (int i = 0; i < cursor.length; i++) {
String user = cursor[i];
computeAndDisplayPin(user, i, false);
}
mUserAdapter = new PinListFieldCallback(mUsers);
setAdapter(); // force refresh of display
if (!FieldUtils.isVisible(mUserList)) {
mEnterPinTextView.setText(sResources.getString(ENTER_PIN));
FieldUtils.setVisible(mEnterPinTextView, true);
FieldUtils.setVisible(mUserList, true);
}
} else {
// If the user started up this app but there is no secret key yet,
// then tell the user to visit a web page to get the secret key.
mUsers = new PinInfo[0]; // clear any existing user PIN state
tellUserToGetSecretKey();
}
}
/**
* Tells the user to visit a web page to get a secret key.
*/
private void tellUserToGetSecretKey() {
// TODO: fill this in with code to send our phone number to the server
String notInitialized = sResources.getString(NOT_INITIALIZED);
mEnterPinTextView.setText(notInitialized);
FieldUtils.setVisible(mEnterPinTextView, true);
FieldUtils.setVisible(mUserList, false);
}
/**
* Computes the PIN and saves it in mUsers. This currently runs in the UI
* thread so it should not take more than a second or so. If necessary, we can
* move the computation to a background thread.
*
* @param user the user email to display with the PIN
* @param position the index for the screen of this user and PIN
* @param computeHotp true if we should increment counter and display new hotp
*
* @return the generated PIN
*/
String computeAndDisplayPin(String user, int position, boolean computeHotp) {
OtpType type = AccountDb.getType(user);
String secret = getSecret(user);
PinInfo currentPin;
if (mUsers[position] != null) {
currentPin = mUsers[position]; // existing PinInfo, so we'll update it
} else {
currentPin = new PinInfo();
currentPin.mPin = sResources.getString(EMPTY_PIN);
}
currentPin.mUser = user;
if (type == OtpType.TOTP) {
currentPin.mPin = computePin(secret, null);
} else if (type == OtpType.HOTP) {
currentPin.mIsHotp = true;
if (computeHotp) {
AccountDb.incrementCounter(user);
Integer counter = AccountDb.getCounter(user);
currentPin.mPin = computePin(secret, new Long(counter.longValue()));
}
}
mUsers[position] = currentPin;
return currentPin.mPin;
}
private void pushScreen(Screen screen) {
UiApplication app = (UiApplication) getApplication();
app.pushScreen(screen);
}
/**
* {@inheritDoc}
*/
public Menu getMenu(int instance) {
if (instance == Menu.INSTANCE_CONTEXT) {
// Show the full menu instead of the context menu
return super.getMenu(Menu.INSTANCE_DEFAULT);
} else {
return super.getMenu(instance);
}
}
/**
* {@inheritDoc}
*/
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
MenuItem enterKeyItem = new MenuItem(sResources, ENTER_KEY_MENU_ITEM, 0, 0) {
public void run() {
pushScreen(new EnterKeyScreen());
}
};
MenuItem termsItem = new MenuItem(sResources, TERMS_MENU_ITEM, 0, 0) {
public void run() {
BrowserSession session = Browser.getDefaultSession();
session.displayPage(TERMS_URL);
}
};
MenuItem privacyItem = new MenuItem(sResources, PRIVACY_MENU_ITEM, 0, 0) {
public void run() {
BrowserSession session = Browser.getDefaultSession();
session.displayPage(PRIVACY_URL);
}
};
menu.add(enterKeyItem);
if (!isTimerSet()) {
MenuItem refreshItem = new MenuItem(sResources, REFRESH_MENU_ITEM, 0, 0) {
public void run() {
refreshUserList();
}
};
menu.add(refreshItem);
}
if (mUpdateAvailable) {
MenuItem updateItem = new MenuItem(sResources, UPDATE_NOW, 0, 0) {
public void run() {
BrowserSession session = Browser.getDefaultSession();
session.displayPage(Build.DOWNLOAD_URL);
mStatusText.setText("");
}
};
menu.add(updateItem);
}
menu.add(termsItem);
menu.add(privacyItem);
}
/**
* {@inheritDoc}
*/
public void onUpdate(String version) {
String status = sResources.getString(UPDATE_AVAILABLE) + ": " + version;
mStatusText.setText(status);
mUpdateAvailable = true;
}
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
import java.util.Vector;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.ActiveFieldCookie;
import net.rim.device.api.ui.component.CookieProvider;
/**
* Handler for input events and context menus on URLs containing shared secrets.
*/
public class UriActiveFieldCookie implements ActiveFieldCookie {
private String mUrl;
public UriActiveFieldCookie(String data) {
mUrl = data;
}
/**
* {@inheritDoc}
*/
public boolean invokeApplicationKeyVerb() {
return false;
}
public MenuItem getFocusVerbs(CookieProvider provider, Object context,
Vector items) {
items.addElement(new UriMenuItem(mUrl));
return (MenuItem) items.elementAt(0);
}
}
| Java |
/*-
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modifications:
* -Changed package name
* -Removed Android dependencies
* -Removed/replaced Java SE dependencies
* -Removed/replaced annotations
*/
package com.google.authenticator.blackberry;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.ByteArrayOutputStream;
import java.util.Vector;
/**
* Immutable URI reference. A URI reference includes a URI and a fragment, the
* component of the URI following a '#'. Builds and parses URI references
* which conform to
* <a href="http://www.faqs.org/rfcs/rfc2396.html">RFC 2396</a>.
*
* <p>In the interest of performance, this class performs little to no
* validation. Behavior is undefined for invalid input. This class is very
* forgiving--in the face of invalid input, it will return garbage
* rather than throw an exception unless otherwise specified.
*/
public abstract class Uri {
/*
This class aims to do as little up front work as possible. To accomplish
that, we vary the implementation dependending on what the user passes in.
For example, we have one implementation if the user passes in a
URI string (StringUri) and another if the user passes in the
individual components (OpaqueUri).
*Concurrency notes*: Like any truly immutable object, this class is safe
for concurrent use. This class uses a caching pattern in some places where
it doesn't use volatile or synchronized. This is safe to do with ints
because getting or setting an int is atomic. It's safe to do with a String
because the internal fields are final and the memory model guarantees other
threads won't see a partially initialized instance. We are not guaranteed
that some threads will immediately see changes from other threads on
certain platforms, but we don't mind if those threads reconstruct the
cached result. As a result, we get thread safe caching with no concurrency
overhead, which means the most common case, access from a single thread,
is as fast as possible.
From the Java Language spec.:
"17.5 Final Field Semantics
... when the object is seen by another thread, that thread will always
see the correctly constructed version of that object's final fields.
It will also see versions of any object or array referenced by
those final fields that are at least as up-to-date as the final fields
are."
In that same vein, all non-transient fields within Uri
implementations should be final and immutable so as to ensure true
immutability for clients even when they don't use proper concurrency
control.
For reference, from RFC 2396:
"4.3. Parsing a URI Reference
A URI reference is typically parsed according to the four main
components and fragment identifier in order to determine what
components are present and whether the reference is relative or
absolute. The individual components are then parsed for their
subparts and, if not opaque, to verify their validity.
Although the BNF defines what is allowed in each component, it is
ambiguous in terms of differentiating between an authority component
and a path component that begins with two slash characters. The
greedy algorithm is used for disambiguation: the left-most matching
rule soaks up as much of the URI reference string as it is capable of
matching. In other words, the authority component wins."
The "four main components" of a hierarchical URI consist of
<scheme>://<authority><path>?<query>
*/
/**
* NOTE: EMPTY accesses this field during its own initialization, so this
* field *must* be initialized first, or else EMPTY will see a null value!
*
* Placeholder for strings which haven't been cached. This enables us
* to cache null. We intentionally create a new String instance so we can
* compare its identity and there is no chance we will confuse it with
* user data.
*/
private static final String NOT_CACHED = new String("NOT CACHED");
/**
* The empty URI, equivalent to "".
*/
public static final Uri EMPTY = new HierarchicalUri(null, Part.NULL,
PathPart.EMPTY, Part.NULL, Part.NULL);
/**
* Prevents external subclassing.
*/
private Uri() {}
/**
* Returns true if this URI is hierarchical like "http://google.com".
* Absolute URIs are hierarchical if the scheme-specific part starts with
* a '/'. Relative URIs are always hierarchical.
*/
public abstract boolean isHierarchical();
/**
* Returns true if this URI is opaque like "mailto:nobody@google.com". The
* scheme-specific part of an opaque URI cannot start with a '/'.
*/
public boolean isOpaque() {
return !isHierarchical();
}
/**
* Returns true if this URI is relative, i.e. if it doesn't contain an
* explicit scheme.
*
* @return true if this URI is relative, false if it's absolute
*/
public abstract boolean isRelative();
/**
* Returns true if this URI is absolute, i.e. if it contains an
* explicit scheme.
*
* @return true if this URI is absolute, false if it's relative
*/
public boolean isAbsolute() {
return !isRelative();
}
/**
* Gets the scheme of this URI. Example: "http"
*
* @return the scheme or null if this is a relative URI
*/
public abstract String getScheme();
/**
* Gets the scheme-specific part of this URI, i.e. everything between the
* scheme separator ':' and the fragment separator '#'. If this is a
* relative URI, this method returns the entire URI. Decodes escaped octets.
*
* <p>Example: "//www.google.com/search?q=android"
*
* @return the decoded scheme-specific-part
*/
public abstract String getSchemeSpecificPart();
/**
* Gets the scheme-specific part of this URI, i.e. everything between the
* scheme separator ':' and the fragment separator '#'. If this is a
* relative URI, this method returns the entire URI. Leaves escaped octets
* intact.
*
* <p>Example: "//www.google.com/search?q=android"
*
* @return the decoded scheme-specific-part
*/
public abstract String getEncodedSchemeSpecificPart();
/**
* Gets the decoded authority part of this URI. For
* server addresses, the authority is structured as follows:
* {@code [ userinfo '@' ] host [ ':' port ]}
*
* <p>Examples: "google.com", "bob@google.com:80"
*
* @return the authority for this URI or null if not present
*/
public abstract String getAuthority();
/**
* Gets the encoded authority part of this URI. For
* server addresses, the authority is structured as follows:
* {@code [ userinfo '@' ] host [ ':' port ]}
*
* <p>Examples: "google.com", "bob@google.com:80"
*
* @return the authority for this URI or null if not present
*/
public abstract String getEncodedAuthority();
/**
* Gets the decoded user information from the authority.
* For example, if the authority is "nobody@google.com", this method will
* return "nobody".
*
* @return the user info for this URI or null if not present
*/
public abstract String getUserInfo();
/**
* Gets the encoded user information from the authority.
* For example, if the authority is "nobody@google.com", this method will
* return "nobody".
*
* @return the user info for this URI or null if not present
*/
public abstract String getEncodedUserInfo();
/**
* Gets the encoded host from the authority for this URI. For example,
* if the authority is "bob@google.com", this method will return
* "google.com".
*
* @return the host for this URI or null if not present
*/
public abstract String getHost();
/**
* Gets the port from the authority for this URI. For example,
* if the authority is "google.com:80", this method will return 80.
*
* @return the port for this URI or -1 if invalid or not present
*/
public abstract int getPort();
/**
* Gets the decoded path.
*
* @return the decoded path, or null if this is not a hierarchical URI
* (like "mailto:nobody@google.com") or the URI is invalid
*/
public abstract String getPath();
/**
* Gets the encoded path.
*
* @return the encoded path, or null if this is not a hierarchical URI
* (like "mailto:nobody@google.com") or the URI is invalid
*/
public abstract String getEncodedPath();
/**
* Gets the decoded query component from this URI. The query comes after
* the query separator ('?') and before the fragment separator ('#'). This
* method would return "q=android" for
* "http://www.google.com/search?q=android".
*
* @return the decoded query or null if there isn't one
*/
public abstract String getQuery();
/**
* Gets the encoded query component from this URI. The query comes after
* the query separator ('?') and before the fragment separator ('#'). This
* method would return "q=android" for
* "http://www.google.com/search?q=android".
*
* @return the encoded query or null if there isn't one
*/
public abstract String getEncodedQuery();
/**
* Gets the decoded fragment part of this URI, everything after the '#'.
*
* @return the decoded fragment or null if there isn't one
*/
public abstract String getFragment();
/**
* Gets the encoded fragment part of this URI, everything after the '#'.
*
* @return the encoded fragment or null if there isn't one
*/
public abstract String getEncodedFragment();
/**
* Gets the decoded path segments.
*
* @return decoded path segments, each without a leading or trailing '/'
*/
public abstract String[] getPathSegments();
/**
* Gets the decoded last segment in the path.
*
* @return the decoded last segment or null if the path is empty
*/
public abstract String getLastPathSegment();
/**
* Compares this Uri to another object for equality. Returns true if the
* encoded string representations of this Uri and the given Uri are
* equal. Case counts. Paths are not normalized. If one Uri specifies a
* default port explicitly and the other leaves it implicit, they will not
* be considered equal.
*/
public boolean equals(Object o) {
if (!(o instanceof Uri)) {
return false;
}
Uri other = (Uri) o;
return toString().equals(other.toString());
}
/**
* Hashes the encoded string represention of this Uri consistently with
* {@link #equals(Object)}.
*/
public int hashCode() {
return toString().hashCode();
}
/**
* Compares the string representation of this Uri with that of
* another.
*/
public int compareTo(Uri other) {
return toString().compareTo(other.toString());
}
/**
* Returns the encoded string representation of this URI.
* Example: "http://google.com/"
*/
public abstract String toString();
/**
* Constructs a new builder, copying the attributes from this Uri.
*/
public abstract Builder buildUpon();
/** Index of a component which was not found. */
private final static int NOT_FOUND = -1;
/** Placeholder value for an index which hasn't been calculated yet. */
private final static int NOT_CALCULATED = -2;
/**
* Error message presented when a user tries to treat an opaque URI as
* hierarchical.
*/
private static final String NOT_HIERARCHICAL
= "This isn't a hierarchical URI.";
/** Default encoding. */
private static final String DEFAULT_ENCODING = "UTF-8";
/**
* Creates a Uri which parses the given encoded URI string.
*
* @param uriString an RFC 2396-compliant, encoded URI
* @throws NullPointerException if uriString is null
* @return Uri for this given uri string
*/
public static Uri parse(String uriString) {
return new StringUri(uriString);
}
/**
* An implementation which wraps a String URI. This URI can be opaque or
* hierarchical, but we extend AbstractHierarchicalUri in case we need
* the hierarchical functionality.
*/
private static class StringUri extends AbstractHierarchicalUri {
/** Used in parcelling. */
static final int TYPE_ID = 1;
/** URI string representation. */
private final String uriString;
private StringUri(String uriString) {
if (uriString == null) {
throw new NullPointerException("uriString");
}
this.uriString = uriString;
}
/** Cached scheme separator index. */
private volatile int cachedSsi = NOT_CALCULATED;
/** Finds the first ':'. Returns -1 if none found. */
private int findSchemeSeparator() {
return cachedSsi == NOT_CALCULATED
? cachedSsi = uriString.indexOf(':')
: cachedSsi;
}
/** Cached fragment separator index. */
private volatile int cachedFsi = NOT_CALCULATED;
/** Finds the first '#'. Returns -1 if none found. */
private int findFragmentSeparator() {
return cachedFsi == NOT_CALCULATED
? cachedFsi = uriString.indexOf('#', findSchemeSeparator())
: cachedFsi;
}
public boolean isHierarchical() {
int ssi = findSchemeSeparator();
if (ssi == NOT_FOUND) {
// All relative URIs are hierarchical.
return true;
}
if (uriString.length() == ssi + 1) {
// No ssp.
return false;
}
// If the ssp starts with a '/', this is hierarchical.
return uriString.charAt(ssi + 1) == '/';
}
public boolean isRelative() {
// Note: We return true if the index is 0
return findSchemeSeparator() == NOT_FOUND;
}
private volatile String scheme = NOT_CACHED;
public String getScheme() {
boolean cached = (scheme != NOT_CACHED);
return cached ? scheme : (scheme = parseScheme());
}
private String parseScheme() {
int ssi = findSchemeSeparator();
return ssi == NOT_FOUND ? null : uriString.substring(0, ssi);
}
private Part ssp;
private Part getSsp() {
return ssp == null ? ssp = Part.fromEncoded(parseSsp()) : ssp;
}
public String getEncodedSchemeSpecificPart() {
return getSsp().getEncoded();
}
public String getSchemeSpecificPart() {
return getSsp().getDecoded();
}
private String parseSsp() {
int ssi = findSchemeSeparator();
int fsi = findFragmentSeparator();
// Return everything between ssi and fsi.
return fsi == NOT_FOUND
? uriString.substring(ssi + 1)
: uriString.substring(ssi + 1, fsi);
}
private Part authority;
private Part getAuthorityPart() {
if (authority == null) {
String encodedAuthority
= parseAuthority(this.uriString, findSchemeSeparator());
return authority = Part.fromEncoded(encodedAuthority);
}
return authority;
}
public String getEncodedAuthority() {
return getAuthorityPart().getEncoded();
}
public String getAuthority() {
return getAuthorityPart().getDecoded();
}
private PathPart path;
private PathPart getPathPart() {
return path == null
? path = PathPart.fromEncoded(parsePath())
: path;
}
public String getPath() {
return getPathPart().getDecoded();
}
public String getEncodedPath() {
return getPathPart().getEncoded();
}
public String[] getPathSegments() {
return getPathPart().getPathSegments().segments;
}
private String parsePath() {
String uriString = this.uriString;
int ssi = findSchemeSeparator();
// If the URI is absolute.
if (ssi > -1) {
// Is there anything after the ':'?
boolean schemeOnly = ssi + 1 == uriString.length();
if (schemeOnly) {
// Opaque URI.
return null;
}
// A '/' after the ':' means this is hierarchical.
if (uriString.charAt(ssi + 1) != '/') {
// Opaque URI.
return null;
}
} else {
// All relative URIs are hierarchical.
}
return parsePath(uriString, ssi);
}
private Part query;
private Part getQueryPart() {
return query == null
? query = Part.fromEncoded(parseQuery()) : query;
}
public String getEncodedQuery() {
return getQueryPart().getEncoded();
}
private String parseQuery() {
// It doesn't make sense to cache this index. We only ever
// calculate it once.
int qsi = uriString.indexOf('?', findSchemeSeparator());
if (qsi == NOT_FOUND) {
return null;
}
int fsi = findFragmentSeparator();
if (fsi == NOT_FOUND) {
return uriString.substring(qsi + 1);
}
if (fsi < qsi) {
// Invalid.
return null;
}
return uriString.substring(qsi + 1, fsi);
}
public String getQuery() {
return getQueryPart().getDecoded();
}
private Part fragment;
private Part getFragmentPart() {
return fragment == null
? fragment = Part.fromEncoded(parseFragment()) : fragment;
}
public String getEncodedFragment() {
return getFragmentPart().getEncoded();
}
private String parseFragment() {
int fsi = findFragmentSeparator();
return fsi == NOT_FOUND ? null : uriString.substring(fsi + 1);
}
public String getFragment() {
return getFragmentPart().getDecoded();
}
public String toString() {
return uriString;
}
/**
* Parses an authority out of the given URI string.
*
* @param uriString URI string
* @param ssi scheme separator index, -1 for a relative URI
*
* @return the authority or null if none is found
*/
static String parseAuthority(String uriString, int ssi) {
int length = uriString.length();
// If "//" follows the scheme separator, we have an authority.
if (length > ssi + 2
&& uriString.charAt(ssi + 1) == '/'
&& uriString.charAt(ssi + 2) == '/') {
// We have an authority.
// Look for the start of the path, query, or fragment, or the
// end of the string.
int end = ssi + 3;
LOOP: while (end < length) {
switch (uriString.charAt(end)) {
case '/': // Start of path
case '?': // Start of query
case '#': // Start of fragment
break LOOP;
}
end++;
}
return uriString.substring(ssi + 3, end);
} else {
return null;
}
}
/**
* Parses a path out of this given URI string.
*
* @param uriString URI string
* @param ssi scheme separator index, -1 for a relative URI
*
* @return the path
*/
static String parsePath(String uriString, int ssi) {
int length = uriString.length();
// Find start of path.
int pathStart;
if (length > ssi + 2
&& uriString.charAt(ssi + 1) == '/'
&& uriString.charAt(ssi + 2) == '/') {
// Skip over authority to path.
pathStart = ssi + 3;
LOOP: while (pathStart < length) {
switch (uriString.charAt(pathStart)) {
case '?': // Start of query
case '#': // Start of fragment
return ""; // Empty path.
case '/': // Start of path!
break LOOP;
}
pathStart++;
}
} else {
// Path starts immediately after scheme separator.
pathStart = ssi + 1;
}
// Find end of path.
int pathEnd = pathStart;
LOOP: while (pathEnd < length) {
switch (uriString.charAt(pathEnd)) {
case '?': // Start of query
case '#': // Start of fragment
break LOOP;
}
pathEnd++;
}
return uriString.substring(pathStart, pathEnd);
}
public Builder buildUpon() {
if (isHierarchical()) {
return new Builder()
.scheme(getScheme())
.authority(getAuthorityPart())
.path(getPathPart())
.query(getQueryPart())
.fragment(getFragmentPart());
} else {
return new Builder()
.scheme(getScheme())
.opaquePart(getSsp())
.fragment(getFragmentPart());
}
}
}
/**
* Creates an opaque Uri from the given components. Encodes the ssp
* which means this method cannot be used to create hierarchical URIs.
*
* @param scheme of the URI
* @param ssp scheme-specific-part, everything between the
* scheme separator (':') and the fragment separator ('#'), which will
* get encoded
* @param fragment fragment, everything after the '#', null if undefined,
* will get encoded
*
* @throws NullPointerException if scheme or ssp is null
* @return Uri composed of the given scheme, ssp, and fragment
*
* @see Builder if you don't want the ssp and fragment to be encoded
*/
public static Uri fromParts(String scheme, String ssp,
String fragment) {
if (scheme == null) {
throw new NullPointerException("scheme");
}
if (ssp == null) {
throw new NullPointerException("ssp");
}
return new OpaqueUri(scheme, Part.fromDecoded(ssp),
Part.fromDecoded(fragment));
}
/**
* Opaque URI.
*/
private static class OpaqueUri extends Uri {
/** Used in parcelling. */
static final int TYPE_ID = 2;
private final String scheme;
private final Part ssp;
private final Part fragment;
private OpaqueUri(String scheme, Part ssp, Part fragment) {
this.scheme = scheme;
this.ssp = ssp;
this.fragment = fragment == null ? Part.NULL : fragment;
}
public boolean isHierarchical() {
return false;
}
public boolean isRelative() {
return scheme == null;
}
public String getScheme() {
return this.scheme;
}
public String getEncodedSchemeSpecificPart() {
return ssp.getEncoded();
}
public String getSchemeSpecificPart() {
return ssp.getDecoded();
}
public String getAuthority() {
return null;
}
public String getEncodedAuthority() {
return null;
}
public String getPath() {
return null;
}
public String getEncodedPath() {
return null;
}
public String getQuery() {
return null;
}
public String getEncodedQuery() {
return null;
}
public String getFragment() {
return fragment.getDecoded();
}
public String getEncodedFragment() {
return fragment.getEncoded();
}
public String[] getPathSegments() {
return new String[0];
}
public String getLastPathSegment() {
return null;
}
public String getUserInfo() {
return null;
}
public String getEncodedUserInfo() {
return null;
}
public String getHost() {
return null;
}
public int getPort() {
return -1;
}
private volatile String cachedString = NOT_CACHED;
public String toString() {
boolean cached = cachedString != NOT_CACHED;
if (cached) {
return cachedString;
}
StringBuffer sb = new StringBuffer();
sb.append(scheme).append(':');
sb.append(getEncodedSchemeSpecificPart());
if (!fragment.isEmpty()) {
sb.append('#').append(fragment.getEncoded());
}
return cachedString = sb.toString();
}
public Builder buildUpon() {
return new Builder()
.scheme(this.scheme)
.opaquePart(this.ssp)
.fragment(this.fragment);
}
}
/**
* Wrapper for path segment array.
*/
static class PathSegments {
static final PathSegments EMPTY = new PathSegments(null, 0);
final String[] segments;
final int size;
PathSegments(String[] segments, int size) {
this.segments = segments;
this.size = size;
}
public String get(int index) {
if (index >= size) {
throw new IndexOutOfBoundsException();
}
return segments[index];
}
public int size() {
return this.size;
}
}
/**
* Builds PathSegments.
*/
static class PathSegmentsBuilder {
String[] segments;
int size = 0;
void add(String segment) {
if (segments == null) {
segments = new String[4];
} else if (size + 1 == segments.length) {
String[] expanded = new String[segments.length * 2];
System.arraycopy(segments, 0, expanded, 0, segments.length);
segments = expanded;
}
segments[size++] = segment;
}
PathSegments build() {
if (segments == null) {
return PathSegments.EMPTY;
}
try {
return new PathSegments(segments, size);
} finally {
// Makes sure this doesn't get reused.
segments = null;
}
}
}
/**
* Support for hierarchical URIs.
*/
private abstract static class AbstractHierarchicalUri extends Uri {
public String getLastPathSegment() {
// TODO: If we haven't parsed all of the segments already, just
// grab the last one directly so we only allocate one string.
String[] segments = getPathSegments();
int size = segments.length;
if (size == 0) {
return null;
}
return segments[size - 1];
}
private Part userInfo;
private Part getUserInfoPart() {
return userInfo == null
? userInfo = Part.fromEncoded(parseUserInfo()) : userInfo;
}
public final String getEncodedUserInfo() {
return getUserInfoPart().getEncoded();
}
private String parseUserInfo() {
String authority = getEncodedAuthority();
if (authority == null) {
return null;
}
int end = authority.indexOf('@');
return end == NOT_FOUND ? null : authority.substring(0, end);
}
public String getUserInfo() {
return getUserInfoPart().getDecoded();
}
private volatile String host = NOT_CACHED;
public String getHost() {
boolean cached = (host != NOT_CACHED);
return cached ? host
: (host = parseHost());
}
private String parseHost() {
String authority = getEncodedAuthority();
if (authority == null) {
return null;
}
// Parse out user info and then port.
int userInfoSeparator = authority.indexOf('@');
int portSeparator = authority.indexOf(':', userInfoSeparator);
String encodedHost = portSeparator == NOT_FOUND
? authority.substring(userInfoSeparator + 1)
: authority.substring(userInfoSeparator + 1, portSeparator);
return decode(encodedHost);
}
private volatile int port = NOT_CALCULATED;
public int getPort() {
return port == NOT_CALCULATED
? port = parsePort()
: port;
}
private int parsePort() {
String authority = getEncodedAuthority();
if (authority == null) {
return -1;
}
// Make sure we look for the port separtor *after* the user info
// separator. We have URLs with a ':' in the user info.
int userInfoSeparator = authority.indexOf('@');
int portSeparator = authority.indexOf(':', userInfoSeparator);
if (portSeparator == NOT_FOUND) {
return -1;
}
String portString = decode(authority.substring(portSeparator + 1));
try {
return Integer.parseInt(portString);
} catch (NumberFormatException e) {
return -1;
}
}
}
/**
* Hierarchical Uri.
*/
private static class HierarchicalUri extends AbstractHierarchicalUri {
/** Used in parcelling. */
static final int TYPE_ID = 3;
private final String scheme; // can be null
private final Part authority;
private final PathPart path;
private final Part query;
private final Part fragment;
private HierarchicalUri(String scheme, Part authority, PathPart path,
Part query, Part fragment) {
this.scheme = scheme;
this.authority = Part.nonNull(authority);
this.path = path == null ? PathPart.NULL : path;
this.query = Part.nonNull(query);
this.fragment = Part.nonNull(fragment);
}
public boolean isHierarchical() {
return true;
}
public boolean isRelative() {
return scheme == null;
}
public String getScheme() {
return scheme;
}
private Part ssp;
private Part getSsp() {
return ssp == null
? ssp = Part.fromEncoded(makeSchemeSpecificPart()) : ssp;
}
public String getEncodedSchemeSpecificPart() {
return getSsp().getEncoded();
}
public String getSchemeSpecificPart() {
return getSsp().getDecoded();
}
/**
* Creates the encoded scheme-specific part from its sub parts.
*/
private String makeSchemeSpecificPart() {
StringBuffer builder = new StringBuffer();
appendSspTo(builder);
return builder.toString();
}
private void appendSspTo(StringBuffer builder) {
String encodedAuthority = authority.getEncoded();
if (encodedAuthority != null) {
// Even if the authority is "", we still want to append "//".
builder.append("//").append(encodedAuthority);
}
String encodedPath = path.getEncoded();
if (encodedPath != null) {
builder.append(encodedPath);
}
if (!query.isEmpty()) {
builder.append('?').append(query.getEncoded());
}
}
public String getAuthority() {
return this.authority.getDecoded();
}
public String getEncodedAuthority() {
return this.authority.getEncoded();
}
public String getEncodedPath() {
return this.path.getEncoded();
}
public String getPath() {
return this.path.getDecoded();
}
public String getQuery() {
return this.query.getDecoded();
}
public String getEncodedQuery() {
return this.query.getEncoded();
}
public String getFragment() {
return this.fragment.getDecoded();
}
public String getEncodedFragment() {
return this.fragment.getEncoded();
}
public String[] getPathSegments() {
return this.path.getPathSegments().segments;
}
private volatile String uriString = NOT_CACHED;
/**
* {@inheritDoc}
*/
public String toString() {
boolean cached = (uriString != NOT_CACHED);
return cached ? uriString
: (uriString = makeUriString());
}
private String makeUriString() {
StringBuffer builder = new StringBuffer();
if (scheme != null) {
builder.append(scheme).append(':');
}
appendSspTo(builder);
if (!fragment.isEmpty()) {
builder.append('#').append(fragment.getEncoded());
}
return builder.toString();
}
public Builder buildUpon() {
return new Builder()
.scheme(scheme)
.authority(authority)
.path(path)
.query(query)
.fragment(fragment);
}
}
/**
* Helper class for building or manipulating URI references. Not safe for
* concurrent use.
*
* <p>An absolute hierarchical URI reference follows the pattern:
* {@code <scheme>://<authority><absolute path>?<query>#<fragment>}
*
* <p>Relative URI references (which are always hierarchical) follow one
* of two patterns: {@code <relative or absolute path>?<query>#<fragment>}
* or {@code //<authority><absolute path>?<query>#<fragment>}
*
* <p>An opaque URI follows this pattern:
* {@code <scheme>:<opaque part>#<fragment>}
*/
public static final class Builder {
private String scheme;
private Part opaquePart;
private Part authority;
private PathPart path;
private Part query;
private Part fragment;
/**
* Constructs a new Builder.
*/
public Builder() {}
/**
* Sets the scheme.
*
* @param scheme name or {@code null} if this is a relative Uri
*/
public Builder scheme(String scheme) {
this.scheme = scheme;
return this;
}
Builder opaquePart(Part opaquePart) {
this.opaquePart = opaquePart;
return this;
}
/**
* Encodes and sets the given opaque scheme-specific-part.
*
* @param opaquePart decoded opaque part
*/
public Builder opaquePart(String opaquePart) {
return opaquePart(Part.fromDecoded(opaquePart));
}
/**
* Sets the previously encoded opaque scheme-specific-part.
*
* @param opaquePart encoded opaque part
*/
public Builder encodedOpaquePart(String opaquePart) {
return opaquePart(Part.fromEncoded(opaquePart));
}
Builder authority(Part authority) {
// This URI will be hierarchical.
this.opaquePart = null;
this.authority = authority;
return this;
}
/**
* Encodes and sets the authority.
*/
public Builder authority(String authority) {
return authority(Part.fromDecoded(authority));
}
/**
* Sets the previously encoded authority.
*/
public Builder encodedAuthority(String authority) {
return authority(Part.fromEncoded(authority));
}
Builder path(PathPart path) {
// This URI will be hierarchical.
this.opaquePart = null;
this.path = path;
return this;
}
/**
* Sets the path. Leaves '/' characters intact but encodes others as
* necessary.
*
* <p>If the path is not null and doesn't start with a '/', and if
* you specify a scheme and/or authority, the builder will prepend the
* given path with a '/'.
*/
public Builder path(String path) {
return path(PathPart.fromDecoded(path));
}
/**
* Sets the previously encoded path.
*
* <p>If the path is not null and doesn't start with a '/', and if
* you specify a scheme and/or authority, the builder will prepend the
* given path with a '/'.
*/
public Builder encodedPath(String path) {
return path(PathPart.fromEncoded(path));
}
/**
* Encodes the given segment and appends it to the path.
*/
public Builder appendPath(String newSegment) {
return path(PathPart.appendDecodedSegment(path, newSegment));
}
/**
* Appends the given segment to the path.
*/
public Builder appendEncodedPath(String newSegment) {
return path(PathPart.appendEncodedSegment(path, newSegment));
}
Builder query(Part query) {
// This URI will be hierarchical.
this.opaquePart = null;
this.query = query;
return this;
}
/**
* Encodes and sets the query.
*/
public Builder query(String query) {
return query(Part.fromDecoded(query));
}
/**
* Sets the previously encoded query.
*/
public Builder encodedQuery(String query) {
return query(Part.fromEncoded(query));
}
Builder fragment(Part fragment) {
this.fragment = fragment;
return this;
}
/**
* Encodes and sets the fragment.
*/
public Builder fragment(String fragment) {
return fragment(Part.fromDecoded(fragment));
}
/**
* Sets the previously encoded fragment.
*/
public Builder encodedFragment(String fragment) {
return fragment(Part.fromEncoded(fragment));
}
/**
* Encodes the key and value and then appends the parameter to the
* query string.
*
* @param key which will be encoded
* @param value which will be encoded
*/
public Builder appendQueryParameter(String key, String value) {
// This URI will be hierarchical.
this.opaquePart = null;
String encodedParameter = encode(key, null) + "="
+ encode(value, null);
if (query == null) {
query = Part.fromEncoded(encodedParameter);
return this;
}
String oldQuery = query.getEncoded();
if (oldQuery == null || oldQuery.length() == 0) {
query = Part.fromEncoded(encodedParameter);
} else {
query = Part.fromEncoded(oldQuery + "&" + encodedParameter);
}
return this;
}
/**
* Constructs a Uri with the current attributes.
*
* @throws UnsupportedOperationException if the URI is opaque and the
* scheme is null
*/
public Uri build() {
if (opaquePart != null) {
if (this.scheme == null) {
throw new UnsupportedOperationException(
"An opaque URI must have a scheme.");
}
return new OpaqueUri(scheme, opaquePart, fragment);
} else {
// Hierarchical URIs should not return null for getPath().
PathPart path = this.path;
if (path == null || path == PathPart.NULL) {
path = PathPart.EMPTY;
} else {
// If we have a scheme and/or authority, the path must
// be absolute. Prepend it with a '/' if necessary.
if (hasSchemeOrAuthority()) {
path = PathPart.makeAbsolute(path);
}
}
return new HierarchicalUri(
scheme, authority, path, query, fragment);
}
}
private boolean hasSchemeOrAuthority() {
return scheme != null
|| (authority != null && authority != Part.NULL);
}
/**
* {@inheritDoc}
*/
public String toString() {
return build().toString();
}
}
/**
* Searches the query string for parameter values with the given key.
*
* @param key which will be encoded
*
* @throws UnsupportedOperationException if this isn't a hierarchical URI
* @throws NullPointerException if key is null
*
* @return a list of decoded values
*/
public String[] getQueryParameters(String key) {
if (isOpaque()) {
throw new UnsupportedOperationException(NOT_HIERARCHICAL);
}
String query = getEncodedQuery();
if (query == null) {
return new String[0];
}
String encodedKey;
try {
encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
}
// Prepend query with "&" making the first parameter the same as the
// rest.
query = "&" + query;
// Parameter prefix.
String prefix = "&" + encodedKey + "=";
Vector values = new Vector();
int start = 0;
int length = query.length();
while (start < length) {
start = query.indexOf(prefix, start);
if (start == -1) {
// No more values.
break;
}
// Move start to start of value.
start += prefix.length();
// Find end of value.
int end = query.indexOf('&', start);
if (end == -1) {
end = query.length();
}
String value = query.substring(start, end);
values.addElement(decode(value));
start = end;
}
int size = values.size();
String[] result = new String[size];
values.copyInto(result);
return result;
}
/**
* Searches the query string for the first value with the given key.
*
* @param key which will be encoded
* @throws UnsupportedOperationException if this isn't a hierarchical URI
* @throws NullPointerException if key is null
*
* @return the decoded value or null if no parameter is found
*/
public String getQueryParameter(String key) {
if (isOpaque()) {
throw new UnsupportedOperationException(NOT_HIERARCHICAL);
}
String query = getEncodedQuery();
if (query == null) {
return null;
}
String encodedKey;
try {
encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
}
String prefix = encodedKey + "=";
if (query.length() < prefix.length()) {
return null;
}
int start;
if (query.startsWith(prefix)) {
// It's the first parameter.
start = prefix.length();
} else {
// It must be later in the query string.
prefix = "&" + prefix;
start = query.indexOf(prefix);
if (start == -1) {
// Not found.
return null;
}
start += prefix.length();
}
// Find end of value.
int end = query.indexOf('&', start);
if (end == -1) {
end = query.length();
}
String value = query.substring(start, end);
return decode(value);
}
private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
/**
* Encodes characters in the given string as '%'-escaped octets
* using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers
* ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes
* all other characters.
*
* @param s string to encode
* @return an encoded version of s suitable for use as a URI component,
* or null if s is null
*/
public static String encode(String s) {
return encode(s, null);
}
/**
* Encodes characters in the given string as '%'-escaped octets
* using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers
* ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes
* all other characters with the exception of those specified in the
* allow argument.
*
* @param s string to encode
* @param allow set of additional characters to allow in the encoded form,
* null if no characters should be skipped
* @return an encoded version of s suitable for use as a URI component,
* or null if s is null
*/
public static String encode(String s, String allow) {
if (s == null) {
return null;
}
// Lazily-initialized buffers.
StringBuffer encoded = null;
int oldLength = s.length();
// This loop alternates between copying over allowed characters and
// encoding in chunks. This results in fewer method calls and
// allocations than encoding one character at a time.
int current = 0;
while (current < oldLength) {
// Start in "copying" mode where we copy over allowed chars.
// Find the next character which needs to be encoded.
int nextToEncode = current;
while (nextToEncode < oldLength
&& isAllowed(s.charAt(nextToEncode), allow)) {
nextToEncode++;
}
// If there's nothing more to encode...
if (nextToEncode == oldLength) {
if (current == 0) {
// We didn't need to encode anything!
return s;
} else {
// Presumably, we've already done some encoding.
encoded.append(s.substring(current, oldLength));
return encoded.toString();
}
}
if (encoded == null) {
encoded = new StringBuffer();
}
if (nextToEncode > current) {
// Append allowed characters leading up to this point.
encoded.append(s.substring(current, nextToEncode));
} else {
// assert nextToEncode == current
}
// Switch to "encoding" mode.
// Find the next allowed character.
current = nextToEncode;
int nextAllowed = current + 1;
while (nextAllowed < oldLength
&& !isAllowed(s.charAt(nextAllowed), allow)) {
nextAllowed++;
}
// Convert the substring to bytes and encode the bytes as
// '%'-escaped octets.
String toEncode = s.substring(current, nextAllowed);
try {
byte[] bytes = toEncode.getBytes(DEFAULT_ENCODING);
int bytesLength = bytes.length;
for (int i = 0; i < bytesLength; i++) {
encoded.append('%');
encoded.append(HEX_DIGITS[(bytes[i] & 0xf0) >> 4]);
encoded.append(HEX_DIGITS[bytes[i] & 0xf]);
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
}
current = nextAllowed;
}
// Encoded could still be null at this point if s is empty.
return encoded == null ? s : encoded.toString();
}
/**
* Returns true if the given character is allowed.
*
* @param c character to check
* @param allow characters to allow
* @return true if the character is allowed or false if it should be
* encoded
*/
private static boolean isAllowed(char c, String allow) {
return (c >= 'A' && c <= 'Z')
|| (c >= 'a' && c <= 'z')
|| (c >= '0' && c <= '9')
|| "_-!.~'()*".indexOf(c) != NOT_FOUND
|| (allow != null && allow.indexOf(c) != NOT_FOUND);
}
/** Unicode replacement character: \\uFFFD. */
private static final byte[] REPLACEMENT = { (byte) 0xFF, (byte) 0xFD };
/**
* Decodes '%'-escaped octets in the given string using the UTF-8 scheme.
* Replaces invalid octets with the unicode replacement character
* ("\\uFFFD").
*
* @param s encoded string to decode
* @return the given string with escaped octets decoded, or null if
* s is null
*/
public static String decode(String s) {
/*
Compared to java.net.URLEncoderDecoder.decode(), this method decodes a
chunk at a time instead of one character at a time, and it doesn't
throw exceptions. It also only allocates memory when necessary--if
there's nothing to decode, this method won't do much.
*/
if (s == null) {
return null;
}
// Lazily-initialized buffers.
StringBuffer decoded = null;
ByteArrayOutputStream out = null;
int oldLength = s.length();
// This loop alternates between copying over normal characters and
// escaping in chunks. This results in fewer method calls and
// allocations than decoding one character at a time.
int current = 0;
while (current < oldLength) {
// Start in "copying" mode where we copy over normal characters.
// Find the next escape sequence.
int nextEscape = s.indexOf('%', current);
if (nextEscape == NOT_FOUND) {
if (decoded == null) {
// We didn't actually decode anything.
return s;
} else {
// Append the remainder and return the decoded string.
decoded.append(s.substring(current, oldLength));
return decoded.toString();
}
}
// Prepare buffers.
if (decoded == null) {
// Looks like we're going to need the buffers...
// We know the new string will be shorter. Using the old length
// may overshoot a bit, but it will save us from resizing the
// buffer.
decoded = new StringBuffer(oldLength);
out = new ByteArrayOutputStream(4);
} else {
// Clear decoding buffer.
out.reset();
}
// Append characters leading up to the escape.
if (nextEscape > current) {
decoded.append(s.substring(current, nextEscape));
current = nextEscape;
} else {
// assert current == nextEscape
}
// Switch to "decoding" mode where we decode a string of escape
// sequences.
// Decode and append escape sequences. Escape sequences look like
// "%ab" where % is literal and a and b are hex digits.
try {
do {
if (current + 2 >= oldLength) {
// Truncated escape sequence.
out.write(REPLACEMENT);
} else {
int a = Character.digit(s.charAt(current + 1), 16);
int b = Character.digit(s.charAt(current + 2), 16);
if (a == -1 || b == -1) {
// Non hex digits.
out.write(REPLACEMENT);
} else {
// Combine the hex digits into one byte and write.
out.write((a << 4) + b);
}
}
// Move passed the escape sequence.
current += 3;
} while (current < oldLength && s.charAt(current) == '%');
// Decode UTF-8 bytes into a string and append it.
decoded.append(new String(out.toByteArray(), DEFAULT_ENCODING));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
} catch (IOException e) {
throw new RuntimeException("AssertionError: " + e);
}
}
// If we don't have a buffer, we didn't have to decode anything.
return decoded == null ? s : decoded.toString();
}
/**
* Support for part implementations.
*/
static abstract class AbstractPart {
/**
* Enum which indicates which representation of a given part we have.
*/
static class Representation {
static final int BOTH = 0;
static final int ENCODED = 1;
static final int DECODED = 2;
}
volatile String encoded;
volatile String decoded;
AbstractPart(String encoded, String decoded) {
this.encoded = encoded;
this.decoded = decoded;
}
abstract String getEncoded();
final String getDecoded() {
boolean hasDecoded = decoded != NOT_CACHED;
return hasDecoded ? decoded : (decoded = decode(encoded));
}
}
/**
* Immutable wrapper of encoded and decoded versions of a URI part. Lazily
* creates the encoded or decoded version from the other.
*/
static class Part extends AbstractPart {
/** A part with null values. */
static final Part NULL = new EmptyPart(null);
/** A part with empty strings for values. */
static final Part EMPTY = new EmptyPart("");
private Part(String encoded, String decoded) {
super(encoded, decoded);
}
boolean isEmpty() {
return false;
}
String getEncoded() {
boolean hasEncoded = encoded != NOT_CACHED;
return hasEncoded ? encoded : (encoded = encode(decoded));
}
/**
* Returns given part or {@link #NULL} if the given part is null.
*/
static Part nonNull(Part part) {
return part == null ? NULL : part;
}
/**
* Creates a part from the encoded string.
*
* @param encoded part string
*/
static Part fromEncoded(String encoded) {
return from(encoded, NOT_CACHED);
}
/**
* Creates a part from the decoded string.
*
* @param decoded part string
*/
static Part fromDecoded(String decoded) {
return from(NOT_CACHED, decoded);
}
/**
* Creates a part from the encoded and decoded strings.
*
* @param encoded part string
* @param decoded part string
*/
static Part from(String encoded, String decoded) {
// We have to check both encoded and decoded in case one is
// NOT_CACHED.
if (encoded == null) {
return NULL;
}
if (encoded.length() == 0) {
return EMPTY;
}
if (decoded == null) {
return NULL;
}
if (decoded .length() == 0) {
return EMPTY;
}
return new Part(encoded, decoded);
}
private static class EmptyPart extends Part {
public EmptyPart(String value) {
super(value, value);
}
/**
* {@inheritDoc}
*/
boolean isEmpty() {
return true;
}
}
}
/**
* Immutable wrapper of encoded and decoded versions of a path part. Lazily
* creates the encoded or decoded version from the other.
*/
static class PathPart extends AbstractPart {
/** A part with null values. */
static final PathPart NULL = new PathPart(null, null);
/** A part with empty strings for values. */
static final PathPart EMPTY = new PathPart("", "");
private PathPart(String encoded, String decoded) {
super(encoded, decoded);
}
String getEncoded() {
boolean hasEncoded = encoded != NOT_CACHED;
// Don't encode '/'.
return hasEncoded ? encoded : (encoded = encode(decoded, "/"));
}
/**
* Cached path segments. This doesn't need to be volatile--we don't
* care if other threads see the result.
*/
private PathSegments pathSegments;
/**
* Gets the individual path segments. Parses them if necessary.
*
* @return parsed path segments or null if this isn't a hierarchical
* URI
*/
PathSegments getPathSegments() {
if (pathSegments != null) {
return pathSegments;
}
String path = getEncoded();
if (path == null) {
return pathSegments = PathSegments.EMPTY;
}
PathSegmentsBuilder segmentBuilder = new PathSegmentsBuilder();
int previous = 0;
int current;
while ((current = path.indexOf('/', previous)) > -1) {
// This check keeps us from adding a segment if the path starts
// '/' and an empty segment for "//".
if (previous < current) {
String decodedSegment
= decode(path.substring(previous, current));
segmentBuilder.add(decodedSegment);
}
previous = current + 1;
}
// Add in the final path segment.
if (previous < path.length()) {
segmentBuilder.add(decode(path.substring(previous)));
}
return pathSegments = segmentBuilder.build();
}
static PathPart appendEncodedSegment(PathPart oldPart,
String newSegment) {
// If there is no old path, should we make the new path relative
// or absolute? I pick absolute.
if (oldPart == null) {
// No old path.
return fromEncoded("/" + newSegment);
}
String oldPath = oldPart.getEncoded();
if (oldPath == null) {
oldPath = "";
}
int oldPathLength = oldPath.length();
String newPath;
if (oldPathLength == 0) {
// No old path.
newPath = "/" + newSegment;
} else if (oldPath.charAt(oldPathLength - 1) == '/') {
newPath = oldPath + newSegment;
} else {
newPath = oldPath + "/" + newSegment;
}
return fromEncoded(newPath);
}
static PathPart appendDecodedSegment(PathPart oldPart, String decoded) {
String encoded = encode(decoded);
// TODO: Should we reuse old PathSegments? Probably not.
return appendEncodedSegment(oldPart, encoded);
}
/**
* Creates a path from the encoded string.
*
* @param encoded part string
*/
static PathPart fromEncoded(String encoded) {
return from(encoded, NOT_CACHED);
}
/**
* Creates a path from the decoded string.
*
* @param decoded part string
*/
static PathPart fromDecoded(String decoded) {
return from(NOT_CACHED, decoded);
}
/**
* Creates a path from the encoded and decoded strings.
*
* @param encoded part string
* @param decoded part string
*/
static PathPart from(String encoded, String decoded) {
if (encoded == null) {
return NULL;
}
if (encoded.length() == 0) {
return EMPTY;
}
return new PathPart(encoded, decoded);
}
/**
* Prepends path values with "/" if they're present, not empty, and
* they don't already start with "/".
*/
static PathPart makeAbsolute(PathPart oldPart) {
boolean encodedCached = oldPart.encoded != NOT_CACHED;
// We don't care which version we use, and we don't want to force
// unneccessary encoding/decoding.
String oldPath = encodedCached ? oldPart.encoded : oldPart.decoded;
if (oldPath == null || oldPath.length() == 0
|| oldPath.startsWith("/")) {
return oldPart;
}
// Prepend encoded string if present.
String newEncoded = encodedCached
? "/" + oldPart.encoded : NOT_CACHED;
// Prepend decoded string if present.
boolean decodedCached = oldPart.decoded != NOT_CACHED;
String newDecoded = decodedCached
? "/" + oldPart.decoded
: NOT_CACHED;
return new PathPart(newEncoded, newDecoded);
}
}
/**
* Creates a new Uri by appending an already-encoded path segment to a
* base Uri.
*
* @param baseUri Uri to append path segment to
* @param pathSegment encoded path segment to append
* @return a new Uri based on baseUri with the given segment appended to
* the path
* @throws NullPointerException if baseUri is null
*/
public static Uri withAppendedPath(Uri baseUri, String pathSegment) {
Builder builder = baseUri.buildUpon();
builder = builder.appendEncodedPath(pathSegment);
return builder.build();
}
}
| Java |
/*-
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.authenticator.blackberry;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import com.google.authenticator.blackberry.AccountDb.OtpType;
import com.google.authenticator.blackberry.resource.AuthenticatorResource;
/**
* BlackBerry port of {@code EnterKeyActivity}.
*/
public class EnterKeyScreen extends MainScreen implements AuthenticatorResource,
FieldChangeListener {
private static ResourceBundle sResources = ResourceBundle.getBundle(
BUNDLE_ID, BUNDLE_NAME);
private static final int MIN_KEY_BYTES = 10;
private static final boolean INTEGRITY_CHECK_ENABLED = false;
private LabelField mDescriptionText;
private LabelField mStatusText;
private LabelField mVersionText;
private EditField mAccountName;
private EditField mKeyEntryField;
private ObjectChoiceField mType;
private ButtonField mClearButton;
private ButtonField mSubmitButton;
private ButtonField mCancelButton;
private int mStatusColor;
public EnterKeyScreen() {
setTitle(sResources.getString(ENTER_KEY_TITLE));
VerticalFieldManager manager = new VerticalFieldManager();
mDescriptionText = new LabelField(sResources.getString(ENTER_KEY_HELP));
mAccountName = new EditField(EditField.NO_NEWLINE);
mAccountName.setLabel(sResources.getString(ENTER_ACCOUNT_LABEL));
mKeyEntryField = new EditField(EditField.NO_NEWLINE);
mKeyEntryField.setLabel(sResources.getString(ENTER_KEY_LABEL));
mType = new ObjectChoiceField(sResources.getString(TYPE_PROMPT), OtpType
.values());
mStatusText = new LabelField() {
protected void paint(Graphics graphics) {
int savedColor = graphics.getColor();
graphics.setColor(mStatusColor);
super.paint(graphics);
graphics.setColor(savedColor);
}
};
mKeyEntryField.setChangeListener(this);
manager.add(mDescriptionText);
manager.add(new LabelField()); // Spacer
manager.add(mAccountName);
manager.add(mKeyEntryField);
manager.add(mStatusText);
manager.add(mType);
HorizontalFieldManager buttons = new HorizontalFieldManager(FIELD_HCENTER);
mSubmitButton = new ButtonField(sResources.getString(SUBMIT),
ButtonField.CONSUME_CLICK);
mClearButton = new ButtonField(sResources.getString(CLEAR),
ButtonField.CONSUME_CLICK);
mCancelButton = new ButtonField(sResources.getString(CANCEL),
ButtonField.CONSUME_CLICK);
mSubmitButton.setChangeListener(this);
mClearButton.setChangeListener(this);
mCancelButton.setChangeListener(this);
buttons.add(mSubmitButton);
buttons.add(mClearButton);
buttons.add(mCancelButton);
ApplicationDescriptor applicationDescriptor = ApplicationDescriptor
.currentApplicationDescriptor();
String version = applicationDescriptor.getVersion();
mVersionText = new LabelField(version, FIELD_RIGHT | FIELD_BOTTOM);
add(manager);
add(buttons);
add(mVersionText);
}
/*
* Either return a check code or an error message
*/
private boolean validateKeyAndUpdateStatus(boolean submitting) {
String userEnteredKey = mKeyEntryField.getText();
try {
byte[] decoded = Base32String.decode(userEnteredKey);
if (decoded.length < MIN_KEY_BYTES) {
// If the user is trying to submit a key that's too short, then
// display a message saying it's too short.
mStatusText.setText(submitting ? sResources.getString(ENTER_KEY_VALUE_TOO_SHORT) : "");
mStatusColor = Color.BLACK;
return false;
} else {
if (INTEGRITY_CHECK_ENABLED) {
String checkCode = CheckCodeScreen.getCheckCode(mKeyEntryField.getText());
mStatusText.setText(sResources.getString(ENTER_KEY_INTEGRITY_CHECK_VALUE) + checkCode);
mStatusColor = Color.GREEN;
} else {
mStatusText.setText("");
}
return true;
}
} catch (Base32String.DecodingException e) {
mStatusText.setText(sResources.getString(ENTER_KEY_INVALID_FORMAT));
mStatusColor = Color.RED;
return false;
} catch (RuntimeException e) {
mStatusText.setText(sResources.getString(ENTER_KEY_UNEXPECTED_PROBLEM));
mStatusColor = Color.RED;
return false;
}
}
/**
* {@inheritDoc}
*/
public void fieldChanged(Field field, int context) {
if (field == mSubmitButton) {
if (validateKeyAndUpdateStatus(true)) {
AuthenticatorScreen.saveSecret(mAccountName.getText(), mKeyEntryField
.getText(), null, (OtpType) mType.getChoice(mType
.getSelectedIndex()));
close();
}
} else if (field == mClearButton) {
mStatusText.setText("");
mAccountName.setText("");
mKeyEntryField.setText("");
} else if (field == mCancelButton) {
close();
} else if (field == mKeyEntryField) {
validateKeyAndUpdateStatus(false);
}
}
/**
* {@inheritDoc}
*/
protected boolean onSavePrompt() {
// Disable prompt when the user hits the back button
return false;
}
}
| Java |
package transactions;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import transactions.BookReview;
@Entity(name = "Book")
public class Book {
@Id
private String isbn;
private String title;
private String author;
private int copyrightYear;
private Date authorBirthdate;
private List<BookReview> bookReviews = null;
public Book(String isbn) {
this.isbn = isbn;
}
public String getIsbn() {
return isbn;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthor() {
return author;
}
public void setCopyrightYear(int copyrightYear) {
this.copyrightYear = copyrightYear;
}
public int getCopyrightYear() {
return copyrightYear;
}
public void setAuthorBirthdate(Date authorBirthdate) {
this.authorBirthdate = authorBirthdate;
}
public Date getAuthorBirthdate() {
return authorBirthdate;
}
public void setBookReviews(List<BookReview> bookReviews) {
this.bookReviews = bookReviews;
}
public List<BookReview> getBookReviews() {
if (bookReviews == null) {
bookReviews = new ArrayList<BookReview>();
}
return bookReviews;
}
}
| Java |
package transactions;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public final class EMF {
private static final EntityManagerFactory emfInstance =
Persistence.createEntityManagerFactory("transactions-optional");
private EMF() {}
public static EntityManagerFactory get() {
return emfInstance;
}
}
| Java |
package transactions;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.SimpleTimeZone;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.servlet.http.*;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.KeyFactory.Builder;
import transactions.Book;
import transactions.BookReview;
import transactions.EMF;
@SuppressWarnings("serial")
public class JPATransactionsServlet extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
EntityManagerFactory emf = EMF.get();
EntityManager em = null;
try {
em = emf.createEntityManager();
Book book = new Book("978-0596522728");
book.setTitle("Programming Google App Engine");
book.setAuthor("Dan Sanderson");
book.setCopyrightYear(2010);
Date authorBirthdate =
new GregorianCalendar(1978, Calendar.JANUARY, 11).getTime();
book.setAuthorBirthdate(authorBirthdate);
em.persist(book);
} finally {
em.close();
}
try {
em = emf.createEntityManager();
EntityTransaction txn = em.getTransaction();
txn.begin();
try {
Book book = em.find(Book.class, "978-0596522728");
BookReview bookReview = new BookReview();
bookReview.setRating(5);
book.getBookReviews().add(bookReview);
// No need to explicitly persist() the BookReview
// because it is a field of Book.
// Persist all updates and commit.
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
} finally {
em.close();
}
try {
em = emf.createEntityManager();
Book book = em.find(Book.class, "978-0596522728");
if (book != null) {
out.println("<p>Ratings for <i>" + book.getTitle() + "</i>: ");
for (BookReview review : book.getBookReviews()) {
out.println("[" + review.getRating() + "]");
}
out.println("</ul>");
} else {
out.println("Could not find that book I was looking for...");
}
} finally {
em.close();
}
out.println("<p>Objects saved. See <a href=\"/_ah/admin\">the datastore viewer</a>.</p>");
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS");
fmt.setTimeZone(new SimpleTimeZone(0, ""));
out.println("<p>The time is: " + fmt.format(new Date()) + "</p>");
}
}
| Java |
package ids;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public final class EMF {
private static final EntityManagerFactory emfInstance =
Persistence.createEntityManagerFactory("transactions-optional");
private EMF() {}
public static EntityManagerFactory get() {
return emfInstance;
}
}
| Java |
package ids;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity(name = "BookStringId")
public class BookStringId {
// String ID field: entities of this class use key names set by
// the app prior to saving, and do not have ancestors (entity
// group parents).
@Id
private String isbn;
private String title;
private String author;
private int copyrightYear;
private Date authorBirthdate;
public BookStringId(String isbn) {
this.isbn = isbn;
}
public String getIsbn() {
return isbn;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthor() {
return author;
}
public void setCopyrightYear(int copyrightYear) {
this.copyrightYear = copyrightYear;
}
public int getCopyrightYear() {
return copyrightYear;
}
public void setAuthorBirthdate(Date authorBirthdate) {
this.authorBirthdate = authorBirthdate;
}
public Date getAuthorBirthdate() {
return authorBirthdate;
}
}
| Java |
package ids;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Entity;
// import javax.persistence.GeneratedValue;
// import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.datanucleus.jpa.annotations.Extension;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
@Entity(name = "BookEncodedStringId")
public class BookEncodedStringId {
// Encoded String ID field: objects of this class represent the
// entity key as an encoded String, making the class portable to
// other data backends. Key values can be encoded and decoded
// using the KeyFactory.keyToString() and stringToKey() methods.
// Without a @GeneratedValue annotation, the Key value (prior to
// encoding) must contain an app-assigned key name (a String).
// With a @GeneratedValue annotation, the datastore assigns a
// numeric system ID when the object is saved. The key name or
// system ID is contained in the (encoded) Key value.
@Id
@Extension(vendorName = "datanucleus",
key = "gae.encoded-pk",
value = "true")
// @GeneratedValue(strategy = GenerationType.IDENTITY)
private String encodedKeyString;
// With string-encoded keys, an entity group parent is represented
// as a separate encoded field. Its value is the encoded key of
// the parent.
@Basic
@Extension(vendorName = "datanucleus",
key = "gae.parent-pk",
value = "true")
private String parentEncodedKeyString;
private String title;
private String author;
private int copyrightYear;
private Date authorBirthdate;
public BookEncodedStringId(Key encodedKey) {
this.encodedKeyString = KeyFactory.keyToString(encodedKey);
this.parentEncodedKeyString = null;
}
public BookEncodedStringId(String encodedKeyString) {
this.encodedKeyString = encodedKeyString;
this.parentEncodedKeyString = null;
}
public BookEncodedStringId(Key encodedKey,
Key parentEncodedKey) {
this.encodedKeyString = KeyFactory.keyToString(encodedKey);
this.parentEncodedKeyString = KeyFactory.keyToString(parentEncodedKey);
}
public BookEncodedStringId(String encodedKeyString,
String parentEncodedKeyString) {
this.encodedKeyString = encodedKeyString;
this.parentEncodedKeyString = parentEncodedKeyString;
}
public Key getEncodedKey() {
return KeyFactory.stringToKey(encodedKeyString);
}
public String getEncodedKeyString() {
return encodedKeyString;
}
public Key getParentEncodedKey() {
if (parentEncodedKeyString == null) {
return null;
} else {
return KeyFactory.stringToKey(parentEncodedKeyString);
}
}
public String getParentEncodedKeyString() {
return parentEncodedKeyString;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthor() {
return author;
}
public void setCopyrightYear(int copyrightYear) {
this.copyrightYear = copyrightYear;
}
public int getCopyrightYear() {
return copyrightYear;
}
public void setAuthorBirthdate(Date authorBirthdate) {
this.authorBirthdate = authorBirthdate;
}
public Date getAuthorBirthdate() {
return authorBirthdate;
}
}
| Java |
package ids;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.servlet.http.*;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.KeyFactory.Builder;
import ids.BookEncodedStringId;
import ids.BookKeyId;
import ids.BookNumericId;
import ids.BookStringId;
import ids.EMF;
@SuppressWarnings("serial")
public class JPAIDsServlet extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
EntityManagerFactory emf = EMF.get();
EntityManager em = null;
// TODO: It should be possible to do all of these with one
// EntityManager with NontransactionalWrite set to true in the
// persistence.xml configuration, but this doesn't appear to
// work in SDK 1.3.0.
// http://code.google.com/p/datanucleus-appengine/issues/detail?id=183
try {
em = emf.createEntityManager();
// An entity with a String key name and no ancestors.
BookStringId book1 = new BookStringId("978-0-596-52272-8");
em.persist(book1);
} finally {
em.close();
}
try {
em = emf.createEntityManager();
// An entity with a numeric system ID and no ancestors.
// System ID is not assigned until the EntityManager is
// closed in the finally block.
BookNumericId book2 = new BookNumericId();
em.persist(book2);
} finally {
em.close();
}
try {
em = emf.createEntityManager();
// An entity with a Key ID field. Can have an ancestor set
// in the Key.
Key book3key = new Builder("Publisher", "O'Reilly")
.addChild("BookKeyId", "978-0-596-52272-8")
.getKey();
BookKeyId book3 = new BookKeyId(book3key);
em.persist(book3);
} finally {
em.close();
}
try {
em = emf.createEntityManager();
// An object with its entity's key encoded as two String
// fields, one for the object's kind and (string or
// numeric) ID, and one for the parent. (The class
// constructor calls KeyFactory.keyToString() to encode
// the Key values. See BookEncodedStringId.java.)
Key book4keyParent = new Builder("Publisher", "O'Reilly").getKey();
Key book4key = new Builder("BookEncodedStringId", "978-0-596-52272-8")
.getKey();
BookEncodedStringId book4 = new BookEncodedStringId(book4key,
book4keyParent);
em.persist(book4);
} finally {
em.close();
}
out.println("<p>Objects saved. See <a href=\"/_ah/admin\">the datastore viewer</a>.</p>");
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS");
fmt.setTimeZone(new SimpleTimeZone(0, ""));
out.println("<p>The time is: " + fmt.format(new Date()) + "</p>");
}
}
| Java |
package properties;
import javax.persistence.Embeddable;
// A class that can be used as a JPA embeddable field. Fields are
// stored as individual properties of the data object that has the
// field, and can be indexed and queried.
@Embeddable
public class Publisher {
private String name;
private String mailingAddress;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setMailingAddress(String mailingAddress) {
this.mailingAddress = mailingAddress;
}
public String getMailingAddress() {
return mailingAddress;
}
}
| Java |
package properties;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Transient;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.ShortBlob;
import org.datanucleus.jpa.annotations.Extension;
import properties.Publisher;
import properties.PublisherMetadata;
@Entity(name = "Book")
public class Book {
// A Key ID with system-assigned numeric IDs.
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key id;
// These fields are automatically considered persistent (@Basic)
// because their types are described as such in the JPA
// specification.
private String title;
private String author;
private int copyrightYear;
private Date authorBirthdate;
// Datastore native types that are not in the JPA standard must
// have the @Basic annotation to be considered persistent.
@Basic
private ShortBlob coverIcon;
// Collection fields are stored as multi-valued properties. Such
// a field must have the @Basic annotation.
@Basic
private List<String> tags;
// Fields annotated as @Transient are not persisted to the
// datastore, regardless of their types.
@Transient
private int debugAccessCount;
// By default, the property name is the name of the field. You
// can specify the property name manually using @Column.
@Column(name = "long_description")
private String longDescription;
// You can declare that a field should not be indexed by the
// datastore with a DataNucleus @Extension annotation.
@Extension(vendorName = "datanucleus",
key = "gae.unindexed",
value = "true")
private String firstSentence;
// A Serializable object can be stored in a field. The value is
// serialized and stored as a datastore blob property value (not
// indexed).
@Lob
private PublisherMetadata publisherMetadata;
// JPA embedded objects are supported. See the @Embeddable
// annotation on the data class. The embedded class's fields are
// stored as individual properties of the outer object, and are
// queryable.
private Publisher publisher;
public Key getId() {
return id;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthor() {
return author;
}
public void setCopyrightYear(int copyrightYear) {
this.copyrightYear = copyrightYear;
}
public int getCopyrightYear() {
return copyrightYear;
}
public void setAuthorBirthdate(Date authorBirthdate) {
this.authorBirthdate = authorBirthdate;
}
public Date getAuthorBirthdate() {
return authorBirthdate;
}
public void setCoverIcon(ShortBlob coverIcon) {
this.coverIcon = coverIcon;
}
public ShortBlob getCoverIcon() {
return coverIcon;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public List<String> getTags() {
return tags;
}
public void setDebugAccessCount(int debugAccessCount) {
this.debugAccessCount = debugAccessCount;
}
public int getDebugAccessCount() {
return debugAccessCount;
}
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
public String getLongDescription() {
return longDescription;
}
public void setFirstSentence(String firstSentence) {
this.firstSentence = firstSentence;
}
public String getFirstSentence() {
return firstSentence;
}
public void setPublisherMetadata(PublisherMetadata publisherMetadata) {
this.publisherMetadata = publisherMetadata;
}
public PublisherMetadata getPublisherMetadata() {
return publisherMetadata;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
public Publisher getPublisher() {
return publisher;
}
}
| Java |
package properties;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public final class EMF {
private static final EntityManagerFactory emfInstance =
Persistence.createEntityManagerFactory("transactions-optional");
private EMF() {}
public static EntityManagerFactory get() {
return emfInstance;
}
}
| Java |
package properties;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.SimpleTimeZone;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.servlet.http.*;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.KeyFactory.Builder;
import com.google.appengine.api.datastore.ShortBlob;
import properties.Book;
import properties.EMF;
@SuppressWarnings("serial")
public class JPAPropsServlet extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
EntityManagerFactory emf = EMF.get();
EntityManager em = null;
try {
em = emf.createEntityManager();
Book book = new Book();
book.setTitle("The Grapes of Wrath");
book.setAuthor("John Steinbeck");
book.setCopyrightYear(1939);
Date authorBirthdate =
new GregorianCalendar(1902, Calendar.FEBRUARY, 27).getTime();
book.setAuthorBirthdate(authorBirthdate);
ShortBlob coverIcon = new ShortBlob(new byte[] { 1, 2, 126, 127 });
book.setCoverIcon(coverIcon);
// stored as a multi-valued property
book.setTags(Arrays.asList("depression", "grapes", "wrath"));
// not stored (@Transient)
book.setDebugAccessCount(9999);
// stored as long_description
book.setLongDescription("...");
// stored but not indexed
book.setFirstSentence("...");
// Serializable field type stored as a datastore blob property,
// not indexed
PublisherMetadata publisherMetadata = new PublisherMetadata();
publisherMetadata.setItemCode("X1841GH9");
Date productionStartDate =
new GregorianCalendar(2002, Calendar.APRIL, 28).getTime();
publisherMetadata.setProductionStartDate(productionStartDate);
Date productionEndDate =
new GregorianCalendar(2002, Calendar.JULY, 7).getTime();
publisherMetadata.setProductionEndDate(productionEndDate);
book.setPublisherMetadata(publisherMetadata);
// JPA embedded object, stored as multiple properties on the
// Book entity.
Publisher publisher = new Publisher();
publisher.setName("GM Classics");
publisher.setMailingAddress("123 Paper St., Schenectady, NY, 12345");
book.setPublisher(publisher);
em.persist(book);
} finally {
em.close();
}
out.println("<p>Object of kind \"Book\" saved. See <a href=\"/_ah/admin\">the datastore viewer</a>.</p>");
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS");
fmt.setTimeZone(new SimpleTimeZone(0, ""));
out.println("<p>The time is: " + fmt.format(new Date()) + "</p>");
}
}
| Java |
package properties;
import java.io.Serializable;
import java.util.Date;
// A Serializable class that can be a field type, stored as a
// datastore blob property value (not indexed). There are no special
// JPA annotations needed for this; any Serializable class will work.
public class PublisherMetadata implements Serializable {
private String itemCode;
private Date productionStartDate;
private Date productionEndDate;
public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}
public String getItemCode() {
return itemCode;
}
public void setProductionStartDate(Date productionStartDate) {
this.productionStartDate = productionStartDate;
}
public Date getProductionStartDate() {
return productionStartDate;
}
public void setProductionEndDate(Date productionEndDate) {
this.productionEndDate = productionEndDate;
}
public Date getProductionEndDate() {
return productionEndDate;
}
}
| Java |
package relationships;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.OneToMany;
import relationships.BookCoverImage;
import relationships.BookReview;
@Entity(name = "Book")
public class Book {
@Id
private String isbn;
private String title;
private String author;
private int copyrightYear;
private Date authorBirthdate;
@OneToMany(cascade=CascadeType.ALL, mappedBy="book")
private List<BookReview> bookReviews = null;
@OneToOne(cascade=CascadeType.ALL)
private BookCoverImage bookCoverImage;
public Book(String isbn) {
this.isbn = isbn;
}
public String getIsbn() {
return isbn;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthor() {
return author;
}
public void setCopyrightYear(int copyrightYear) {
this.copyrightYear = copyrightYear;
}
public int getCopyrightYear() {
return copyrightYear;
}
public void setAuthorBirthdate(Date authorBirthdate) {
this.authorBirthdate = authorBirthdate;
}
public Date getAuthorBirthdate() {
return authorBirthdate;
}
public void setBookReviews(List<BookReview> bookReviews) {
this.bookReviews = bookReviews;
}
public List<BookReview> getBookReviews() {
if (bookReviews == null) {
bookReviews = new ArrayList<BookReview>();
}
return bookReviews;
}
public void setBookCoverImage(BookCoverImage bookCoverImage) {
this.bookCoverImage = bookCoverImage;
}
public BookCoverImage getBookCoverImage() {
return bookCoverImage;
}
}
| Java |
package relationships;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public final class EMF {
private static final EntityManagerFactory emfInstance =
Persistence.createEntityManagerFactory("transactions-optional");
private EMF() {}
public static EntityManagerFactory get() {
return emfInstance;
}
}
| Java |
package relationships;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.SimpleTimeZone;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.servlet.http.*;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.KeyFactory.Builder;
import relationships.Book;
import relationships.BookReview;
import relationships.EMF;
@SuppressWarnings("serial")
public class JPARelationshipsServlet extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
EntityManagerFactory emf = EMF.get();
EntityManager em = null;
try {
em = emf.createEntityManager();
Book book = new Book("978-0141185064");
book.setTitle("The Grapes of Wrath");
book.setAuthor("John Steinbeck");
book.setCopyrightYear(1939);
Date authorBirthdate =
new GregorianCalendar(1902, Calendar.FEBRUARY, 27).getTime();
book.setAuthorBirthdate(authorBirthdate);
book.setBookCoverImage(new BookCoverImage());
book.getBookCoverImage().setType("image/jpg");
List<BookReview> bookReviews = book.getBookReviews();
BookReview bookReview = new BookReview();
bookReview.setRating(5);
bookReviews.add(bookReview);
bookReview = new BookReview();
bookReview.setRating(4);
bookReviews.add(bookReview);
EntityTransaction txn = em.getTransaction();
txn.begin();
try {
// When the Book is made persistent, the "PERSIST"
// action cascades to the BookCoverImage object and
// all BookReview objects.
em.persist(book);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
} finally {
em.close();
}
try {
em = emf.createEntityManager();
Book book = em.find(Book.class, "978-0141185064");
if (book != null) {
out.println("<p>Found <i>" + book.getTitle() + "</i></p>");
// Automatically fetch the BookCoverImage entity and access a field.
out.println("<p>Book cover image type: " + book.getBookCoverImage().getType() + "</p>");
out.println("<p>Ratings: ");
for (BookReview bookReview : book.getBookReviews()) {
out.println("[" + bookReview.getRating() + "] ");
}
out.println("</p>");
} else {
out.println("Could not find that book I was looking for...");
}
} finally {
em.close();
}
out.println("<p>Objects saved. See <a href=\"/_ah/admin\">the datastore viewer</a>.</p>");
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS");
fmt.setTimeZone(new SimpleTimeZone(0, ""));
out.println("<p>The time is: " + fmt.format(new Date()) + "</p>");
}
}
| Java |
package queries;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity(name = "Book")
public class Book {
@Id
private String isbn;
private String title;
private String author;
private int copyrightYear;
private Date authorBirthdate;
public Book(String isbn) {
this.isbn = isbn;
}
public String getIsbn() {
return isbn;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthor() {
return author;
}
public void setCopyrightYear(int copyrightYear) {
this.copyrightYear = copyrightYear;
}
public int getCopyrightYear() {
return copyrightYear;
}
public void setAuthorBirthdate(Date authorBirthdate) {
this.authorBirthdate = authorBirthdate;
}
public Date getAuthorBirthdate() {
return authorBirthdate;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.