Commit 5545c985 by LAPTOP-146U5DF5\28422

no message

parents
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="1.8" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="PLATFORM" />
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="1.8" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
<option name="resolveModulePerSourceSet" value="false" />
<option name="useQualifiedModuleNames" value="true" />
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="BintrayJCenter" />
<option name="name" value="BintrayJCenter" />
<option name="url" value="https://jcenter.bintray.com/" />
</remote-repository>
<remote-repository>
<option name="id" value="Google" />
<option name="name" value="Google" />
<option name="url" value="https://dl.google.com/dl/android/maven2/" />
</remote-repository>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
/build
\ No newline at end of file
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 30
defaultConfig {
applicationId "com.fear1ess.reyunaditool"
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'org.jsoup:jsoup:1.13.1'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
\ No newline at end of file
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
\ No newline at end of file
package com.fear1ess.reyunaditool;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.fear1ess.reyunaditool", appContext.getPackageName());
}
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.fear1ess.reyunaditool" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name=".AdiToolApp"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.ReyunAdiTool" >
<receiver
android:name=".ReBootBroadcastReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter android:priority="1000" >
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".RemoteService"
android:enabled="true"
android:exported="true"
android:process=":RemoteProcess" >
</service>
<service
android:name=".LocalService"
android:enabled="true"
android:exported="true" />
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".DoCommandService"
android:exported="true"
android:process=":HandleAppService" />
</application>
</manifest>
\ No newline at end of file
// DefendInterface.aidl
package com.fear1ess.reyunaditool;
// Declare any non-default types here with import statements
interface DefendInterface {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
String getServiceName();
}
\ No newline at end of file
// IRecvDataService.aidl
package com.fear1ess.reyunaditool;
// Declare any non-default types here with import statements
interface IDoCommandService {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
// void handleData(int cmd, in Map args);
String doCommand(int cmd, String args);
}
\ No newline at end of file
package com.fear1ess.reyunaditool;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
public class AdiToolApp extends Application {
private static Context mAppContext = null;
private Handler uiHandler = null;
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
synchronized (this){
if(mAppContext == null) mAppContext = base;
}
}
public static Context getAppContext(){
return mAppContext;
}
public Handler getUiHandler() {
return uiHandler;
}
public void setUiHandler(Handler uiHandler) {
this.uiHandler = uiHandler;
}
}
package com.fear1ess.reyunaditool;
public class AppInfo {
public String mPkgName;
public String mDownloadPath;
public AppInfo(String pkgName, String downloadPath) {
mPkgName = pkgName;
mDownloadPath = downloadPath;
}
}
package com.fear1ess.reyunaditool;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.fear1ess.reyunaditool.cmd.OperateCmd;
import com.fear1ess.reyunaditool.cmd.WSConnectCmd;
import com.fear1ess.reyunaditool.cmd.WSConnectCmd.ClientCmd;
import com.fear1ess.reyunaditool.server.NanoWSD;
import com.fear1ess.reyunaditool.thread.DownloadThread;
import com.fear1ess.reyunaditool.thread.InstallAndStartAppThread;
import com.fear1ess.reyunaditool.thread.RemoveAppProceduce;
import com.fear1ess.reyunaditool.thread.UploadAdsDataProceduce;
import com.fear1ess.reyunaditool.utils.PushMsgUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.charset.CharacterCodingException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class DoCommandService extends Service {
public static String TAG = "reyunaditool_log";
private String mCurPkgName;
private String mCurDownloadPath;
private String mCurAdsStateStr;
private WSCommandServer mWSServer;
private WSCommandServer.WSCommandWebSocket mWebSocket;
private volatile boolean isWSConnected = false;
public volatile boolean isUploadAdsData = false;
private Handler mUiHandler;
private InstallAndStartAppThread mInstallAndStartAppThread;
private DownloadThread mDownloadAppThread;
private Binder mBinder = new DoCommandBinder();
public NanoWSD.WebSocket getWebSocket(){
return mWebSocket;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind...");
return mBinder;
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onCreate() {
super.onCreate();
String CHANNEL_ONE_ID = "10086";
String CHANNEL_ONE_NAME= "ReyunDoCommandService";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel= new NotificationChannel(CHANNEL_ONE_ID,
CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (manager != null) {
manager.createNotificationChannel(notificationChannel);
}
}
Notification notification= new Notification.Builder(this, CHANNEL_ONE_ID)
.setChannelId(CHANNEL_ONE_ID)
.setTicker("Nature")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("启动服务")
.setContentText("ReyunAdiDommandService")
.build();
startForeground(1,notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand...");
//start websocket service
if(mWSServer == null) {
mWSServer = new WSCommandServer(2020);
Log.d(TAG, "start websocket server on port 2020...");
try {
mWSServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
startOperateAppThread();
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ....");
// mInstallAndStartAppThread.exit();
// mDownloadAppThread.exit();
stopForeground(true);
}
public void startOperateAppThread(){
Log.d(TAG, "startOperateAppThread...");
AdiToolApp app = (AdiToolApp) getApplication();
mUiHandler = app.getUiHandler();
Context cxt = AdiToolApp.getAppContext();
ExecutorService es = Executors.newCachedThreadPool();
if(mDownloadAppThread == null) {
mDownloadAppThread = new DownloadThread(cxt, mUiHandler, this);
es.execute(mDownloadAppThread);
}
if(mInstallAndStartAppThread == null) {
mInstallAndStartAppThread = new InstallAndStartAppThread(mDownloadAppThread, cxt, mUiHandler,this);
es.execute(mInstallAndStartAppThread);
}
es.shutdown();
}
public void sendMsgToClient(String str){
if(!isWSConnected) return;
try {
mWebSocket.send(str);
} catch (IOException e) {
e.printStackTrace();
}
}
public void setCurApp(String pkgName,String downloadPath){
mCurPkgName = pkgName;
mCurDownloadPath = downloadPath;
}
public void uploadAdsData(String str) {
Log.d(TAG, "start upload ads data: " + str);
ExecutorService es = Executors.newSingleThreadExecutor();
es.execute(new UploadAdsDataProceduce(str));
es.shutdown();
isUploadAdsData = true;
}
public void uploadErrorApkData() {
Log.d(TAG, "start upload empty ads data...");
ExecutorService es = Executors.newSingleThreadExecutor();
JSONObject jo = new JSONObject();
try {
jo.put("app_id", mCurPkgName);
jo.put("apk_error", 1);
} catch (JSONException e) {
e.printStackTrace();
}
es.execute(new UploadAdsDataProceduce(jo.toString()));
es.shutdown();
}
public class DoCommandBinder extends IDoCommandService.Stub{
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
}
@Override
public String doCommand(int cmd, String str) throws RemoteException {
switch (cmd) {
case OperateCmd.QUERY_CURRENT_PKGNAME: {
Log.d(TAG, "query current pkgname: " + mCurPkgName);
return mCurPkgName;
}
case OperateCmd.UPLOAD_ADSDK_INFO: {
uploadAdsData(str);
return "success";
}
case OperateCmd.SHUTDOWN_APP: {
ExecutorService es = Executors.newSingleThreadExecutor();
es.execute(new RemoveAppProceduce(mInstallAndStartAppThread, mCurPkgName, mCurDownloadPath, DoCommandService.this));
es.shutdown();
return "success";
}
case OperateCmd.UPLOAD_ADSDK_EXISTS_STATE: {
try {
if(mWebSocket != null){
mCurAdsStateStr = str;
JSONObject sendjo = new JSONObject(str);
sendjo.put("cmd", WSConnectCmd.ServerCmd.NEW_ADS_PUSH_MSG);
sendMsgToClient(sendjo.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
return "success";
}
default: return null;
}
}
}
public class WSCommandServer extends NanoWSD {
public WSCommandServer(int port) {
super(port);
}
@Override
protected WebSocket openWebSocket(IHTTPSession handshake) {
return new WSCommandWebSocket(handshake);
}
public class WSCommandWebSocket extends WebSocket{
public WSCommandWebSocket(IHTTPSession handshakeRequest) {
super(handshakeRequest);
}
@Override
protected void onOpen() {
if(isWSConnected){
try {
String str = "server has been connected by other device...";
send(new WebSocketFrame.CloseFrame(WebSocketFrame.CloseCode.GoingAway, str).getBinaryPayload());
} catch (IOException e) {
e.printStackTrace();
}
}
Log.d(TAG, "a client success to connect server...");
isWSConnected = true;
mWebSocket = this;
}
@Override
protected void onClose(WebSocketFrame.CloseCode code, String reason, boolean initiatedByRemote) {
Log.d(TAG, "onClose: ");
isWSConnected = false;
mWebSocket = null;
}
@Override
protected void onMessage(WebSocketFrame message) {
Log.d(TAG, "onMessage: ");
String data = message.getTextPayload();
try {
JSONObject jo = new JSONObject(data);
if(!jo.has("cmd")) send("error data format!");
int cmd = jo.getInt("cmd");
switch (cmd){
case ClientCmd.START_OPERATE_APP:
startOperateAppThread();
break;
case ClientCmd.STOP_SERVICE:
stopSelf();
break;
case ClientCmd.REQ_APP_ADS_STATE:
JSONObject sendjo = new JSONObject(mCurAdsStateStr);
sendjo.put("cmd", WSConnectCmd.ServerCmd.NEW_ADS_PUSH_MSG);
sendMsgToClient(sendjo.toString());
break;
default: break;
}
} catch (JSONException | IOException e) {
e.printStackTrace();
}
}
@Override
protected void onPong(WebSocketFrame pong) {
Log.d(TAG, "onPong: ");
}
@Override
protected void onException(IOException exception) {
Log.d(TAG, "onException: ");
}
}
/*
@Override
public Response serve(IHTTPSession sessionBase) {
if ((sessionBase instanceof HTTPSession) == false)
return newFixedLengthResponse("method error!");
HTTPSession session = ((HTTPSession) sessionBase);
Map<String, List<String>> queryMap = session.getParameters();
String cmdStr = queryMap.get("cmd").get(0);
int cmd = new Integer(cmdStr);
switch (cmd) {
case OperateCmd.QUERY_CURRENT_PKGNAME:
Log.d(TAG, "query current pkgname...");
return newFixedLengthResponse(mCurPkgName);
default: {
Message msg = Message.obtain();
msg.what = cmd;
Bundle bundle = new Bundle();
byte[] data = null;
if (Method.POST.equals(session.getMethod())) {
InputStream in = session.getInputStream();
Log.d(TAG, "body size: " + session.getBodySize());
data = new byte[(int) session.getBodySize()];
try {
in.read(data);
} catch (IOException e) {
e.printStackTrace();
}
}
bundle.putByteArray("data", data);
msg.setData(bundle);
mHandleAppHandler.sendMessage(msg);
return newFixedLengthResponse("success");
}
}
}*/
}
}
package com.fear1ess.reyunaditool;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.fear1ess.reyunaditool.MainActivity.MainActivityHandler;
public class DoWorkThread implements Runnable {
public Handler mainUiHandler = null;
public Context appContext = null;
public static String getAppInfoUrlStr = "http://adfly-api.adinsights-global.com/get_app_res/?count=1&ua=android";
public static String postAppInfoUrlStr = "http://adfly-api.adinsights-global.com/get_app_res/?ua=android";
public DoWorkThread(Context cxt,Handler handler){
mainUiHandler = handler;
appContext = cxt;
}
@Override
public void run() {
NetWorkUtils.Response res = NetWorkUtils.get(getAppInfoUrlStr,null);
if(res.resCode != 200){
Message message = Message.obtain();
message.what = MainActivityHandler.NETWORK_ERROR;
Bundle bundle = new Bundle();
bundle.putCharSequence("errText","获取app下载列表失败!请检查网络连接");
message.setData(bundle);
mainUiHandler.sendMessage(message);
return;
}
try {
JSONArray appInfoArray = new JSONObject(new String(res.resData)).getJSONArray("res");
ExecutorService es = Executors.newSingleThreadExecutor();
for(int i = 0;i<appInfoArray.length();++i){
JSONObject item = appInfoArray.getJSONObject(i);
// HandleAppThread tr = new HandleAppThread(appContext,mainUiHandler);
// es.execute(tr);
}
es.shutdown();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
package com.fear1ess.reyunaditool;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class ExecuteCmdUtils {
public static String TAG = "reyunaditool_log";
public static int executeCmd(String cmd){
Process p = null;
int exitCode = 0;
try {
p = Runtime.getRuntime().exec("su -c " + cmd);
exitCode = p.waitFor();
if(exitCode != 0){
byte[] b = new byte[1024];
InputStream is = p.getErrorStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
while((len = is.read(b)) != -1){
bos.write(b,0,len);
bos.flush();
}
String cmdErrMsg = new String(bos.toByteArray());
bos.close();
is.close();
Log.e(TAG, cmdErrMsg + " when execute cmd: " + cmd);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return exitCode;
}
public static int installApp(String downloadPath){
String cmd = "pm install " + downloadPath;
Log.d(TAG, "installApp " + downloadPath);
return executeCmd(cmd);
}
public static int finishApp(String packageName){
String cmd = "am force-stop " + packageName;
Log.d(TAG, "finishApp " + packageName);
return executeCmd(cmd);
}
public static int uninstallApp(String packageName){
String cmd = "pm uninstall " + packageName;
Log.d(TAG, "uninstallapp " + packageName);
return executeCmd(cmd);
}
public static int deletePkg(String downloadPath){
if(!downloadPath.startsWith("/sdcard/reyundownload")){
Log.e(TAG, "delete path is not reyundownload!!!" );
return -1;
}
String cmd = "rm -f " + downloadPath;
return executeCmd(cmd);
}
public static int startApp(Context appContext, String packageName) {
PackageManager pm = appContext.getPackageManager();
Intent intent = pm.getLaunchIntentForPackage(packageName);
if(intent == null) return -1;
ComponentName cn = intent.getComponent();
String pkgName = cn.getPackageName();
String className = cn.getClassName();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(intent);
return 0;
// Log.d(TAG, "startApp " + packageName);
// String cmd = "am start -n " + pkgName + "/" + className;
// return executeCmd(cmd);
}
}
package com.fear1ess.reyunaditool;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class LocalService extends Service {
private MyBinder mBinder;
public static Context m_comtext=null;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//获取RemoteService的 IBinder的对象
DefendInterface iMyAidlInterface = DefendInterface.Stub.asInterface(service);
try {
//
Intent intent = new Intent(LocalService.this.getBaseContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(intent);
Log.d("LocalService", "connected with " + iMyAidlInterface.getServiceName());
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
startService(new Intent(LocalService.this,RemoteService.class));
bindService(new Intent(LocalService.this,RemoteService.class),connection, Context.BIND_IMPORTANT);
}
};
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("myTest", "onStartCommand: 本地服务启动");
startService(new Intent(LocalService.this,RemoteService.class));
bindService(new Intent(this,RemoteService.class),connection, Context.BIND_IMPORTANT);
return START_STICKY;
}
public LocalService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
mBinder = new MyBinder();
return mBinder;
}
private class MyBinder extends DefendInterface.Stub {
@Override
public String getServiceName() throws RemoteException {
return LocalService.class.getName();
}
}
}
\ No newline at end of file
package com.fear1ess.reyunaditool;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocalService.m_comtext=getApplicationContext();
RemoteService.m_comtext=getApplicationContext();
startService(new Intent(this, LocalService.class));
AdiToolApp app = (AdiToolApp) getApplication();
Button startBtn = findViewById(R.id.start_btn);
Button stopBtn = findViewById(R.id.stop_btn);
stopBtn.setEnabled(false);
requestPermissions(new String[]{"android.permission.WRITE_EXTERNAL_STORAGE",
"android.permission.READ_EXTERNAL_STORAGE"},100);
startBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startBtn.setText("Working");
startBtn.setEnabled(false);
stopBtn.setEnabled(true);
Context cxt = AdiToolApp.getAppContext();
startForegroundService(new Intent(MainActivity.this, DoCommandService.class));
}
});
stopBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Context cxt = AdiToolApp.getAppContext();
stopService(new Intent(cxt, DoCommandService.class));
startBtn.setText("Start");
startBtn.setEnabled(true);
stopBtn.setEnabled(false);
}
});
new Thread(){
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
startBtn.performClick();
}
});
}
}.start();
}
public static class MainActivityHandler extends Handler{
public static final int NETWORK_ERROR = 0;
private WeakReference<Activity> mActivityWeakRef = null;
public MainActivityHandler(Activity activity){
mActivityWeakRef = new WeakReference<>(activity);
}
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what){
case NETWORK_ERROR:
CharSequence errText = msg.getData().getCharSequence("errText");
Toast t = Toast.makeText(mActivityWeakRef.get(),errText,Toast.LENGTH_SHORT);
t.show();
break;
default:
break;
}
}
}
}
\ No newline at end of file
package com.fear1ess.reyunaditool;
import android.content.res.Resources;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class NetWorkUtils {
public interface NetWorkCallback {
void onDownloadPkgNameGetSuccess(String name);
void onDownloadPkgNameGetfailed();
void onDownloadBytesUpdate (String name, int bytesDownloaded);
}
private static NetWorkCallback callback;
public static void setNetWorkCallback(NetWorkCallback cb) {
callback = cb;
}
private static Response get(String urlStr,HashMap<String,String> headers,OutputStream os){
if(os == null){
os = new ByteArrayOutputStream();
}
Response res = null;
if(urlStr.startsWith("https://")) res = httpsReq(urlStr,headers,null,os);
else if(urlStr.startsWith("http://")) res = httpReq(urlStr,headers,null,os);
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
private static Response post(String urlStr,HashMap<String,String> headers,byte[] data,OutputStream os){
if(os == null){
os = new ByteArrayOutputStream();
}
Response res = null;
if(urlStr.startsWith("https://")) res = httpsReq(urlStr,headers,data,os);
else if(urlStr.startsWith("http://")) res = httpReq(urlStr,headers,data,os);
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
public static Response get(String urlStr,HashMap<String,String> headers){
return get(urlStr,headers,null);
}
public static Response post(String urlStr,HashMap<String,String> headers,byte[] data){
return post(urlStr,headers,data,null);
}
public static Response download(String urlStr,HashMap<String,String> headers,byte[] data,String downloadPath) {
File fi = new File(downloadPath);
try {
if(!fi.exists()) fi.createNewFile();
FileOutputStream fos = null;
fos = new FileOutputStream(fi);
if(data == null) return get(urlStr,headers,fos);
else return post(urlStr,headers,data,fos);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static Response httpReq(String urlStr, HashMap<String,String> headers, byte[] postData,OutputStream os) {
boolean isDownload = false;
if(os instanceof FileOutputStream) {
isDownload = true;
}
Response res = null;
HttpURLConnection huc = null;
try {
URL getAppInfoUrl = new URL(urlStr);
huc = (HttpURLConnection) getAppInfoUrl.openConnection();
if(postData == null) huc.setRequestMethod("GET");
else {
huc.setRequestMethod("POST");
huc.setRequestProperty("Content-Type", "application/json");
}
if(headers != null){
for(Map.Entry<String,String> entry:headers.entrySet()){
huc.setRequestProperty(entry.getKey(),entry.getValue());
}
}
huc.setConnectTimeout(10*1000);
huc.setReadTimeout(10*1000);
huc.connect();
if(postData != null){
OutputStream out = huc.getOutputStream();
out.write(postData);
out.flush();
}
String fileName = huc.getHeaderField("Content-Disposition");
if(fileName == null){
callback.onDownloadPkgNameGetfailed();
huc.disconnect();
return null;
}
String pkgName = fileName.replace("attachment; filename=","")
.replace(".apk", "");
if(isDownload){
callback.onDownloadPkgNameGetSuccess(pkgName);
}
InputStream is = huc.getInputStream();
byte[] data = new byte[8192];
int len = 0;
int totalBytes = 0;
while((len = is.read(data)) != -1){
os.write(data,0,len);
totalBytes += len;
if(isDownload){
if(fileName != null) {
callback.onDownloadBytesUpdate(pkgName, totalBytes);
}
}
}
os.flush();
byte[] resData = null;
if(os instanceof ByteArrayOutputStream) {
resData = ((ByteArrayOutputStream) os).toByteArray();
}
res = new Response(huc.getResponseCode(),huc.getResponseMessage(),resData,pkgName);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
os.close();
huc.getInputStream().close();
} catch (IOException e) {
e.printStackTrace();
}finally {
Log.d("aditool", "close httpconnection.... ");
huc.disconnect();
return res;
}
}
}
private static Response httpsReq(String urlStr, HashMap<String,String> headers,byte[] postData,OutputStream os){
URL getAppInfoUrl = null;
Response res = null;
try {
getAppInfoUrl = new URL(urlStr);
HttpsURLConnection huc = (HttpsURLConnection) getAppInfoUrl.openConnection();
if(postData == null) huc.setRequestMethod("GET");
else huc.setRequestMethod("POST");
if(headers != null){
for(Map.Entry<String,String> entry:headers.entrySet()){
huc.setRequestProperty(entry.getKey(),entry.getValue());
}
}
huc.setConnectTimeout(5000);
huc.setHostnameVerifier(new TrustAllHostnamesVerifier());
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null,new TrustManager[]{new TrustAllCertificateManager()},new SecureRandom());
huc.setSSLSocketFactory(sc.getSocketFactory());
huc.connect();
if(postData != null){
OutputStream out = huc.getOutputStream();
out.write(postData);
out.flush();
}
InputStream is = huc.getInputStream();
byte[] data = new byte[8192];
// ByteArrayOutputStream bo = new ByteArrayOutputStream();
int len = 0;
while((len = is.read(data)) != -1){
os.write(data,0,len);
}
os.flush();
byte[] resData = null;
if(os instanceof ByteArrayOutputStream) {
resData = ((ByteArrayOutputStream)os).toByteArray();
}
String fileName = huc.getHeaderField("Content-Disposition");
res = new Response(huc.getResponseCode(),huc.getResponseMessage(),resData,fileName);
os.close();
is.close();
huc.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return res;
}
public static class Response{
public int resCode;
public String resMessage;
public byte[] resData;
public String resFileName;
public Response(int code,String msg,byte[] data,String fileName){
resCode = code;
resMessage = msg;
resData = data;
resFileName = fileName;
}
}
public static class TrustAllHostnamesVerifier implements HostnameVerifier{
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
}
public static class TrustAllCertificateManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}
package com.fear1ess.reyunaditool;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ReBootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
{
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
\ No newline at end of file
package com.fear1ess.reyunaditool;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import androidx.annotation.RequiresApi;
public class RemoteService extends Service {
private MyBinder mBinder;
public static Context m_comtext=null;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
DefendInterface iMyAidlInterface = DefendInterface.Stub.asInterface(service);
try {
Log.d("RemoteService", "connected with " + iMyAidlInterface.getServiceName());
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
startService(new Intent(RemoteService.this,LocalService.class));
bindService(new Intent(RemoteService.this,LocalService.class),connection, Context.BIND_IMPORTANT);
}
};
public RemoteService() {
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onCreate() {
super.onCreate();
String CHANNEL_ONE_ID = "100861";
String CHANNEL_ONE_NAME= "RemoteService";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel= new NotificationChannel(CHANNEL_ONE_ID,
CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (manager != null) {
manager.createNotificationChannel(notificationChannel);
}
}
Notification notification= new Notification.Builder(this, CHANNEL_ONE_ID)
.setChannelId(CHANNEL_ONE_ID)
.setTicker("Nature")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("远程保活服务")
.setContentText("DefendProcess")
.build();
startForeground(2,notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("myTest", "onStartCommand: 远程服务启动");
bindService(new Intent(this,LocalService.class),connection, Context.BIND_IMPORTANT);
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
mBinder = new MyBinder();
return mBinder;
}
private class MyBinder extends DefendInterface.Stub{
@Override
public String getServiceName() throws RemoteException {
return RemoteService.class.getName();
}
}
}
\ No newline at end of file
package com.fear1ess.reyunaditool;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onStart() {
super.onStart();
startMainActivity();
}
public void startMainActivity(){
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
finish();
}
}
package com.fear1ess.reyunaditool.cmd;
public class OperateCmd {
public final static int SHUTDOWN_APP = 0;
public final static int UPLOAD_ADSDK_INFO = 1;
public final static int QUERY_CURRENT_PKGNAME = 2;
public final static int UPLOAD_ADSDK_EXISTS_STATE = 3;
}
package com.fear1ess.reyunaditool.cmd;
public class WSConnectCmd {
public class ClientCmd {
public final static int START_OPERATE_APP = 1;
public final static int STOP_SERVICE = 2;
public final static int REQ_APP_ADS_STATE = 3;
}
public class ServerCmd {
public final static int NEW_APP_PUSH_MSG = 101;
public final static int NEW_ADS_PUSH_MSG = 102;
}
}
package com.fear1ess.reyunaditool.server;
/*
* #%L
* NanoHttpd-Core
* %%
* Copyright (C) 2012 - 2015 nanohttpd
* %%
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the nanohttpd nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.security.KeyStore;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.TrustManagerFactory;
/**
* A simple, tiny, nicely embeddable HTTP server in Java
* <p/>
* <p/>
* NanoHTTPD
* <p>
* Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen,
* 2010 by Konstantinos Togias
* </p>
* <p/>
* <p/>
* <b>Features + limitations: </b>
* <ul>
* <p/>
* <li>Only one Java file</li>
* <li>Java 5 compatible</li>
* <li>Released as open source, Modified BSD licence</li>
* <li>No fixed config files, logging, authorization etc. (Implement yourself if
* you need them.)</li>
* <li>Supports parameter parsing of GET and POST methods (+ rudimentary PUT
* support in 1.25)</li>
* <li>Supports both dynamic content and file serving</li>
* <li>Supports file upload (since version 1.2, 2010)</li>
* <li>Supports partial content (streaming)</li>
* <li>Supports ETags</li>
* <li>Never caches anything</li>
* <li>Doesn't limit bandwidth, request time or simultaneous connections</li>
* <li>Default code serves files and shows all HTTP parameters and headers</li>
* <li>File server supports directory listing, index.html and index.htm</li>
* <li>File server supports partial content (streaming)</li>
* <li>File server supports ETags</li>
* <li>File server does the 301 redirection trick for directories without '/'</li>
* <li>File server supports simple skipping for files (continue download)</li>
* <li>File server serves also very long files without memory overhead</li>
* <li>Contains a built-in list of most common MIME types</li>
* <li>All header names are converted to lower case so they don't vary between
* browsers/clients</li>
* <p/>
* </ul>
* <p/>
* <p/>
* <b>How to use: </b>
* <ul>
* <p/>
* <li>Subclass and implement serve() and embed to your own program</li>
* <p/>
* </ul>
* <p/>
* See the separate "LICENSE.md" file for the distribution license (Modified BSD
* licence)
*/
public abstract class NanoHTTPD {
/**
* Pluggable strategy for asynchronously executing requests.
*/
public interface AsyncRunner {
void closeAll();
void closed(ClientHandler clientHandler);
void exec(ClientHandler code);
}
/**
* The runnable that will be used for every new client connection.
*/
public class ClientHandler implements Runnable {
private final InputStream inputStream;
private final Socket acceptSocket;
public ClientHandler(InputStream inputStream, Socket acceptSocket) {
this.inputStream = inputStream;
this.acceptSocket = acceptSocket;
}
public void close() {
safeClose(this.inputStream);
safeClose(this.acceptSocket);
}
@Override
public void run() {
OutputStream outputStream = null;
try {
outputStream = this.acceptSocket.getOutputStream();
TempFileManager tempFileManager = NanoHTTPD.this.tempFileManagerFactory.create();
HTTPSession session = new HTTPSession(tempFileManager, this.inputStream, outputStream, this.acceptSocket.getInetAddress());
while (!this.acceptSocket.isClosed()) {
session.execute();
}
} catch (Exception e) {
// When the socket is closed by the client,
// we throw our own SocketException
// to break the "keep alive" loop above. If
// the exception was anything other
// than the expected SocketException OR a
// SocketTimeoutException, print the
// stacktrace
if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage())) && !(e instanceof SocketTimeoutException)) {
NanoHTTPD.LOG.log(Level.SEVERE, "Communication with the client broken, or an bug in the handler code", e);
}
} finally {
safeClose(outputStream);
safeClose(this.inputStream);
safeClose(this.acceptSocket);
NanoHTTPD.this.asyncRunner.closed(this);
}
}
}
public static class Cookie {
public static String getHTTPTime(int days) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar.add(Calendar.DAY_OF_MONTH, days);
return dateFormat.format(calendar.getTime());
}
private final String n, v, e;
public Cookie(String name, String value) {
this(name, value, 30);
}
public Cookie(String name, String value, int numDays) {
this.n = name;
this.v = value;
this.e = getHTTPTime(numDays);
}
public Cookie(String name, String value, String expires) {
this.n = name;
this.v = value;
this.e = expires;
}
public String getHTTPHeader() {
String fmt = "%s=%s; expires=%s";
return String.format(fmt, this.n, this.v, this.e);
}
}
/**
* Provides rudimentary support for cookies. Doesn't support 'path',
* 'secure' nor 'httpOnly'. Feel free to improve it and/or add unsupported
* features.
*
* @author LordFokas
*/
public class CookieHandler implements Iterable<String> {
private final HashMap<String, String> cookies = new HashMap<String, String>();
private final ArrayList<Cookie> queue = new ArrayList<Cookie>();
public CookieHandler(Map<String, String> httpHeaders) {
String raw = httpHeaders.get("cookie");
if (raw != null) {
String[] tokens = raw.split(";");
for (String token : tokens) {
String[] data = token.trim().split("=");
if (data.length == 2) {
this.cookies.put(data[0], data[1]);
}
}
}
}
/**
* Set a cookie with an expiration date from a month ago, effectively
* deleting it on the client side.
*
* @param name
* The cookie name.
*/
public void delete(String name) {
set(name, "-delete-", -30);
}
@Override
public Iterator<String> iterator() {
return this.cookies.keySet().iterator();
}
/**
* Read a cookie from the HTTP Headers.
*
* @param name
* The cookie's name.
* @return The cookie's value if it exists, null otherwise.
*/
public String read(String name) {
return this.cookies.get(name);
}
public void set(Cookie cookie) {
this.queue.add(cookie);
}
/**
* Sets a cookie.
*
* @param name
* The cookie's name.
* @param value
* The cookie's value.
* @param expires
* How many days until the cookie expires.
*/
public void set(String name, String value, int expires) {
this.queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires)));
}
/**
* Internally used by the webserver to add all queued cookies into the
* Response's HTTP Headers.
*
* @param response
* The Response object to which headers the queued cookies
* will be added.
*/
public void unloadQueue(Response response) {
for (Cookie cookie : this.queue) {
response.addHeader("Set-Cookie", cookie.getHTTPHeader());
}
}
}
/**
* Default threading strategy for NanoHTTPD.
* <p/>
* <p>
* By default, the server spawns a new Thread for every incoming request.
* These are set to <i>daemon</i> status, and named according to the request
* number. The name is useful when profiling the application.
* </p>
*/
public static class DefaultAsyncRunner implements AsyncRunner {
private long requestCount;
private final List<ClientHandler> running = Collections.synchronizedList(new ArrayList<ClientHandler>());
/**
* @return a list with currently running clients.
*/
public List<ClientHandler> getRunning() {
return running;
}
@Override
public void closeAll() {
// copy of the list for concurrency
for (ClientHandler clientHandler : new ArrayList<ClientHandler>(this.running)) {
clientHandler.close();
}
}
@Override
public void closed(ClientHandler clientHandler) {
this.running.remove(clientHandler);
}
@Override
public void exec(ClientHandler clientHandler) {
++this.requestCount;
Thread t = new Thread(clientHandler);
t.setDaemon(true);
t.setName("NanoHttpd Request Processor (#" + this.requestCount + ")");
this.running.add(clientHandler);
t.start();
}
}
/**
* Default strategy for creating and cleaning up temporary files.
* <p/>
* <p>
* By default, files are created by <code>File.createTempFile()</code> in
* the directory specified.
* </p>
*/
public static class DefaultTempFile implements TempFile {
private final File file;
private final OutputStream fstream;
public DefaultTempFile(File tempdir) throws IOException {
this.file = File.createTempFile("NanoHTTPD-", "", tempdir);
this.fstream = new FileOutputStream(this.file);
}
@Override
public void delete() throws Exception {
safeClose(this.fstream);
if (!this.file.delete()) {
throw new Exception("could not delete temporary file: " + this.file.getAbsolutePath());
}
}
@Override
public String getName() {
return this.file.getAbsolutePath();
}
@Override
public OutputStream open() throws Exception {
return this.fstream;
}
}
/**
* Default strategy for creating and cleaning up temporary files.
* <p/>
* <p>
* This class stores its files in the standard location (that is, wherever
* <code>java.io.tmpdir</code> points to). Files are added to an internal
* list, and deleted when no longer needed (that is, when
* <code>clear()</code> is invoked at the end of processing a request).
* </p>
*/
public static class DefaultTempFileManager implements TempFileManager {
private final File tmpdir;
private final List<TempFile> tempFiles;
public DefaultTempFileManager() {
this.tmpdir = new File(System.getProperty("java.io.tmpdir"));
if (!tmpdir.exists()) {
tmpdir.mkdirs();
}
this.tempFiles = new ArrayList<TempFile>();
}
@Override
public void clear() {
for (TempFile file : this.tempFiles) {
try {
file.delete();
} catch (Exception ignored) {
NanoHTTPD.LOG.log(Level.WARNING, "could not delete file ", ignored);
}
}
this.tempFiles.clear();
}
@Override
public TempFile createTempFile(String filename_hint) throws Exception {
DefaultTempFile tempFile = new DefaultTempFile(this.tmpdir);
this.tempFiles.add(tempFile);
return tempFile;
}
}
/**
* Default strategy for creating and cleaning up temporary files.
*/
private class DefaultTempFileManagerFactory implements TempFileManagerFactory {
@Override
public TempFileManager create() {
return new DefaultTempFileManager();
}
}
/**
* Creates a normal ServerSocket for TCP connections
*/
public static class DefaultServerSocketFactory implements ServerSocketFactory {
@Override
public ServerSocket create() throws IOException {
return new ServerSocket();
}
}
/**
* Creates a new SSLServerSocket
*/
public static class SecureServerSocketFactory implements ServerSocketFactory {
private SSLServerSocketFactory sslServerSocketFactory;
private String[] sslProtocols;
public SecureServerSocketFactory(SSLServerSocketFactory sslServerSocketFactory, String[] sslProtocols) {
this.sslServerSocketFactory = sslServerSocketFactory;
this.sslProtocols = sslProtocols;
}
@Override
public ServerSocket create() throws IOException {
SSLServerSocket ss = null;
ss = (SSLServerSocket) this.sslServerSocketFactory.createServerSocket();
if (this.sslProtocols != null) {
ss.setEnabledProtocols(this.sslProtocols);
} else {
ss.setEnabledProtocols(ss.getSupportedProtocols());
}
ss.setUseClientMode(false);
ss.setWantClientAuth(false);
ss.setNeedClientAuth(false);
return ss;
}
}
private static final String CONTENT_DISPOSITION_REGEX = "([ |\t]*Content-Disposition[ |\t]*:)(.*)";
private static final Pattern CONTENT_DISPOSITION_PATTERN = Pattern.compile(CONTENT_DISPOSITION_REGEX, Pattern.CASE_INSENSITIVE);
private static final String CONTENT_TYPE_REGEX = "([ |\t]*content-type[ |\t]*:)(.*)";
private static final Pattern CONTENT_TYPE_PATTERN = Pattern.compile(CONTENT_TYPE_REGEX, Pattern.CASE_INSENSITIVE);
private static final String CONTENT_DISPOSITION_ATTRIBUTE_REGEX = "[ |\t]*([a-zA-Z]*)[ |\t]*=[ |\t]*['|\"]([^\"^']*)['|\"]";
private static final Pattern CONTENT_DISPOSITION_ATTRIBUTE_PATTERN = Pattern.compile(CONTENT_DISPOSITION_ATTRIBUTE_REGEX);
protected static class ContentType {
private static final String ASCII_ENCODING = "US-ASCII";
private static final String MULTIPART_FORM_DATA_HEADER = "multipart/form-data";
private static final String CONTENT_REGEX = "[ |\t]*([^/^ ^;^,]+/[^ ^;^,]+)";
private static final Pattern MIME_PATTERN = Pattern.compile(CONTENT_REGEX, Pattern.CASE_INSENSITIVE);
private static final String CHARSET_REGEX = "[ |\t]*(charset)[ |\t]*=[ |\t]*['|\"]?([^\"^'^;^,]*)['|\"]?";
private static final Pattern CHARSET_PATTERN = Pattern.compile(CHARSET_REGEX, Pattern.CASE_INSENSITIVE);
private static final String BOUNDARY_REGEX = "[ |\t]*(boundary)[ |\t]*=[ |\t]*['|\"]?([^\"^'^;^,]*)['|\"]?";
private static final Pattern BOUNDARY_PATTERN = Pattern.compile(BOUNDARY_REGEX, Pattern.CASE_INSENSITIVE);
private final String contentTypeHeader;
private final String contentType;
private final String encoding;
private final String boundary;
public ContentType(String contentTypeHeader) {
this.contentTypeHeader = contentTypeHeader;
if (contentTypeHeader != null) {
contentType = getDetailFromContentHeader(contentTypeHeader, MIME_PATTERN, "", 1);
encoding = getDetailFromContentHeader(contentTypeHeader, CHARSET_PATTERN, null, 2);
} else {
contentType = "";
encoding = "UTF-8";
}
if (MULTIPART_FORM_DATA_HEADER.equalsIgnoreCase(contentType)) {
boundary = getDetailFromContentHeader(contentTypeHeader, BOUNDARY_PATTERN, null, 2);
} else {
boundary = null;
}
}
private String getDetailFromContentHeader(String contentTypeHeader, Pattern pattern, String defaultValue, int group) {
Matcher matcher = pattern.matcher(contentTypeHeader);
return matcher.find() ? matcher.group(group) : defaultValue;
}
public String getContentTypeHeader() {
return contentTypeHeader;
}
public String getContentType() {
return contentType;
}
public String getEncoding() {
return encoding == null ? ASCII_ENCODING : encoding;
}
public String getBoundary() {
return boundary;
}
public boolean isMultipart() {
return MULTIPART_FORM_DATA_HEADER.equalsIgnoreCase(contentType);
}
public ContentType tryUTF8() {
if (encoding == null) {
return new ContentType(this.contentTypeHeader + "; charset=UTF-8");
}
return this;
}
}
protected class HTTPSession implements IHTTPSession {
private static final int REQUEST_BUFFER_LEN = 512;
private static final int MEMORY_STORE_LIMIT = 1024;
public static final int BUFSIZE = 8192;
public static final int MAX_HEADER_SIZE = 1024;
private final TempFileManager tempFileManager;
private final OutputStream outputStream;
private final BufferedInputStream inputStream;
private int splitbyte;
private int rlen;
private String uri;
private Method method;
private Map<String, List<String>> parms;
private Map<String, String> headers;
private CookieHandler cookies;
private String queryParameterString;
private String remoteIp;
private String remoteHostname;
private String protocolVersion;
public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream) {
this.tempFileManager = tempFileManager;
this.inputStream = new BufferedInputStream(inputStream, HTTPSession.BUFSIZE);
this.outputStream = outputStream;
}
public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) {
this.tempFileManager = tempFileManager;
this.inputStream = new BufferedInputStream(inputStream, HTTPSession.BUFSIZE);
this.outputStream = outputStream;
this.remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString();
this.remoteHostname = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "localhost" : inetAddress.getHostName().toString();
this.headers = new HashMap<String, String>();
}
/**
* Decodes the sent headers and loads the data into Key/value pairs
*/
private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, List<String>> parms, Map<String, String> headers) throws ResponseException {
try {
// Read the request line
String inLine = in.readLine();
if (inLine == null) {
return;
}
StringTokenizer st = new StringTokenizer(inLine);
if (!st.hasMoreTokens()) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html");
}
pre.put("method", st.nextToken());
if (!st.hasMoreTokens()) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html");
}
String uri = st.nextToken();
// Decode parameters from the URI
int qmi = uri.indexOf('?');
if (qmi >= 0) {
decodeParms(uri.substring(qmi + 1), parms);
uri = decodePercent(uri.substring(0, qmi));
} else {
uri = decodePercent(uri);
}
// If there's another token, its protocol version,
// followed by HTTP headers.
// NOTE: this now forces header names lower case since they are
// case insensitive and vary by client.
if (st.hasMoreTokens()) {
protocolVersion = st.nextToken();
} else {
protocolVersion = "HTTP/1.1";
NanoHTTPD.LOG.log(Level.FINE, "no protocol version specified, strange. Assuming HTTP/1.1.");
}
String line = in.readLine();
while (line != null && !line.trim().isEmpty()) {
int p = line.indexOf(':');
if (p >= 0) {
headers.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim());
}
line = in.readLine();
}
pre.put("uri", uri);
} catch (IOException ioe) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
}
}
/**
* Decodes the Multipart Body data and put it into Key/Value pairs.
*/
private void decodeMultipartFormData(ContentType contentType, ByteBuffer fbuf, Map<String, List<String>> parms, Map<String, String> files) throws ResponseException {
int pcount = 0;
try {
int[] boundaryIdxs = getBoundaryPositions(fbuf, contentType.getBoundary().getBytes());
if (boundaryIdxs.length < 2) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but contains less than two boundary strings.");
}
byte[] partHeaderBuff = new byte[MAX_HEADER_SIZE];
for (int boundaryIdx = 0; boundaryIdx < boundaryIdxs.length - 1; boundaryIdx++) {
fbuf.position(boundaryIdxs[boundaryIdx]);
int len = (fbuf.remaining() < MAX_HEADER_SIZE) ? fbuf.remaining() : MAX_HEADER_SIZE;
fbuf.get(partHeaderBuff, 0, len);
BufferedReader in =
new BufferedReader(new InputStreamReader(new ByteArrayInputStream(partHeaderBuff, 0, len), Charset.forName(contentType.getEncoding())), len);
int headerLines = 0;
// First line is boundary string
String mpline = in.readLine();
headerLines++;
if (mpline == null || !mpline.contains(contentType.getBoundary())) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but chunk does not start with boundary.");
}
String partName = null, fileName = null, partContentType = null;
// Parse the reset of the header lines
mpline = in.readLine();
headerLines++;
while (mpline != null && mpline.trim().length() > 0) {
Matcher matcher = CONTENT_DISPOSITION_PATTERN.matcher(mpline);
if (matcher.matches()) {
String attributeString = matcher.group(2);
matcher = CONTENT_DISPOSITION_ATTRIBUTE_PATTERN.matcher(attributeString);
while (matcher.find()) {
String key = matcher.group(1);
if ("name".equalsIgnoreCase(key)) {
partName = matcher.group(2);
} else if ("filename".equalsIgnoreCase(key)) {
fileName = matcher.group(2);
// add these two line to support multiple
// files uploaded using the same field Id
if (!fileName.isEmpty()) {
if (pcount > 0)
partName = partName + String.valueOf(pcount++);
else
pcount++;
}
}
}
}
matcher = CONTENT_TYPE_PATTERN.matcher(mpline);
if (matcher.matches()) {
partContentType = matcher.group(2).trim();
}
mpline = in.readLine();
headerLines++;
}
int partHeaderLength = 0;
while (headerLines-- > 0) {
partHeaderLength = scipOverNewLine(partHeaderBuff, partHeaderLength);
}
// Read the part data
if (partHeaderLength >= len - 4) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "Multipart header size exceeds MAX_HEADER_SIZE.");
}
int partDataStart = boundaryIdxs[boundaryIdx] + partHeaderLength;
int partDataEnd = boundaryIdxs[boundaryIdx + 1] - 4;
fbuf.position(partDataStart);
List<String> values = parms.get(partName);
if (values == null) {
values = new ArrayList<String>();
parms.put(partName, values);
}
if (partContentType == null) {
// Read the part into a string
byte[] data_bytes = new byte[partDataEnd - partDataStart];
fbuf.get(data_bytes);
values.add(new String(data_bytes, contentType.getEncoding()));
} else {
// Read it into a file
String path = saveTmpFile(fbuf, partDataStart, partDataEnd - partDataStart, fileName);
if (!files.containsKey(partName)) {
files.put(partName, path);
} else {
int count = 2;
while (files.containsKey(partName + count)) {
count++;
}
files.put(partName + count, path);
}
values.add(fileName);
}
}
} catch (ResponseException re) {
throw re;
} catch (Exception e) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, e.toString());
}
}
private int scipOverNewLine(byte[] partHeaderBuff, int index) {
while (partHeaderBuff[index] != '\n') {
index++;
}
return ++index;
}
/**
* Decodes parameters in percent-encoded URI-format ( e.g.
* "name=Jack%20Daniels&pass=Single%20Malt" ) and adds them to given
* Map.
*/
private void decodeParms(String parms, Map<String, List<String>> p) {
if (parms == null) {
this.queryParameterString = "";
return;
}
this.queryParameterString = parms;
StringTokenizer st = new StringTokenizer(parms, "&");
while (st.hasMoreTokens()) {
String e = st.nextToken();
int sep = e.indexOf('=');
String key = null;
String value = null;
if (sep >= 0) {
key = decodePercent(e.substring(0, sep)).trim();
value = decodePercent(e.substring(sep + 1));
} else {
key = decodePercent(e).trim();
value = "";
}
List<String> values = p.get(key);
if (values == null) {
values = new ArrayList<String>();
p.put(key, values);
}
values.add(value);
}
}
@Override
public void execute() throws IOException {
Response r = null;
try {
// Read the first 8192 bytes.
// The full header should fit in here.
// Apache's default header limit is 8KB.
// Do NOT assume that a single read will get the entire header
// at once!
byte[] buf = new byte[HTTPSession.BUFSIZE];
this.splitbyte = 0;
this.rlen = 0;
int read = -1;
this.inputStream.mark(HTTPSession.BUFSIZE);
try {
read = this.inputStream.read(buf, 0, HTTPSession.BUFSIZE);
} catch (SSLException e) {
throw e;
} catch (IOException e) {
safeClose(this.inputStream);
safeClose(this.outputStream);
throw new SocketException("NanoHttpd Shutdown");
}
if (read == -1) {
// socket was been closed
safeClose(this.inputStream);
safeClose(this.outputStream);
throw new SocketException("NanoHttpd Shutdown");
}
while (read > 0) {
this.rlen += read;
this.splitbyte = findHeaderEnd(buf, this.rlen);
if (this.splitbyte > 0) {
break;
}
read = this.inputStream.read(buf, this.rlen, HTTPSession.BUFSIZE - this.rlen);
}
if (this.splitbyte < this.rlen) {
this.inputStream.reset();
this.inputStream.skip(this.splitbyte);
}
this.parms = new HashMap<String, List<String>>();
if (null == this.headers) {
this.headers = new HashMap<String, String>();
} else {
this.headers.clear();
}
// Create a BufferedReader for parsing the header.
BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, this.rlen)));
// Decode the header into parms and header java properties
Map<String, String> pre = new HashMap<String, String>();
decodeHeader(hin, pre, this.parms, this.headers);
if (null != this.remoteIp) {
this.headers.put("remote-addr", this.remoteIp);
this.headers.put("http-client-ip", this.remoteIp);
}
this.method = Method.lookup(pre.get("method"));
if (this.method == null) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. HTTP verb " + pre.get("method") + " unhandled.");
}
this.uri = pre.get("uri");
this.cookies = new CookieHandler(this.headers);
String connection = this.headers.get("connection");
boolean keepAlive = "HTTP/1.1".equals(protocolVersion) && (connection == null || !connection.matches("(?i).*close.*"));
// Ok, now do the serve()
// TODO: long body_size = getBodySize();
// TODO: long pos_before_serve = this.inputStream.totalRead()
// (requires implementation for totalRead())
r = serve(this);
// TODO: this.inputStream.skip(body_size -
// (this.inputStream.totalRead() - pos_before_serve))
if (r == null) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response.");
} else {
String acceptEncoding = this.headers.get("accept-encoding");
this.cookies.unloadQueue(r);
r.setRequestMethod(this.method);
r.setGzipEncoding(useGzipWhenAccepted(r) && acceptEncoding != null && acceptEncoding.contains("gzip"));
r.setKeepAlive(keepAlive);
r.send(this.outputStream);
}
if (!keepAlive || r.isCloseConnection()) {
throw new SocketException("NanoHttpd Shutdown");
}
} catch (SocketException e) {
// throw it out to close socket object (finalAccept)
throw e;
} catch (SocketTimeoutException ste) {
// treat socket timeouts the same way we treat socket exceptions
// i.e. close the stream & finalAccept object by throwing the
// exception up the call stack.
throw ste;
} catch (SSLException ssle) {
Response resp = newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SSL PROTOCOL FAILURE: " + ssle.getMessage());
resp.send(this.outputStream);
safeClose(this.outputStream);
} catch (IOException ioe) {
Response resp = newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
resp.send(this.outputStream);
safeClose(this.outputStream);
} catch (ResponseException re) {
Response resp = newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage());
resp.send(this.outputStream);
safeClose(this.outputStream);
} finally {
safeClose(r);
this.tempFileManager.clear();
}
}
/**
* Find byte index separating header from body. It must be the last byte
* of the first two sequential new lines.
*/
private int findHeaderEnd(final byte[] buf, int rlen) {
int splitbyte = 0;
while (splitbyte + 1 < rlen) {
// RFC2616
if (buf[splitbyte] == '\r' && buf[splitbyte + 1] == '\n' && splitbyte + 3 < rlen && buf[splitbyte + 2] == '\r' && buf[splitbyte + 3] == '\n') {
return splitbyte + 4;
}
// tolerance
if (buf[splitbyte] == '\n' && buf[splitbyte + 1] == '\n') {
return splitbyte + 2;
}
splitbyte++;
}
return 0;
}
/**
* Find the byte positions where multipart boundaries start. This reads
* a large block at a time and uses a temporary buffer to optimize
* (memory mapped) file access.
*/
private int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) {
int[] res = new int[0];
if (b.remaining() < boundary.length) {
return res;
}
int search_window_pos = 0;
byte[] search_window = new byte[4 * 1024 + boundary.length];
int first_fill = (b.remaining() < search_window.length) ? b.remaining() : search_window.length;
b.get(search_window, 0, first_fill);
int new_bytes = first_fill - boundary.length;
do {
// Search the search_window
for (int j = 0; j < new_bytes; j++) {
for (int i = 0; i < boundary.length; i++) {
if (search_window[j + i] != boundary[i])
break;
if (i == boundary.length - 1) {
// Match found, add it to results
int[] new_res = new int[res.length + 1];
System.arraycopy(res, 0, new_res, 0, res.length);
new_res[res.length] = search_window_pos + j;
res = new_res;
}
}
}
search_window_pos += new_bytes;
// Copy the end of the buffer to the start
System.arraycopy(search_window, search_window.length - boundary.length, search_window, 0, boundary.length);
// Refill search_window
new_bytes = search_window.length - boundary.length;
new_bytes = (b.remaining() < new_bytes) ? b.remaining() : new_bytes;
b.get(search_window, boundary.length, new_bytes);
} while (new_bytes > 0);
return res;
}
@Override
public CookieHandler getCookies() {
return this.cookies;
}
@Override
public final Map<String, String> getHeaders() {
return this.headers;
}
@Override
public final InputStream getInputStream() {
return this.inputStream;
}
@Override
public final Method getMethod() {
return this.method;
}
/**
* @deprecated use {@link #getParameters()} instead.
*/
@Override
@Deprecated
public final Map<String, String> getParms() {
Map<String, String> result = new HashMap<String, String>();
for (String key : this.parms.keySet()) {
result.put(key, this.parms.get(key).get(0));
}
return result;
}
@Override
public final Map<String, List<String>> getParameters() {
return this.parms;
}
@Override
public String getQueryParameterString() {
return this.queryParameterString;
}
private RandomAccessFile getTmpBucket() {
try {
TempFile tempFile = this.tempFileManager.createTempFile(null);
return new RandomAccessFile(tempFile.getName(), "rw");
} catch (Exception e) {
throw new Error(e); // we won't recover, so throw an error
}
}
@Override
public final String getUri() {
return this.uri;
}
/**
* Deduce body length in bytes. Either from "content-length" header or
* read bytes.
*/
public long getBodySize() {
if (this.headers.containsKey("content-length")) {
return Long.parseLong(this.headers.get("content-length"));
} else if (this.splitbyte < this.rlen) {
return this.rlen - this.splitbyte;
}
return 0;
}
@Override
public void parseBody(Map<String, String> files) throws IOException, ResponseException {
RandomAccessFile randomAccessFile = null;
try {
long size = getBodySize();
ByteArrayOutputStream baos = null;
DataOutput requestDataOutput = null;
// Store the request in memory or a file, depending on size
if (size < MEMORY_STORE_LIMIT) {
baos = new ByteArrayOutputStream();
requestDataOutput = new DataOutputStream(baos);
} else {
randomAccessFile = getTmpBucket();
requestDataOutput = randomAccessFile;
}
// Read all the body and write it to request_data_output
byte[] buf = new byte[REQUEST_BUFFER_LEN];
while (this.rlen >= 0 && size > 0) {
this.rlen = this.inputStream.read(buf, 0, (int) Math.min(size, REQUEST_BUFFER_LEN));
size -= this.rlen;
if (this.rlen > 0) {
requestDataOutput.write(buf, 0, this.rlen);
}
}
ByteBuffer fbuf = null;
if (baos != null) {
fbuf = ByteBuffer.wrap(baos.toByteArray(), 0, baos.size());
} else {
fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length());
randomAccessFile.seek(0);
}
// If the method is POST, there may be parameters
// in data section, too, read it:
if (Method.POST.equals(this.method)) {
ContentType contentType = new ContentType(this.headers.get("content-type"));
if (contentType.isMultipart()) {
String boundary = contentType.getBoundary();
if (boundary == null) {
throw new ResponseException(Response.Status.BAD_REQUEST,
"BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html");
}
decodeMultipartFormData(contentType, fbuf, this.parms, files);
} else {
byte[] postBytes = new byte[fbuf.remaining()];
fbuf.get(postBytes);
String postLine = new String(postBytes, contentType.getEncoding()).trim();
// Handle application/x-www-form-urlencoded
if ("application/x-www-form-urlencoded".equalsIgnoreCase(contentType.getContentType())) {
decodeParms(postLine, this.parms);
} else if (postLine.length() != 0) {
// Special case for raw POST data => create a
// special files entry "postData" with raw content
// data
files.put("postData", postLine);
}
}
} else if (Method.PUT.equals(this.method)) {
files.put("content", saveTmpFile(fbuf, 0, fbuf.limit(), null));
}
} finally {
safeClose(randomAccessFile);
}
}
/**
* Retrieves the content of a sent file and saves it to a temporary
* file. The full path to the saved file is returned.
*/
private String saveTmpFile(ByteBuffer b, int offset, int len, String filename_hint) {
String path = "";
if (len > 0) {
FileOutputStream fileOutputStream = null;
try {
TempFile tempFile = this.tempFileManager.createTempFile(filename_hint);
ByteBuffer src = b.duplicate();
fileOutputStream = new FileOutputStream(tempFile.getName());
FileChannel dest = fileOutputStream.getChannel();
src.position(offset).limit(offset + len);
dest.write(src.slice());
path = tempFile.getName();
} catch (Exception e) { // Catch exception if any
throw new Error(e); // we won't recover, so throw an error
} finally {
safeClose(fileOutputStream);
}
}
return path;
}
@Override
public String getRemoteIpAddress() {
return this.remoteIp;
}
@Override
public String getRemoteHostName() {
return this.remoteHostname;
}
}
/**
* Handles one session, i.e. parses the HTTP request and returns the
* response.
*/
public interface IHTTPSession {
void execute() throws IOException;
CookieHandler getCookies();
Map<String, String> getHeaders();
InputStream getInputStream();
Method getMethod();
/**
* This method will only return the first value for a given parameter.
* You will want to use getParameters if you expect multiple values for
* a given key.
*
* @deprecated use {@link #getParameters()} instead.
*/
@Deprecated
Map<String, String> getParms();
Map<String, List<String>> getParameters();
String getQueryParameterString();
/**
* @return the path part of the URL.
*/
String getUri();
/**
* Adds the files in the request body to the files map.
*
* @param files
* map to modify
*/
void parseBody(Map<String, String> files) throws IOException, ResponseException;
/**
* Get the remote ip address of the requester.
*
* @return the IP address.
*/
String getRemoteIpAddress();
/**
* Get the remote hostname of the requester.
*
* @return the hostname.
*/
String getRemoteHostName();
}
/**
* HTTP Request methods, with the ability to decode a <code>String</code>
* back to its enum value.
*/
public enum Method {
GET,
PUT,
POST,
DELETE,
HEAD,
OPTIONS,
TRACE,
CONNECT,
PATCH,
PROPFIND,
PROPPATCH,
MKCOL,
MOVE,
COPY,
LOCK,
UNLOCK;
static Method lookup(String method) {
if (method == null)
return null;
try {
return valueOf(method);
} catch (IllegalArgumentException e) {
// TODO: Log it?
return null;
}
}
}
/**
* HTTP response. Return one of these from serve().
*/
public static class Response implements Closeable {
public interface IStatus {
String getDescription();
int getRequestStatus();
}
/**
* Some HTTP response status codes
*/
public enum Status implements IStatus {
SWITCH_PROTOCOL(101, "Switching Protocols"),
OK(200, "OK"),
CREATED(201, "Created"),
ACCEPTED(202, "Accepted"),
NO_CONTENT(204, "No Content"),
PARTIAL_CONTENT(206, "Partial Content"),
MULTI_STATUS(207, "Multi-Status"),
REDIRECT(301, "Moved Permanently"),
/**
* Many user agents mishandle 302 in ways that violate the RFC1945
* spec (i.e., redirect a POST to a GET). 303 and 307 were added in
* RFC2616 to address this. You should prefer 303 and 307 unless the
* calling user agent does not support 303 and 307 functionality
*/
@Deprecated
FOUND(302, "Found"),
REDIRECT_SEE_OTHER(303, "See Other"),
NOT_MODIFIED(304, "Not Modified"),
TEMPORARY_REDIRECT(307, "Temporary Redirect"),
BAD_REQUEST(400, "Bad Request"),
UNAUTHORIZED(401, "Unauthorized"),
FORBIDDEN(403, "Forbidden"),
NOT_FOUND(404, "Not Found"),
METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
NOT_ACCEPTABLE(406, "Not Acceptable"),
REQUEST_TIMEOUT(408, "Request Timeout"),
CONFLICT(409, "Conflict"),
GONE(410, "Gone"),
LENGTH_REQUIRED(411, "Length Required"),
PRECONDITION_FAILED(412, "Precondition Failed"),
PAYLOAD_TOO_LARGE(413, "Payload Too Large"),
UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"),
RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"),
EXPECTATION_FAILED(417, "Expectation Failed"),
TOO_MANY_REQUESTS(429, "Too Many Requests"),
INTERNAL_ERROR(500, "Internal Server Error"),
NOT_IMPLEMENTED(501, "Not Implemented"),
SERVICE_UNAVAILABLE(503, "Service Unavailable"),
UNSUPPORTED_HTTP_VERSION(505, "HTTP Version Not Supported");
private final int requestStatus;
private final String description;
Status(int requestStatus, String description) {
this.requestStatus = requestStatus;
this.description = description;
}
public static Status lookup(int requestStatus) {
for (Status status : Status.values()) {
if (status.getRequestStatus() == requestStatus) {
return status;
}
}
return null;
}
@Override
public String getDescription() {
return "" + this.requestStatus + " " + this.description;
}
@Override
public int getRequestStatus() {
return this.requestStatus;
}
}
/**
* Output stream that will automatically send every write to the wrapped
* OutputStream according to chunked transfer:
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1
*/
private static class ChunkedOutputStream extends FilterOutputStream {
public ChunkedOutputStream(OutputStream out) {
super(out);
}
@Override
public void write(int b) throws IOException {
byte[] data = {
(byte) b
};
write(data, 0, 1);
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (len == 0)
return;
out.write(String.format("%x\r\n", len).getBytes());
out.write(b, off, len);
out.write("\r\n".getBytes());
}
public void finish() throws IOException {
out.write("0\r\n\r\n".getBytes());
}
}
/**
* HTTP status code after processing, e.g. "200 OK", Status.OK
*/
private IStatus status;
/**
* MIME type of content, e.g. "text/html"
*/
private String mimeType;
/**
* Data of the response, may be null.
*/
private InputStream data;
private long contentLength;
/**
* Headers for the HTTP response. Use addHeader() to add lines. the
* lowercase map is automatically kept up to date.
*/
@SuppressWarnings("serial")
private final Map<String, String> header = new HashMap<String, String>() {
public String put(String key, String value) {
lowerCaseHeader.put(key == null ? key : key.toLowerCase(), value);
return super.put(key, value);
};
};
/**
* copy of the header map with all the keys lowercase for faster
* searching.
*/
private final Map<String, String> lowerCaseHeader = new HashMap<String, String>();
/**
* The request method that spawned this response.
*/
private Method requestMethod;
/**
* Use chunkedTransfer
*/
private boolean chunkedTransfer;
private boolean encodeAsGzip;
private boolean keepAlive;
/**
* Creates a fixed length response if totalBytes>=0, otherwise chunked.
*/
protected Response(IStatus status, String mimeType, InputStream data, long totalBytes) {
this.status = status;
this.mimeType = mimeType;
if (data == null) {
this.data = new ByteArrayInputStream(new byte[0]);
this.contentLength = 0L;
} else {
this.data = data;
this.contentLength = totalBytes;
}
this.chunkedTransfer = this.contentLength < 0;
keepAlive = true;
}
@Override
public void close() throws IOException {
if (this.data != null) {
this.data.close();
}
}
/**
* Adds given line to the header.
*/
public void addHeader(String name, String value) {
this.header.put(name, value);
}
/**
* Indicate to close the connection after the Response has been sent.
*
* @param close
* {@code true} to hint connection closing, {@code false} to
* let connection be closed by client.
*/
public void closeConnection(boolean close) {
if (close)
this.header.put("connection", "close");
else
this.header.remove("connection");
}
/**
* @return {@code true} if connection is to be closed after this
* Response has been sent.
*/
public boolean isCloseConnection() {
return "close".equals(getHeader("connection"));
}
public InputStream getData() {
return this.data;
}
public String getHeader(String name) {
return this.lowerCaseHeader.get(name.toLowerCase());
}
public String getMimeType() {
return this.mimeType;
}
public Method getRequestMethod() {
return this.requestMethod;
}
public IStatus getStatus() {
return this.status;
}
public void setGzipEncoding(boolean encodeAsGzip) {
this.encodeAsGzip = encodeAsGzip;
}
public void setKeepAlive(boolean useKeepAlive) {
this.keepAlive = useKeepAlive;
}
/**
* Sends given response to the socket.
*/
protected void send(OutputStream outputStream) {
SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
if (this.status == null) {
throw new Error("sendResponse(): Status can't be null.");
}
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, new ContentType(this.mimeType).getEncoding())), false);
pw.append("HTTP/1.1 ").append(this.status.getDescription()).append(" \r\n");
if (this.mimeType != null) {
printHeader(pw, "Content-Type", this.mimeType);
}
if (getHeader("date") == null) {
printHeader(pw, "Date", gmtFrmt.format(new Date()));
}
for (Entry<String, String> entry : this.header.entrySet()) {
printHeader(pw, entry.getKey(), entry.getValue());
}
if (getHeader("connection") == null) {
printHeader(pw, "Connection", (this.keepAlive ? "keep-alive" : "close"));
}
if (getHeader("content-length") != null) {
encodeAsGzip = false;
}
if (encodeAsGzip) {
printHeader(pw, "Content-Encoding", "gzip");
setChunkedTransfer(true);
}
long pending = this.data != null ? this.contentLength : 0;
if (this.requestMethod != Method.HEAD && this.chunkedTransfer) {
printHeader(pw, "Transfer-Encoding", "chunked");
} else if (!encodeAsGzip) {
pending = sendContentLengthHeaderIfNotAlreadyPresent(pw, pending);
}
pw.append("\r\n");
pw.flush();
sendBodyWithCorrectTransferAndEncoding(outputStream, pending);
outputStream.flush();
safeClose(this.data);
} catch (IOException ioe) {
NanoHTTPD.LOG.log(Level.SEVERE, "Could not send response to the client", ioe);
}
}
@SuppressWarnings("static-method")
protected void printHeader(PrintWriter pw, String key, String value) {
pw.append(key).append(": ").append(value).append("\r\n");
}
protected long sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, long defaultSize) {
String contentLengthString = getHeader("content-length");
long size = defaultSize;
if (contentLengthString != null) {
try {
size = Long.parseLong(contentLengthString);
} catch (NumberFormatException ex) {
LOG.severe("content-length was no number " + contentLengthString);
}
}
pw.print("Content-Length: " + size + "\r\n");
return size;
}
private void sendBodyWithCorrectTransferAndEncoding(OutputStream outputStream, long pending) throws IOException {
if (this.requestMethod != Method.HEAD && this.chunkedTransfer) {
ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(outputStream);
sendBodyWithCorrectEncoding(chunkedOutputStream, -1);
chunkedOutputStream.finish();
} else {
sendBodyWithCorrectEncoding(outputStream, pending);
}
}
private void sendBodyWithCorrectEncoding(OutputStream outputStream, long pending) throws IOException {
if (encodeAsGzip) {
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
sendBody(gzipOutputStream, -1);
gzipOutputStream.finish();
} else {
sendBody(outputStream, pending);
}
}
/**
* Sends the body to the specified OutputStream. The pending parameter
* limits the maximum amounts of bytes sent unless it is -1, in which
* case everything is sent.
*
* @param outputStream
* the OutputStream to send data to
* @param pending
* -1 to send everything, otherwise sets a max limit to the
* number of bytes sent
* @throws IOException
* if something goes wrong while sending the data.
*/
private void sendBody(OutputStream outputStream, long pending) throws IOException {
long BUFFER_SIZE = 16 * 1024;
byte[] buff = new byte[(int) BUFFER_SIZE];
boolean sendEverything = pending == -1;
while (pending > 0 || sendEverything) {
long bytesToRead = sendEverything ? BUFFER_SIZE : Math.min(pending, BUFFER_SIZE);
int read = this.data.read(buff, 0, (int) bytesToRead);
if (read <= 0) {
break;
}
outputStream.write(buff, 0, read);
if (!sendEverything) {
pending -= read;
}
}
}
public void setChunkedTransfer(boolean chunkedTransfer) {
this.chunkedTransfer = chunkedTransfer;
}
public void setData(InputStream data) {
this.data = data;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public void setRequestMethod(Method requestMethod) {
this.requestMethod = requestMethod;
}
public void setStatus(IStatus status) {
this.status = status;
}
}
public static final class ResponseException extends Exception {
private static final long serialVersionUID = 6569838532917408380L;
private final Response.Status status;
public ResponseException(Response.Status status, String message) {
super(message);
this.status = status;
}
public ResponseException(Response.Status status, String message, Exception e) {
super(message, e);
this.status = status;
}
public Response.Status getStatus() {
return this.status;
}
}
/**
* The runnable that will be used for the main listening thread.
*/
public class ServerRunnable implements Runnable {
private final int timeout;
private IOException bindException;
private boolean hasBinded = false;
public ServerRunnable(int timeout) {
this.timeout = timeout;
}
@Override
public void run() {
try {
myServerSocket.bind(hostname != null ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));
hasBinded = true;
} catch (IOException e) {
this.bindException = e;
return;
}
do {
try {
final Socket finalAccept = NanoHTTPD.this.myServerSocket.accept();
if (this.timeout > 0) {
finalAccept.setSoTimeout(this.timeout);
}
final InputStream inputStream = finalAccept.getInputStream();
NanoHTTPD.this.asyncRunner.exec(createClientHandler(finalAccept, inputStream));
} catch (IOException e) {
NanoHTTPD.LOG.log(Level.FINE, "Communication with the client broken", e);
}
} while (!NanoHTTPD.this.myServerSocket.isClosed());
}
}
/**
* A temp file.
* <p/>
* <p>
* Temp files are responsible for managing the actual temporary storage and
* cleaning themselves up when no longer needed.
* </p>
*/
public interface TempFile {
public void delete() throws Exception;
public String getName();
public OutputStream open() throws Exception;
}
/**
* Temp file manager.
* <p/>
* <p>
* Temp file managers are created 1-to-1 with incoming requests, to create
* and cleanup temporary files created as a result of handling the request.
* </p>
*/
public interface TempFileManager {
void clear();
public TempFile createTempFile(String filename_hint) throws Exception;
}
/**
* Factory to create temp file managers.
*/
public interface TempFileManagerFactory {
public TempFileManager create();
}
/**
* Factory to create ServerSocketFactories.
*/
public interface ServerSocketFactory {
public ServerSocket create() throws IOException;
}
/**
* Maximum time to wait on Socket.getInputStream().read() (in milliseconds)
* This is required as the Keep-Alive HTTP connections would otherwise block
* the socket reading thread forever (or as long the browser is open).
*/
public static final int SOCKET_READ_TIMEOUT = 5000;
/**
* Common MIME type for dynamic content: plain text
*/
public static final String MIME_PLAINTEXT = "text/plain";
/**
* Common MIME type for dynamic content: html
*/
public static final String MIME_HTML = "text/html";
/**
* Pseudo-Parameter to use to store the actual query string in the
* parameters map for later re-processing.
*/
private static final String QUERY_STRING_PARAMETER = "NanoHttpd.QUERY_STRING";
/**
* logger to log to.
*/
private static final Logger LOG = Logger.getLogger(NanoHTTPD.class.getName());
/**
* Hashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPE
*/
protected static Map<String, String> MIME_TYPES;
public static Map<String, String> mimeTypes() {
if (MIME_TYPES == null) {
MIME_TYPES = new HashMap<String, String>();
loadMimeTypes(MIME_TYPES, "META-INF/nanohttpd/default-mimetypes.properties");
loadMimeTypes(MIME_TYPES, "META-INF/nanohttpd/mimetypes.properties");
if (MIME_TYPES.isEmpty()) {
LOG.log(Level.WARNING, "no mime types found in the classpath! please provide mimetypes.properties");
}
}
return MIME_TYPES;
}
@SuppressWarnings({
"unchecked",
"rawtypes"
})
private static void loadMimeTypes(Map<String, String> result, String resourceName) {
try {
Enumeration<URL> resources = NanoHTTPD.class.getClassLoader().getResources(resourceName);
while (resources.hasMoreElements()) {
URL url = (URL) resources.nextElement();
Properties properties = new Properties();
InputStream stream = null;
try {
stream = url.openStream();
properties.load(stream);
} catch (IOException e) {
LOG.log(Level.SEVERE, "could not load mimetypes from " + url, e);
} finally {
safeClose(stream);
}
result.putAll((Map) properties);
}
} catch (IOException e) {
LOG.log(Level.INFO, "no mime types available at " + resourceName);
}
};
/**
* Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and an
* array of loaded KeyManagers. These objects must properly
* loaded/initialized by the caller.
*/
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException {
SSLServerSocketFactory res = null;
try {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(loadedKeyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
res = ctx.getServerSocketFactory();
} catch (Exception e) {
throw new IOException(e.getMessage());
}
return res;
}
/**
* Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a
* loaded KeyManagerFactory. These objects must properly loaded/initialized
* by the caller.
*/
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException {
try {
return makeSSLSocketFactory(loadedKeyStore, loadedKeyFactory.getKeyManagers());
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/**
* Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
* certificate and passphrase
*/
public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException {
try {
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream keystoreStream = NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath);
if (keystoreStream == null) {
throw new IOException("Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath);
}
keystore.load(keystoreStream, passphrase);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, passphrase);
return makeSSLSocketFactory(keystore, keyManagerFactory);
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/**
* Get MIME type from file name extension, if possible
*
* @param uri
* the string representing a file
* @return the connected mime/type
*/
public static String getMimeTypeForFile(String uri) {
int dot = uri.lastIndexOf('.');
String mime = null;
if (dot >= 0) {
mime = mimeTypes().get(uri.substring(dot + 1).toLowerCase());
}
return mime == null ? "application/octet-stream" : mime;
}
private static final void safeClose(Object closeable) {
try {
if (closeable != null) {
if (closeable instanceof Closeable) {
((Closeable) closeable).close();
} else if (closeable instanceof Socket) {
((Socket) closeable).close();
} else if (closeable instanceof ServerSocket) {
((ServerSocket) closeable).close();
} else {
throw new IllegalArgumentException("Unknown object to close");
}
}
} catch (IOException e) {
NanoHTTPD.LOG.log(Level.SEVERE, "Could not close", e);
}
}
private final String hostname;
private final int myPort;
private volatile ServerSocket myServerSocket;
private ServerSocketFactory serverSocketFactory = new DefaultServerSocketFactory();
private Thread myThread;
/**
* Pluggable strategy for asynchronously executing requests.
*/
protected AsyncRunner asyncRunner;
/**
* Pluggable strategy for creating and cleaning up temporary files.
*/
private TempFileManagerFactory tempFileManagerFactory;
/**
* Constructs an HTTP server on given port.
*/
public NanoHTTPD(int port) {
this(null, port);
}
// -------------------------------------------------------------------------------
// //
//
// Threading Strategy.
//
// -------------------------------------------------------------------------------
// //
/**
* Constructs an HTTP server on given hostname and port.
*/
public NanoHTTPD(String hostname, int port) {
this.hostname = hostname;
this.myPort = port;
setTempFileManagerFactory(new DefaultTempFileManagerFactory());
setAsyncRunner(new DefaultAsyncRunner());
}
/**
* Forcibly closes all connections that are open.
*/
public synchronized void closeAllConnections() {
stop();
}
/**
* create a instance of the client handler, subclasses can return a subclass
* of the ClientHandler.
*
* @param finalAccept
* the socket the cleint is connected to
* @param inputStream
* the input stream
* @return the client handler
*/
protected ClientHandler createClientHandler(final Socket finalAccept, final InputStream inputStream) {
return new ClientHandler(inputStream, finalAccept);
}
/**
* Instantiate the server runnable, can be overwritten by subclasses to
* provide a subclass of the ServerRunnable.
*
* @param timeout
* the socet timeout to use.
* @return the server runnable.
*/
protected ServerRunnable createServerRunnable(final int timeout) {
return new ServerRunnable(timeout);
}
/**
* Decode parameters from a URL, handing the case where a single parameter
* name might have been supplied several times, by return lists of values.
* In general these lists will contain a single element.
*
* @param parms
* original <b>NanoHTTPD</b> parameters values, as passed to the
* <code>serve()</code> method.
* @return a map of <code>String</code> (parameter name) to
* <code>List&lt;String&gt;</code> (a list of the values supplied).
*/
protected static Map<String, List<String>> decodeParameters(Map<String, String> parms) {
return decodeParameters(parms.get(NanoHTTPD.QUERY_STRING_PARAMETER));
}
// -------------------------------------------------------------------------------
// //
/**
* Decode parameters from a URL, handing the case where a single parameter
* name might have been supplied several times, by return lists of values.
* In general these lists will contain a single element.
*
* @param queryString
* a query string pulled from the URL.
* @return a map of <code>String</code> (parameter name) to
* <code>List&lt;String&gt;</code> (a list of the values supplied).
*/
protected static Map<String, List<String>> decodeParameters(String queryString) {
Map<String, List<String>> parms = new HashMap<String, List<String>>();
if (queryString != null) {
StringTokenizer st = new StringTokenizer(queryString, "&");
while (st.hasMoreTokens()) {
String e = st.nextToken();
int sep = e.indexOf('=');
String propertyName = sep >= 0 ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim();
if (!parms.containsKey(propertyName)) {
parms.put(propertyName, new ArrayList<String>());
}
String propertyValue = sep >= 0 ? decodePercent(e.substring(sep + 1)) : null;
if (propertyValue != null) {
parms.get(propertyName).add(propertyValue);
}
}
}
return parms;
}
/**
* Decode percent encoded <code>String</code> values.
*
* @param str
* the percent encoded <code>String</code>
* @return expanded form of the input, for example "foo%20bar" becomes
* "foo bar"
*/
protected static String decodePercent(String str) {
String decoded = null;
try {
decoded = URLDecoder.decode(str, "UTF8");
} catch (UnsupportedEncodingException ignored) {
NanoHTTPD.LOG.log(Level.WARNING, "Encoding not supported, ignored", ignored);
}
return decoded;
}
/**
* @return true if the gzip compression should be used if the client
* accespts it. Default this option is on for text content and off
* for everything. Override this for custom semantics.
*/
@SuppressWarnings("static-method")
protected boolean useGzipWhenAccepted(Response r) {
return r.getMimeType() != null && (r.getMimeType().toLowerCase().contains("text/") || r.getMimeType().toLowerCase().contains("/json"));
}
public final int getListeningPort() {
return this.myServerSocket == null ? -1 : this.myServerSocket.getLocalPort();
}
public final boolean isAlive() {
return wasStarted() && !this.myServerSocket.isClosed() && this.myThread.isAlive();
}
public ServerSocketFactory getServerSocketFactory() {
return serverSocketFactory;
}
public void setServerSocketFactory(ServerSocketFactory serverSocketFactory) {
this.serverSocketFactory = serverSocketFactory;
}
public String getHostname() {
return hostname;
}
public TempFileManagerFactory getTempFileManagerFactory() {
return tempFileManagerFactory;
}
/**
* Call before start() to serve over HTTPS instead of HTTP
*/
public void makeSecure(SSLServerSocketFactory sslServerSocketFactory, String[] sslProtocols) {
this.serverSocketFactory = new SecureServerSocketFactory(sslServerSocketFactory, sslProtocols);
}
/**
* Create a response with unknown length (using HTTP 1.1 chunking).
*/
public static Response newChunkedResponse(Response.IStatus status, String mimeType, InputStream data) {
return new Response(status, mimeType, data, -1);
}
/**
* Create a response with known length.
*/
public static Response newFixedLengthResponse(Response.IStatus status, String mimeType, InputStream data, long totalBytes) {
return new Response(status, mimeType, data, totalBytes);
}
/**
* Create a text response with known length.
*/
public static Response newFixedLengthResponse(Response.IStatus status, String mimeType, String txt) {
ContentType contentType = new ContentType(mimeType);
if (txt == null) {
return newFixedLengthResponse(status, mimeType, new ByteArrayInputStream(new byte[0]), 0);
} else {
byte[] bytes;
try {
CharsetEncoder newEncoder = Charset.forName(contentType.getEncoding()).newEncoder();
if (!newEncoder.canEncode(txt)) {
contentType = contentType.tryUTF8();
}
bytes = txt.getBytes(contentType.getEncoding());
} catch (UnsupportedEncodingException e) {
NanoHTTPD.LOG.log(Level.SEVERE, "encoding problem, responding nothing", e);
bytes = new byte[0];
}
return newFixedLengthResponse(status, contentType.getContentTypeHeader(), new ByteArrayInputStream(bytes), bytes.length);
}
}
/**
* Create a text response with known length.
*/
public static Response newFixedLengthResponse(String msg) {
return newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, msg);
}
/**
* Override this to customize the server.
* <p/>
* <p/>
* (By default, this returns a 404 "Not Found" plain text error response.)
*
* @param session
* The HTTP session
* @return HTTP response, see class Response for details
*/
public Response serve(IHTTPSession session) {
Map<String, String> files = new HashMap<String, String>();
Method method = session.getMethod();
if (Method.PUT.equals(method) || Method.POST.equals(method)) {
try {
session.parseBody(files);
} catch (IOException ioe) {
return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
} catch (ResponseException re) {
return newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage());
}
}
Map<String, String> parms = session.getParms();
parms.put(NanoHTTPD.QUERY_STRING_PARAMETER, session.getQueryParameterString());
return serve(session.getUri(), method, session.getHeaders(), parms, files);
}
/**
* Override this to customize the server.
* <p/>
* <p/>
* (By default, this returns a 404 "Not Found" plain text error response.)
*
* @param uri
* Percent-decoded URI without parameters, for example
* "/index.cgi"
* @param method
* "GET", "POST" etc.
* @param parms
* Parsed, percent decoded parameters from URI and, in case of
* POST, data.
* @param headers
* Header entries, percent decoded
* @return HTTP response, see class Response for details
*/
@Deprecated
public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) {
return newFixedLengthResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Not Found");
}
/**
* Pluggable strategy for asynchronously executing requests.
*
* @param asyncRunner
* new strategy for handling threads.
*/
public void setAsyncRunner(AsyncRunner asyncRunner) {
this.asyncRunner = asyncRunner;
}
/**
* Pluggable strategy for creating and cleaning up temporary files.
*
* @param tempFileManagerFactory
* new strategy for handling temp files.
*/
public void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory) {
this.tempFileManagerFactory = tempFileManagerFactory;
}
/**
* Start the server.
*
* @throws IOException
* if the socket is in use.
*/
public void start() throws IOException {
start(NanoHTTPD.SOCKET_READ_TIMEOUT);
}
/**
* Starts the server (in setDaemon(true) mode).
*/
public void start(final int timeout) throws IOException {
start(timeout, true);
}
/**
* Start the server.
*
* @param timeout
* timeout to use for socket connections.
* @param daemon
* start the thread daemon or not.
* @throws IOException
* if the socket is in use.
*/
public void start(final int timeout, boolean daemon) throws IOException {
this.myServerSocket = this.getServerSocketFactory().create();
this.myServerSocket.setReuseAddress(true);
ServerRunnable serverRunnable = createServerRunnable(timeout);
this.myThread = new Thread(serverRunnable);
this.myThread.setDaemon(daemon);
this.myThread.setName("NanoHttpd Main Listener");
this.myThread.start();
while (!serverRunnable.hasBinded && serverRunnable.bindException == null) {
try {
Thread.sleep(10L);
} catch (Throwable e) {
// on android this may not be allowed, that's why we
// catch throwable the wait should be very short because we are
// just waiting for the bind of the socket
}
}
if (serverRunnable.bindException != null) {
throw serverRunnable.bindException;
}
}
/**
* Stop the server.
*/
public void stop() {
try {
safeClose(this.myServerSocket);
this.asyncRunner.closeAll();
if (this.myThread != null) {
this.myThread.join();
}
} catch (Exception e) {
NanoHTTPD.LOG.log(Level.SEVERE, "Could not stop all connections", e);
}
}
public final boolean wasStarted() {
return this.myServerSocket != null && this.myThread != null;
}
}
package com.fear1ess.reyunaditool.server;
/*
* #%L
* NanoHttpd-Websocket
* %%
* Copyright (C) 2012 - 2015 nanohttpd
* %%
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the nanohttpd nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class NanoWSD extends NanoHTTPD {
public static enum State {
UNCONNECTED,
CONNECTING,
OPEN,
CLOSING,
CLOSED
}
public static abstract class WebSocket {
private final InputStream in;
private OutputStream out;
private WebSocketFrame.OpCode continuousOpCode = null;
private final List<WebSocketFrame> continuousFrames = new LinkedList<WebSocketFrame>();
private State state = State.UNCONNECTED;
private final NanoHTTPD.IHTTPSession handshakeRequest;
private final NanoHTTPD.Response handshakeResponse = new NanoHTTPD.Response(NanoHTTPD.Response.Status.SWITCH_PROTOCOL, null, (InputStream) null, 0) {
@Override
protected void send(OutputStream out) {
WebSocket.this.out = out;
WebSocket.this.state = State.CONNECTING;
super.send(out);
WebSocket.this.state = State.OPEN;
WebSocket.this.onOpen();
readWebsocket();
}
};
public WebSocket(NanoHTTPD.IHTTPSession handshakeRequest) {
this.handshakeRequest = handshakeRequest;
this.in = handshakeRequest.getInputStream();
this.handshakeResponse.addHeader(NanoWSD.HEADER_UPGRADE, NanoWSD.HEADER_UPGRADE_VALUE);
this.handshakeResponse.addHeader(NanoWSD.HEADER_CONNECTION, NanoWSD.HEADER_CONNECTION_VALUE);
}
public boolean isOpen() {
return state == State.OPEN;
}
protected abstract void onOpen();
protected abstract void onClose(WebSocketFrame.CloseCode code, String reason, boolean initiatedByRemote);
protected abstract void onMessage(WebSocketFrame message);
protected abstract void onPong(WebSocketFrame pong);
protected abstract void onException(IOException exception);
/**
* Debug method. <b>Do not Override unless for debug purposes!</b>
*
* @param frame
* The received WebSocket Frame.
*/
protected void debugFrameReceived(WebSocketFrame frame) {
}
/**
* Debug method. <b>Do not Override unless for debug purposes!</b><br>
* This method is called before actually sending the frame.
*
* @param frame
* The sent WebSocket Frame.
*/
protected void debugFrameSent(WebSocketFrame frame) {
}
public void close(WebSocketFrame.CloseCode code, String reason, boolean initiatedByRemote) throws IOException {
State oldState = this.state;
this.state = State.CLOSING;
if (oldState == State.OPEN) {
sendFrame(new WebSocketFrame.CloseFrame(code, reason));
} else {
doClose(code, reason, initiatedByRemote);
}
}
private void doClose(WebSocketFrame.CloseCode code, String reason, boolean initiatedByRemote) {
if (this.state == State.CLOSED) {
return;
}
if (this.in != null) {
try {
this.in.close();
} catch (IOException e) {
NanoWSD.LOG.log(Level.FINE, "close failed", e);
}
}
if (this.out != null) {
try {
this.out.close();
} catch (IOException e) {
NanoWSD.LOG.log(Level.FINE, "close failed", e);
}
}
this.state = State.CLOSED;
onClose(code, reason, initiatedByRemote);
}
// --------------------------------IO--------------------------------------
public NanoHTTPD.IHTTPSession getHandshakeRequest() {
return this.handshakeRequest;
}
public NanoHTTPD.Response getHandshakeResponse() {
return this.handshakeResponse;
}
private void handleCloseFrame(WebSocketFrame frame) throws IOException {
WebSocketFrame.CloseCode code = WebSocketFrame.CloseCode.NormalClosure;
String reason = "";
if (frame instanceof WebSocketFrame.CloseFrame) {
code = ((WebSocketFrame.CloseFrame) frame).getCloseCode();
reason = ((WebSocketFrame.CloseFrame) frame).getCloseReason();
}
if (this.state == State.CLOSING) {
// Answer for my requested close
doClose(code, reason, false);
} else {
close(code, reason, true);
}
}
private void handleFrameFragment(WebSocketFrame frame) throws IOException {
if (frame.getOpCode() != WebSocketFrame.OpCode.Continuation) {
// First
if (this.continuousOpCode != null) {
throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Previous continuous frame sequence not completed.");
}
this.continuousOpCode = frame.getOpCode();
this.continuousFrames.clear();
this.continuousFrames.add(frame);
} else if (frame.isFin()) {
// Last
if (this.continuousOpCode == null) {
throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Continuous frame sequence was not started.");
}
this.continuousFrames.add(frame);
onMessage(new WebSocketFrame(this.continuousOpCode, this.continuousFrames));
this.continuousOpCode = null;
this.continuousFrames.clear();
} else if (this.continuousOpCode == null) {
// Unexpected
throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Continuous frame sequence was not started.");
} else {
// Intermediate
this.continuousFrames.add(frame);
}
}
private void handleWebsocketFrame(WebSocketFrame frame) throws IOException {
debugFrameReceived(frame);
if (frame.getOpCode() == WebSocketFrame.OpCode.Close) {
handleCloseFrame(frame);
} else if (frame.getOpCode() == WebSocketFrame.OpCode.Ping) {
sendFrame(new WebSocketFrame(WebSocketFrame.OpCode.Pong, true, frame.getBinaryPayload()));
} else if (frame.getOpCode() == WebSocketFrame.OpCode.Pong) {
onPong(frame);
} else if (!frame.isFin() || frame.getOpCode() == WebSocketFrame.OpCode.Continuation) {
handleFrameFragment(frame);
} else if (this.continuousOpCode != null) {
throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Continuous frame sequence not completed.");
} else if (frame.getOpCode() == WebSocketFrame.OpCode.Text || frame.getOpCode() == WebSocketFrame.OpCode.Binary) {
onMessage(frame);
} else {
throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Non control or continuous frame expected.");
}
}
// --------------------------------Close-----------------------------------
public void ping(byte[] payload) throws IOException {
sendFrame(new WebSocketFrame(WebSocketFrame.OpCode.Ping, true, payload));
}
// --------------------------------Public
// Facade---------------------------
private void readWebsocket() {
try {
while (this.state == State.OPEN) {
handleWebsocketFrame(WebSocketFrame.read(this.in));
}
} catch (CharacterCodingException e) {
onException(e);
doClose(WebSocketFrame.CloseCode.InvalidFramePayloadData, e.toString(), false);
} catch (IOException e) {
onException(e);
if (e instanceof WebSocketException) {
doClose(((WebSocketException) e).getCode(), ((WebSocketException) e).getReason(), false);
}
} finally {
doClose(WebSocketFrame.CloseCode.InternalServerError, "Handler terminated without closing the connection.", false);
}
}
public void send(byte[] payload) throws IOException {
sendFrame(new WebSocketFrame(WebSocketFrame.OpCode.Binary, true, payload));
}
public void send(String payload) throws IOException {
sendFrame(new WebSocketFrame(WebSocketFrame.OpCode.Text, true, payload));
}
public synchronized void sendFrame(WebSocketFrame frame) throws IOException {
debugFrameSent(frame);
frame.write(this.out);
}
}
public static class WebSocketException extends IOException {
private static final long serialVersionUID = 1L;
private final WebSocketFrame.CloseCode code;
private final String reason;
public WebSocketException(WebSocketFrame.CloseCode code, String reason) {
this(code, reason, null);
}
public WebSocketException(WebSocketFrame.CloseCode code, String reason, Exception cause) {
super(code + ": " + reason, cause);
this.code = code;
this.reason = reason;
}
public WebSocketException(Exception cause) {
this(WebSocketFrame.CloseCode.InternalServerError, cause.toString(), cause);
}
public WebSocketFrame.CloseCode getCode() {
return this.code;
}
public String getReason() {
return this.reason;
}
}
public static class WebSocketFrame {
public static enum CloseCode {
NormalClosure(1000),
GoingAway(1001),
ProtocolError(1002),
UnsupportedData(1003),
NoStatusRcvd(1005),
AbnormalClosure(1006),
InvalidFramePayloadData(1007),
PolicyViolation(1008),
MessageTooBig(1009),
MandatoryExt(1010),
InternalServerError(1011),
TLSHandshake(1015);
public static CloseCode find(int value) {
for (CloseCode code : values()) {
if (code.getValue() == value) {
return code;
}
}
return null;
}
private final int code;
private CloseCode(int code) {
this.code = code;
}
public int getValue() {
return this.code;
}
}
public static class CloseFrame extends WebSocketFrame {
private static byte[] generatePayload(CloseCode code, String closeReason) throws CharacterCodingException {
if (code != null) {
byte[] reasonBytes = text2Binary(closeReason);
byte[] payload = new byte[reasonBytes.length + 2];
payload[0] = (byte) (code.getValue() >> 8 & 0xFF);
payload[1] = (byte) (code.getValue() & 0xFF);
System.arraycopy(reasonBytes, 0, payload, 2, reasonBytes.length);
return payload;
} else {
return new byte[0];
}
}
private CloseCode _closeCode;
private String _closeReason;
public CloseFrame(CloseCode code, String closeReason) throws CharacterCodingException {
super(OpCode.Close, true, generatePayload(code, closeReason));
}
private CloseFrame(WebSocketFrame wrap) throws CharacterCodingException {
super(wrap);
assert wrap.getOpCode() == OpCode.Close;
if (wrap.getBinaryPayload().length >= 2) {
this._closeCode = CloseCode.find((wrap.getBinaryPayload()[0] & 0xFF) << 8 | wrap.getBinaryPayload()[1] & 0xFF);
this._closeReason = binary2Text(getBinaryPayload(), 2, getBinaryPayload().length - 2);
}
}
public CloseCode getCloseCode() {
return this._closeCode;
}
public String getCloseReason() {
return this._closeReason;
}
}
public static enum OpCode {
Continuation(0),
Text(1),
Binary(2),
Close(8),
Ping(9),
Pong(10);
public static OpCode find(byte value) {
for (OpCode opcode : values()) {
if (opcode.getValue() == value) {
return opcode;
}
}
return null;
}
private final byte code;
private OpCode(int code) {
this.code = (byte) code;
}
public byte getValue() {
return this.code;
}
public boolean isControlFrame() {
return this == Close || this == Ping || this == Pong;
}
}
public static final Charset TEXT_CHARSET = Charset.forName("UTF-8");
public static String binary2Text(byte[] payload) throws CharacterCodingException {
return new String(payload, WebSocketFrame.TEXT_CHARSET);
}
public static String binary2Text(byte[] payload, int offset, int length) throws CharacterCodingException {
return new String(payload, offset, length, WebSocketFrame.TEXT_CHARSET);
}
private static int checkedRead(int read) throws IOException {
if (read < 0) {
throw new EOFException();
}
return read;
}
public static WebSocketFrame read(InputStream in) throws IOException {
byte head = (byte) checkedRead(in.read());
boolean fin = (head & 0x80) != 0;
OpCode opCode = OpCode.find((byte) (head & 0x0F));
if ((head & 0x70) != 0) {
throw new WebSocketException(CloseCode.ProtocolError, "The reserved bits (" + Integer.toBinaryString(head & 0x70) + ") must be 0.");
}
if (opCode == null) {
throw new WebSocketException(CloseCode.ProtocolError, "Received frame with reserved/unknown opcode " + (head & 0x0F) + ".");
} else if (opCode.isControlFrame() && !fin) {
throw new WebSocketException(CloseCode.ProtocolError, "Fragmented control frame.");
}
WebSocketFrame frame = new WebSocketFrame(opCode, fin);
frame.readPayloadInfo(in);
frame.readPayload(in);
if (frame.getOpCode() == OpCode.Close) {
return new CloseFrame(frame);
} else {
return frame;
}
}
public static byte[] text2Binary(String payload) throws CharacterCodingException {
return payload.getBytes(WebSocketFrame.TEXT_CHARSET);
}
private OpCode opCode;
private boolean fin;
private byte[] maskingKey;
private byte[] payload;
// --------------------------------GETTERS---------------------------------
private transient int _payloadLength;
private transient String _payloadString;
private WebSocketFrame(OpCode opCode, boolean fin) {
setOpCode(opCode);
setFin(fin);
}
public WebSocketFrame(OpCode opCode, boolean fin, byte[] payload) {
this(opCode, fin, payload, null);
}
public WebSocketFrame(OpCode opCode, boolean fin, byte[] payload, byte[] maskingKey) {
this(opCode, fin);
setMaskingKey(maskingKey);
setBinaryPayload(payload);
}
public WebSocketFrame(OpCode opCode, boolean fin, String payload) throws CharacterCodingException {
this(opCode, fin, payload, null);
}
public WebSocketFrame(OpCode opCode, boolean fin, String payload, byte[] maskingKey) throws CharacterCodingException {
this(opCode, fin);
setMaskingKey(maskingKey);
setTextPayload(payload);
}
public WebSocketFrame(OpCode opCode, List<WebSocketFrame> fragments) throws WebSocketException {
setOpCode(opCode);
setFin(true);
long _payloadLength = 0;
for (WebSocketFrame inter : fragments) {
_payloadLength += inter.getBinaryPayload().length;
}
if (_payloadLength < 0 || _payloadLength > Integer.MAX_VALUE) {
throw new WebSocketException(CloseCode.MessageTooBig, "Max frame length has been exceeded.");
}
this._payloadLength = (int) _payloadLength;
byte[] payload = new byte[this._payloadLength];
int offset = 0;
for (WebSocketFrame inter : fragments) {
System.arraycopy(inter.getBinaryPayload(), 0, payload, offset, inter.getBinaryPayload().length);
offset += inter.getBinaryPayload().length;
}
setBinaryPayload(payload);
}
public WebSocketFrame(WebSocketFrame clone) {
setOpCode(clone.getOpCode());
setFin(clone.isFin());
setBinaryPayload(clone.getBinaryPayload());
setMaskingKey(clone.getMaskingKey());
}
public byte[] getBinaryPayload() {
return this.payload;
}
public byte[] getMaskingKey() {
return this.maskingKey;
}
public OpCode getOpCode() {
return this.opCode;
}
// --------------------------------SERIALIZATION---------------------------
public String getTextPayload() {
if (this._payloadString == null) {
try {
this._payloadString = binary2Text(getBinaryPayload());
} catch (CharacterCodingException e) {
throw new RuntimeException("Undetected CharacterCodingException", e);
}
}
return this._payloadString;
}
public boolean isFin() {
return this.fin;
}
public boolean isMasked() {
return this.maskingKey != null && this.maskingKey.length == 4;
}
private String payloadToString() {
if (this.payload == null) {
return "null";
} else {
final StringBuilder sb = new StringBuilder();
sb.append('[').append(this.payload.length).append("b] ");
if (getOpCode() == OpCode.Text) {
String text = getTextPayload();
if (text.length() > 100) {
sb.append(text.substring(0, 100)).append("...");
} else {
sb.append(text);
}
} else {
sb.append("0x");
for (int i = 0; i < Math.min(this.payload.length, 50); ++i) {
sb.append(Integer.toHexString(this.payload[i] & 0xFF));
}
if (this.payload.length > 50) {
sb.append("...");
}
}
return sb.toString();
}
}
private void readPayload(InputStream in) throws IOException {
this.payload = new byte[this._payloadLength];
int read = 0;
while (read < this._payloadLength) {
read += checkedRead(in.read(this.payload, read, this._payloadLength - read));
}
if (isMasked()) {
for (int i = 0; i < this.payload.length; i++) {
this.payload[i] ^= this.maskingKey[i % 4];
}
}
// Test for Unicode errors
if (getOpCode() == OpCode.Text) {
this._payloadString = binary2Text(getBinaryPayload());
}
}
// --------------------------------ENCODING--------------------------------
private void readPayloadInfo(InputStream in) throws IOException {
byte b = (byte) checkedRead(in.read());
boolean masked = (b & 0x80) != 0;
this._payloadLength = (byte) (0x7F & b);
if (this._payloadLength == 126) {
// checkedRead must return int for this to work
this._payloadLength = (checkedRead(in.read()) << 8 | checkedRead(in.read())) & 0xFFFF;
if (this._payloadLength < 126) {
throw new WebSocketException(CloseCode.ProtocolError, "Invalid data frame 2byte length. (not using minimal length encoding)");
}
} else if (this._payloadLength == 127) {
long _payloadLength =
(long) checkedRead(in.read()) << 56 | (long) checkedRead(in.read()) << 48 | (long) checkedRead(in.read()) << 40 | (long) checkedRead(in.read()) << 32
| checkedRead(in.read()) << 24 | checkedRead(in.read()) << 16 | checkedRead(in.read()) << 8 | checkedRead(in.read());
if (_payloadLength < 65536) {
throw new WebSocketException(CloseCode.ProtocolError, "Invalid data frame 4byte length. (not using minimal length encoding)");
}
if (_payloadLength < 0 || _payloadLength > Integer.MAX_VALUE) {
throw new WebSocketException(CloseCode.MessageTooBig, "Max frame length has been exceeded.");
}
this._payloadLength = (int) _payloadLength;
}
if (this.opCode.isControlFrame()) {
if (this._payloadLength > 125) {
throw new WebSocketException(CloseCode.ProtocolError, "Control frame with payload length > 125 bytes.");
}
if (this.opCode == OpCode.Close && this._payloadLength == 1) {
throw new WebSocketException(CloseCode.ProtocolError, "Received close frame with payload len 1.");
}
}
if (masked) {
this.maskingKey = new byte[4];
int read = 0;
while (read < this.maskingKey.length) {
read += checkedRead(in.read(this.maskingKey, read, this.maskingKey.length - read));
}
}
}
public void setBinaryPayload(byte[] payload) {
this.payload = payload;
this._payloadLength = payload.length;
this._payloadString = null;
}
public void setFin(boolean fin) {
this.fin = fin;
}
public void setMaskingKey(byte[] maskingKey) {
if (maskingKey != null && maskingKey.length != 4) {
throw new IllegalArgumentException("MaskingKey " + Arrays.toString(maskingKey) + " hasn't length 4");
}
this.maskingKey = maskingKey;
}
public void setOpCode(OpCode opcode) {
this.opCode = opcode;
}
public void setTextPayload(String payload) throws CharacterCodingException {
this.payload = text2Binary(payload);
this._payloadLength = payload.length();
this._payloadString = payload;
}
// --------------------------------CONSTANTS-------------------------------
public void setUnmasked() {
setMaskingKey(null);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("WS[");
sb.append(getOpCode());
sb.append(", ").append(isFin() ? "fin" : "inter");
sb.append(", ").append(isMasked() ? "masked" : "unmasked");
sb.append(", ").append(payloadToString());
sb.append(']');
return sb.toString();
}
// ------------------------------------------------------------------------
public void write(OutputStream out) throws IOException {
byte header = 0;
if (this.fin) {
header |= 0x80;
}
header |= this.opCode.getValue() & 0x0F;
out.write(header);
this._payloadLength = getBinaryPayload().length;
if (this._payloadLength <= 125) {
out.write(isMasked() ? 0x80 | (byte) this._payloadLength : (byte) this._payloadLength);
} else if (this._payloadLength <= 0xFFFF) {
out.write(isMasked() ? 0xFE : 126);
out.write(this._payloadLength >>> 8);
out.write(this._payloadLength);
} else {
out.write(isMasked() ? 0xFF : 127);
out.write(this._payloadLength >>> 56 & 0); // integer only
// contains
// 31 bit
out.write(this._payloadLength >>> 48 & 0);
out.write(this._payloadLength >>> 40 & 0);
out.write(this._payloadLength >>> 32 & 0);
out.write(this._payloadLength >>> 24);
out.write(this._payloadLength >>> 16);
out.write(this._payloadLength >>> 8);
out.write(this._payloadLength);
}
if (isMasked()) {
out.write(this.maskingKey);
for (int i = 0; i < this._payloadLength; i++) {
out.write(getBinaryPayload()[i] ^ this.maskingKey[i % 4]);
}
} else {
out.write(getBinaryPayload());
}
out.flush();
}
}
/**
* logger to log to.
*/
private static final Logger LOG = Logger.getLogger(NanoWSD.class.getName());
public static final String HEADER_UPGRADE = "upgrade";
public static final String HEADER_UPGRADE_VALUE = "websocket";
public static final String HEADER_CONNECTION = "connection";
public static final String HEADER_CONNECTION_VALUE = "Upgrade";
public static final String HEADER_WEBSOCKET_VERSION = "sec-websocket-version";
public static final String HEADER_WEBSOCKET_VERSION_VALUE = "13";
public static final String HEADER_WEBSOCKET_KEY = "sec-websocket-key";
public static final String HEADER_WEBSOCKET_ACCEPT = "sec-websocket-accept";
public static final String HEADER_WEBSOCKET_PROTOCOL = "sec-websocket-protocol";
private final static String WEBSOCKET_KEY_MAGIC = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private final static char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
/**
* Translates the specified byte array into Base64 string.
* <p>
* Android has android.util.Base64, sun has sun.misc.Base64Encoder, Java 8
* hast java.util.Base64, I have this from stackoverflow:
* http://stackoverflow.com/a/4265472
* </p>
*
* @param buf
* the byte array (not null)
* @return the translated Base64 string (not null)
*/
private static String encodeBase64(byte[] buf) {
int size = buf.length;
char[] ar = new char[(size + 2) / 3 * 4];
int a = 0;
int i = 0;
while (i < size) {
byte b0 = buf[i++];
byte b1 = i < size ? buf[i++] : 0;
byte b2 = i < size ? buf[i++] : 0;
int mask = 0x3F;
ar[a++] = NanoWSD.ALPHABET[b0 >> 2 & mask];
ar[a++] = NanoWSD.ALPHABET[(b0 << 4 | (b1 & 0xFF) >> 4) & mask];
ar[a++] = NanoWSD.ALPHABET[(b1 << 2 | (b2 & 0xFF) >> 6) & mask];
ar[a++] = NanoWSD.ALPHABET[b2 & mask];
}
switch (size % 3) {
case 1:
ar[--a] = '=';
case 2:
ar[--a] = '=';
}
return new String(ar);
}
public static String makeAcceptKey(String key) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
String text = key + NanoWSD.WEBSOCKET_KEY_MAGIC;
md.update(text.getBytes(), 0, text.length());
byte[] sha1hash = md.digest();
return encodeBase64(sha1hash);
}
public NanoWSD(int port) {
super(port);
}
public NanoWSD(String hostname, int port) {
super(hostname, port);
}
private boolean isWebSocketConnectionHeader(Map<String, String> headers) {
String connection = headers.get(NanoWSD.HEADER_CONNECTION);
return connection != null && connection.toLowerCase().contains(NanoWSD.HEADER_CONNECTION_VALUE.toLowerCase());
}
protected boolean isWebsocketRequested(IHTTPSession session) {
Map<String, String> headers = session.getHeaders();
String upgrade = headers.get(NanoWSD.HEADER_UPGRADE);
boolean isCorrectConnection = isWebSocketConnectionHeader(headers);
boolean isUpgrade = NanoWSD.HEADER_UPGRADE_VALUE.equalsIgnoreCase(upgrade);
return isUpgrade && isCorrectConnection;
}
// --------------------------------Listener--------------------------------
protected abstract WebSocket openWebSocket(IHTTPSession handshake);
@Override
public Response serve(final IHTTPSession session) {
Map<String, String> headers = session.getHeaders();
if (isWebsocketRequested(session)) {
if (!NanoWSD.HEADER_WEBSOCKET_VERSION_VALUE.equalsIgnoreCase(headers.get(NanoWSD.HEADER_WEBSOCKET_VERSION))) {
return newFixedLengthResponse(Response.Status.BAD_REQUEST, NanoHTTPD.MIME_PLAINTEXT,
"Invalid Websocket-Version " + headers.get(NanoWSD.HEADER_WEBSOCKET_VERSION));
}
if (!headers.containsKey(NanoWSD.HEADER_WEBSOCKET_KEY)) {
return newFixedLengthResponse(Response.Status.BAD_REQUEST, NanoHTTPD.MIME_PLAINTEXT, "Missing Websocket-Key");
}
WebSocket webSocket = openWebSocket(session);
Response handshakeResponse = webSocket.getHandshakeResponse();
try {
handshakeResponse.addHeader(NanoWSD.HEADER_WEBSOCKET_ACCEPT, makeAcceptKey(headers.get(NanoWSD.HEADER_WEBSOCKET_KEY)));
} catch (NoSuchAlgorithmException e) {
return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT,
"The SHA-1 Algorithm required for websockets is not available on the server.");
}
if (headers.containsKey(NanoWSD.HEADER_WEBSOCKET_PROTOCOL)) {
handshakeResponse.addHeader(NanoWSD.HEADER_WEBSOCKET_PROTOCOL, headers.get(NanoWSD.HEADER_WEBSOCKET_PROTOCOL).split(",")[0]);
}
return handshakeResponse;
} else {
return serveHttp(session);
}
}
protected Response serveHttp(final IHTTPSession session) {
return super.serve(session);
}
/**
* not all websockets implementations accept gzip compression.
*/
@Override
protected boolean useGzipWhenAccepted(Response r) {
return false;
}
}
package com.fear1ess.reyunaditool.state;
public class AppState {
public final static int APP_DOWNLOADING = 1;
public final static int APP_DOWNLOADED_AND_PARPARE_TO_INSTALL = 2;
public final static int APP_INSTALLING = 3;
public final static int APP_INSTALLED_AND_OPEN = 4;
public final static int APP_REMOVING = 5;
public final static int APP_REMOVED = 6;
public final static int APP_ADSDK_CHECKING = 7;
public final static int APP_INSTALL_FAILED = 8;
}
package com.fear1ess.reyunaditool.thread;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import com.fear1ess.reyunaditool.AppInfo;
import com.fear1ess.reyunaditool.DoCommandService;
import com.fear1ess.reyunaditool.ExecuteCmdUtils;
import com.fear1ess.reyunaditool.NetWorkUtils;
import com.fear1ess.reyunaditool.state.AppState;
import com.fear1ess.reyunaditool.utils.PushMsgUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
public class DownloadThread extends Thread {
private Handler mainUiHandler;
private Context appContext;
private DoCommandService mService;
private volatile boolean needRunning = true;
private int MAX_APPHANDLE_SIZE = 2;
public LinkedBlockingQueue<AppInfo> mAppInfoQueue = new LinkedBlockingQueue<>(MAX_APPHANDLE_SIZE);
public static String downloadDir = "/sdcard/reyundownload";
public static String TAG = "reyunaditool_log";
// public static String downloadAppUrlStr = "http://adfly-api.adinsights-global.com/get_app_res/?count=1&ua=and";
public static String downloadAppUrlStr = "http://101.32.45.4/get_app_res/?count=1&ua=android";
static{
File fi = new File(downloadDir);
if(!fi.exists()) fi.mkdirs();
}
public DownloadThread(Context cxt, Handler handler, DoCommandService doCommandService) {
appContext = cxt;
mainUiHandler = handler;
mService = doCommandService;
}
public String downloadApp(String downloadUrl, String downloadPath) {
Log.d(TAG, "downloadApp...");
NetWorkUtils.Response res = NetWorkUtils.download(downloadUrl,null,null,downloadPath);
if(res == null) return null;
return res.resFileName;
}
public void renameFile(String srcPath,String reNamePath){
File fi = new File(srcPath);
File fi2 = new File(reNamePath);
fi.renameTo(fi2);
}
public void exit() {
needRunning = false;
}
public void handleLocalApp(){
File fi = new File(downloadDir);
String[] fileNames = fi.list();
if(fileNames == null) return;
for(String fileName : fileNames){
String packageName = fileName.replace(".apk","");
String downloadPath = downloadDir + "/" + fileName;
try {
if(packageName.startsWith("rycache_")){
Log.d(TAG, "find app cache,delete it...");
ExecuteCmdUtils.deletePkg(downloadPath);
continue;
}
mAppInfoQueue.put(new AppInfo(packageName, downloadPath));
String msg = PushMsgUtils.createPushMsg(packageName, null, null,
AppState.APP_DOWNLOADED_AND_PARPARE_TO_INSTALL);
mService.sendMsgToClient(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void downloadAppLoop(){
while(needRunning){
try {
Thread.sleep(5*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
setNetWorkCallback();
String ts = String.valueOf(System.currentTimeMillis());
String downloadPath = downloadDir + "/" + "rycache_" + ts + ".apk";
String pkgName = downloadApp(downloadAppUrlStr, downloadPath);
if(pkgName == null) {
ExecuteCmdUtils.deletePkg(downloadPath);
try {
sleep(5*60*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
}
String newPath = downloadDir + "/" + pkgName + ".apk";
renameFile(downloadPath, newPath);
uploadDownLoadSuccessData(pkgName);
try {
mAppInfoQueue.put(new AppInfo(pkgName, newPath));
String msg = PushMsgUtils.createPushMsg(pkgName, null, null,
AppState.APP_DOWNLOADED_AND_PARPARE_TO_INSTALL);
mService.sendMsgToClient(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void uploadDownLoadSuccessData(String pkgName) {
Log.d(TAG, "start upload download success data...");
ExecutorService es = Executors.newSingleThreadExecutor();
JSONObject jo = new JSONObject();
try {
jo.put("app_id", pkgName);
jo.put("download_success", 1);
} catch (JSONException e) {
e.printStackTrace();
}
es.execute(new UploadAdsDataProceduce(jo.toString()));
es.shutdown();
}
public void setNetWorkCallback() {
NetWorkUtils.setNetWorkCallback(new NetWorkUtils.NetWorkCallback() {
@Override
public void onDownloadPkgNameGetSuccess(String name) {
String msg = PushMsgUtils.createPushMsg(name, null, null, 0,
AppState.APP_DOWNLOADING);
mService.sendMsgToClient(msg);
}
@Override
public void onDownloadPkgNameGetfailed() {
}
@Override
public void onDownloadBytesUpdate(String name, int bytesDownloaded) {
String msg = PushMsgUtils.createPushMsg(name, null, null, bytesDownloaded,
AppState.APP_DOWNLOADING);
mService.sendMsgToClient(msg);
}
});
}
@Override
public void run() {
//handle local app
handleLocalApp();
//download app loop...
downloadAppLoop();
}
}
package com.fear1ess.reyunaditool.thread;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import androidx.annotation.NonNull;
import com.fear1ess.reyunaditool.AdiToolApp;
import com.fear1ess.reyunaditool.AppInfo;
import com.fear1ess.reyunaditool.DoCommandService;
import com.fear1ess.reyunaditool.ExecuteCmdUtils;
import com.fear1ess.reyunaditool.NetWorkUtils;
import com.fear1ess.reyunaditool.cmd.OperateCmd;
import com.fear1ess.reyunaditool.state.AppState;
import com.fear1ess.reyunaditool.utils.PushMsgUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class InstallAndStartAppThread extends Thread {
public static String TAG = "reyunaditool_log";
private String mPkgName;
private String mDownloadPath;
private Handler mUiHandler;
private DoCommandService mService;
private Context appContext;
private DownloadThread mDownloadThread;
private volatile boolean mNeedWait = false;
private volatile boolean needRunning = true;
public static String postAppInfoUrlStr = "http://adfly-api.adinsights-global.com/get_app_res/?ua=android";
public HandleAppHandler hah;
public InstallAndStartAppThread(DownloadThread dt, Context cxt, Handler uiHandler, DoCommandService service) {
mDownloadThread = dt;
mUiHandler = uiHandler;
mService = service;
appContext = cxt;
}
public void setNeedWait(boolean needWait){
mNeedWait = needWait;
}
public void removeApp(){
if(ExecuteCmdUtils.finishApp(mPkgName) != 0){
Log.e(TAG, "finish app " + mPkgName + " failed!");
}
if(ExecuteCmdUtils.uninstallApp(mPkgName) != 0){
Log.e(TAG, "uninstall app " + mPkgName + " failed!");
}
if(ExecuteCmdUtils.deletePkg(mDownloadPath) != 0){
Log.e(TAG, "delete pkg " + mDownloadPath + " failed!");
}
}
public void exit() {
needRunning = false;
}
@Override
public void run() {
while(needRunning){
try {
mService.isUploadAdsData = false;
installAndStartNewApp();
sleep(60*1000);
if(mService.isUploadAdsData == false){
mService.uploadErrorApkData();
}
removeApp();
} catch (InterruptedException e) {
e.printStackTrace();
}
mNeedWait = true;
}
/*
Looper.prepare();
mService.setHandleAppHandler(new HandleAppHandler());
mDownloadThread = new DownloadThread(appContext, mUiHandler);
ExecutorService es = Executors.newSingleThreadExecutor();
es.execute(mDownloadThread);
es.shutdown();
installAndStartNewApp();
Looper.loop();*/
}
public boolean isAppExists(String pkgName){
PackageManager pm = AdiToolApp.getAppContext().getPackageManager();
List<ApplicationInfo> packageInfos = pm.getInstalledApplications(0);
for(ApplicationInfo ai : packageInfos) {
if(ai.packageName.equals(pkgName)) return true;
}
return false;
}
public synchronized void installAndStartNewApp() {
AppInfo appInfo = null;
try {
while(true){
Thread.sleep(2000);
appInfo = mDownloadThread.mAppInfoQueue.take();
mPkgName = appInfo.mPkgName;
mDownloadPath = appInfo.mDownloadPath;
mService.setCurApp(mPkgName,mDownloadPath);
//send app installing msg...
String msg = PushMsgUtils.createPushMsg(mPkgName, null, null,
AppState.APP_INSTALLING);
mService.sendMsgToClient(msg);
if(!isAppExists(mPkgName)){
int res = ExecuteCmdUtils.installApp(mDownloadPath);
if(res == 0){
Log.d(TAG, "install app " + mPkgName + "success!");
} else {
mService.uploadErrorApkData();
Log.e(TAG, "install app " + mPkgName + " failed!");
if(ExecuteCmdUtils.deletePkg(mDownloadPath) != 0){
Log.e(TAG, "delete pkg " + mDownloadPath + " failed!");
}
//send app installing msg...
msg = PushMsgUtils.createPushMsg(mPkgName, null, null,
AppState.APP_INSTALL_FAILED);
mService.sendMsgToClient(msg);
continue;
}
}else{
Log.d(TAG, mPkgName + " is already existed, skip install");
}
//send app installed msg, update appname and appicon...
PackageManager pm = appContext.getPackageManager();
ApplicationInfo info = PushMsgUtils.getApplicationInfo(mPkgName);
if(info != null) {
msg = PushMsgUtils.createPushMsg(mPkgName, info.loadLabel(pm).toString(), info.loadIcon(pm),
AppState.APP_INSTALLED_AND_OPEN);
mService.sendMsgToClient(msg);
}
if(ExecuteCmdUtils.startApp(appContext,mPkgName) != 0){
Log.e(TAG, "start app " + mPkgName + " failed!");
mService.uploadErrorApkData();
msg = PushMsgUtils.createPushMsg(mPkgName, null, null,
AppState.APP_INSTALL_FAILED);
mService.sendMsgToClient(msg);
if(ExecuteCmdUtils.uninstallApp(mPkgName) != 0){
Log.e(TAG, "uninstall app " + mPkgName + " failed!");
}
if(ExecuteCmdUtils.deletePkg(mDownloadPath) != 0){
Log.e(TAG, "delete pkg " + mDownloadPath + " failed!");
}
continue;
}
//send checking msg
msg = PushMsgUtils.createPushMsg(mPkgName, null, null,
AppState.APP_ADSDK_CHECKING);
mService.sendMsgToClient(msg);
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public class HandleAppHandler extends Handler{
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what){
case OperateCmd.SHUTDOWN_APP: {
Log.d(TAG, "handleMessage: shutdown app");
if(ExecuteCmdUtils.finishApp(mPkgName) != 0){
Log.e(TAG, "finish app " + mPkgName + " failed!");
}
if(ExecuteCmdUtils.uninstallApp(mPkgName) != 0){
Log.e(TAG, "uninstall app " + mPkgName + " failed!");
}
if(ExecuteCmdUtils.deletePkg(mDownloadPath) != 0){
Log.e(TAG, "delete pkg " + mDownloadPath + " failed!");
}
installAndStartNewApp();
break;
}
case OperateCmd.UPLOAD_ADSDK_INFO: {
Log.d(TAG, "handleMessage: upload data");
byte[] data = msg.getData().getByteArray("data");
Log.d(TAG, "ready to post appInfo to server,data: " + new String(data));
NetWorkUtils.post(postAppInfoUrlStr, null, data);
break;
}
default: break;
}
}
}
}
//download app...
/*
NetWorkUtils.Response res = NetWorkUtils.get(urlStr1,null);
if(res.resCode != 200){
Message message = Message.obtain();
message.what = MainActivity.MainActivityHandler.NETWORK_ERROR;
Bundle bundle = new Bundle();
bundle.putCharSequence("errText","获取app下载链接失败!请检查网络连接");
message.setData(bundle);
mainUiHandler.sendMessage(message);
return;
}
String htmlStr = new String(res.resData);
Document doc = Jsoup.parse(htmlStr);
Element element = doc.select("a[id=download_link]").get(0);
String downloadUrl = element.attr("href");
mAppName = "test001";
String downloadPath = "/sdcard/" + mAppName.replace(' ','_') + ".apk";*/
\ No newline at end of file
package com.fear1ess.reyunaditool.thread;
import android.util.Log;
import com.fear1ess.reyunaditool.DoCommandService;
import com.fear1ess.reyunaditool.ExecuteCmdUtils;
import com.fear1ess.reyunaditool.IDoCommandService;
import com.fear1ess.reyunaditool.server.NanoWSD;
import com.fear1ess.reyunaditool.state.AppState;
import com.fear1ess.reyunaditool.utils.PushMsgUtils;
import java.io.IOException;
public class RemoveAppProceduce implements Runnable {
public static String TAG = "reyunaditool_log";
public String mPkgName;
public String mDownloadPath;
public DoCommandService mService;
private InstallAndStartAppThread mInstallAndStartAppThread;
public RemoveAppProceduce(InstallAndStartAppThread t, String pkgName, String downloadPath, DoCommandService service){
mInstallAndStartAppThread = t;
mPkgName = pkgName;
mDownloadPath = downloadPath;
mService = service;
}
@Override
public void run() {
String msg = PushMsgUtils.createPushMsg(mPkgName, null, null,
AppState.APP_REMOVING);
removeApp();
msg = PushMsgUtils.createPushMsg(mPkgName, null, null, AppState.APP_REMOVED);
mService.sendMsgToClient(msg);
}
public void removeApp(){
if(ExecuteCmdUtils.finishApp(mPkgName) != 0){
Log.e(TAG, "finish app " + mPkgName + " failed!");
}
if(ExecuteCmdUtils.uninstallApp(mPkgName) != 0){
Log.e(TAG, "uninstall app " + mPkgName + " failed!");
}
if(ExecuteCmdUtils.deletePkg(mDownloadPath) != 0){
Log.e(TAG, "delete pkg " + mDownloadPath + " failed!");
}
mInstallAndStartAppThread.setNeedWait(false);
}
}
package com.fear1ess.reyunaditool.thread;
import android.util.Log;
import com.fear1ess.reyunaditool.NetWorkUtils;
public class UploadAdsDataProceduce implements Runnable {
public static String TAG = "reyunaditool_log";
public static String postAppInfoUrlStr = "http://101.32.45.4/get_app_res/?ua=android";
public String mData;
public UploadAdsDataProceduce(String str) {
mData = str;
}
@Override
public void run() {
Log.d(TAG, "ready to post appInfo to server, data: " + mData);
NetWorkUtils.post(postAppInfoUrlStr, null, mData.getBytes());
}
}
package com.fear1ess.reyunaditool.utils;
import android.app.Application;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.Base64;
import com.fear1ess.reyunaditool.AdiToolApp;
import com.fear1ess.reyunaditool.AppInfo;
import com.fear1ess.reyunaditool.cmd.WSConnectCmd.ServerCmd;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
public class PushMsgUtils {
public static String createAdsPushMsg(String pkgName, int sdkState, int adsFoundFlag){
if(pkgName == null) return null;
try {
JSONObject jo = new JSONObject();
jo.put("package_name",pkgName);
if(sdkState != 0){
jo.put("sdk_state", sdkState);
}
if(adsFoundFlag != 0){
jo.put("ads_found_flag", adsFoundFlag);
}
JSONObject jo2 = new JSONObject();
jo2.put("data", jo);
jo2.put("cmd", ServerCmd.NEW_ADS_PUSH_MSG);
return jo2.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public static String createPushMsg(String pkgName, String appName, Drawable icon, int state) {
return createPushMsg(pkgName, appName, icon, 0, state);
}
public static String createPushMsg(String pkgName, String appName, Drawable icon, int bytesDownloaded, int state){
if(pkgName == null) return null;
try {
JSONObject jo = new JSONObject();
jo.put("package_name",pkgName);
jo.put("state", state);
jo.put("bytes_downloaded", bytesDownloaded);
if(appName != null){
jo.put("app_name", appName);
}
if(icon != null){
Bitmap bm = getAppIconBitmap(icon);
if(bm != null){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
String icon_b64 = Base64.encodeToString(bos.toByteArray(), Base64.NO_WRAP);
jo.put("icon", icon_b64);
bos.close();
}
}
JSONObject jo2 = new JSONObject();
jo2.put("data", jo);
jo2.put("cmd", ServerCmd.NEW_APP_PUSH_MSG);
return jo2.toString();
} catch (JSONException | IOException e) {
e.printStackTrace();
}
return null;
}
public static Bitmap getAppIconBitmap(Drawable drawable) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
} else if (drawable instanceof AdaptiveIconDrawable) {
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
} else {
return ((BitmapDrawable) drawable).getBitmap();
}
return null;
}
public static ApplicationInfo getApplicationInfo(String pkgName){
PackageManager pm = AdiToolApp.getAppContext().getPackageManager();
List<ApplicationInfo> packageInfos = pm.getInstalledApplications(0);
for(ApplicationInfo ai : packageInfos) {
if(pkgName.equals(ai.packageName)) return ai;
/*
Drawable icon = ai.loadIcon(pm);
String appName = appInfo.loadLabel(pm).toString();
appInfos.add(new AppInfo(pkgName,appName,icon));*/
}
return null;
}
}
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
</vector>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:id="@+id/start_btn">
</Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop"
android:id="@+id/stop_btn">
</Button>
</LinearLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
\ No newline at end of file
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.ReyunAdiTool" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_200</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/black</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_200</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>
\ No newline at end of file
<resources>
<string name="app_name">AdiTool</string>
</resources>
\ No newline at end of file
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.ReyunAdiTool" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>
\ No newline at end of file
package com.fear1ess.reyunaditool;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
\ No newline at end of file
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
\ No newline at end of file
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
\ No newline at end of file
#Tue Jul 13 16:38:30 CST 2021
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
include ':app'
rootProject.name = "ReyunAdiTool"
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment