Commit a92c9fc2 authored by topjohnwu's avatar topjohnwu

MagiskSU rewrite for unified binary

parent ed052e0b
...@@ -3,17 +3,6 @@ ...@@ -3,17 +3,6 @@
** Copyright 2010, Adam Shanks (@ChainsDD) ** Copyright 2010, Adam Shanks (@ChainsDD)
** Copyright 2008, Zinx Verituse (@zinxv) ** Copyright 2008, Zinx Verituse (@zinxv)
** **
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/ */
#include <sys/types.h> #include <sys/types.h>
...@@ -25,6 +14,7 @@ ...@@ -25,6 +14,7 @@
#include <stdio.h> #include <stdio.h>
#include <stdarg.h> #include <stdarg.h>
#include "magisk.h"
#include "su.h" #include "su.h"
/* intent actions */ /* intent actions */
...@@ -34,18 +24,16 @@ ...@@ -34,18 +24,16 @@
#define AM_PATH "/system/bin/app_process", "/system/bin", "com.android.commands.am.Am" #define AM_PATH "/system/bin/app_process", "/system/bin", "com.android.commands.am.Am"
// TODO: leverage this with exec_log? static void silent_run(char* const args[]) {
int silent_run(char* const args[]) {
set_identity(0); set_identity(0);
pid_t pid; pid_t pid;
pid = fork(); pid = fork();
/* Parent */ /* Parent */
if (pid < 0) { if (pid < 0) {
PLOGE("fork"); PLOGE("fork");
return -1;
} }
else if (pid > 0) { else if (pid > 0) {
return 0; return;
} }
int zero = open("/dev/zero", O_RDONLY | O_CLOEXEC); int zero = open("/dev/zero", O_RDONLY | O_CLOEXEC);
dup2(zero, 0); dup2(zero, 0);
...@@ -56,10 +44,9 @@ int silent_run(char* const args[]) { ...@@ -56,10 +44,9 @@ int silent_run(char* const args[]) {
execv(args[0], args); execv(args[0], args);
PLOGE("exec am"); PLOGE("exec am");
_exit(EXIT_FAILURE); _exit(EXIT_FAILURE);
return -1;
} }
int get_owner_login_user_args(struct su_context *ctx, char* user, int user_len) { static int get_owner_login_user_args(struct su_context *ctx, char* user, int user_len) {
int needs_owner_login_prompt = 0; int needs_owner_login_prompt = 0;
if (ctx->user.multiuser_mode == MULTIUSER_MODE_OWNER_MANAGED) { if (ctx->user.multiuser_mode == MULTIUSER_MODE_OWNER_MANAGED) {
...@@ -81,7 +68,7 @@ int get_owner_login_user_args(struct su_context *ctx, char* user, int user_len) ...@@ -81,7 +68,7 @@ int get_owner_login_user_args(struct su_context *ctx, char* user, int user_len)
return needs_owner_login_prompt; return needs_owner_login_prompt;
} }
int send_result(struct su_context *ctx, policy_t policy) { void app_send_result(struct su_context *ctx, policy_t policy) {
char binary_version[256]; char binary_version[256];
sprintf(binary_version, "%d", VERSION_CODE); sprintf(binary_version, "%d", VERSION_CODE);
...@@ -148,10 +135,10 @@ int send_result(struct su_context *ctx, policy_t policy) { ...@@ -148,10 +135,10 @@ int send_result(struct su_context *ctx, policy_t policy) {
user, user,
NULL NULL
}; };
return silent_run(result_command); silent_run(result_command);
} }
int send_request(struct su_context *ctx) { void app_send_request(struct su_context *ctx) {
// if su is operating in MULTIUSER_MODEL_OWNER, // if su is operating in MULTIUSER_MODEL_OWNER,
// and the user requestor is not the owner, // and the user requestor is not the owner,
// the owner needs to be notified of the request. // the owner needs to be notified of the request.
...@@ -159,7 +146,6 @@ int send_request(struct su_context *ctx) { ...@@ -159,7 +146,6 @@ int send_request(struct su_context *ctx) {
char user[64]; char user[64];
int needs_owner_login_prompt = get_owner_login_user_args(ctx, user, sizeof(user)); int needs_owner_login_prompt = get_owner_login_user_args(ctx, user, sizeof(user));
int ret;
if (needs_owner_login_prompt) { if (needs_owner_login_prompt) {
char uid[256]; char uid[256];
sprintf(uid, "%d", ctx->from.uid); sprintf(uid, "%d", ctx->from.uid);
...@@ -179,10 +165,7 @@ int send_request(struct su_context *ctx) { ...@@ -179,10 +165,7 @@ int send_request(struct su_context *ctx) {
NULL NULL
}; };
int ret = silent_run(notify_command); silent_run(notify_command);
if (ret) {
return ret;
}
} }
char *request_command[] = { char *request_command[] = {
...@@ -196,5 +179,5 @@ int send_request(struct su_context *ctx) { ...@@ -196,5 +179,5 @@ int send_request(struct su_context *ctx) {
NULL NULL
}; };
return silent_run(request_command); silent_run(request_command);
} }
This diff is collapsed.
/* /*
** Copyright 2013, Koushik Dutta (@koush) ** Copyright 2013, Koushik Dutta (@koush)
** **
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/ */
#include <stdlib.h> #include <stdlib.h>
...@@ -19,7 +8,9 @@ ...@@ -19,7 +8,9 @@
#include <limits.h> #include <limits.h>
#include <sqlite3.h> #include <sqlite3.h>
#include <time.h> #include <time.h>
#include <string.h>
#include "magisk.h"
#include "su.h" #include "su.h"
struct callback_data_t { struct callback_data_t {
......
/* misc.c - Miscellaneous stuffs for su
*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include "magisk.h"
#include "su.h"
int quit_signals[] = { SIGALRM, SIGABRT, SIGHUP, SIGPIPE, SIGQUIT, SIGTERM, SIGINT, 0 };
void setup_sighandlers(void (*handler)(int)) {
struct sigaction act;
// Install the termination handlers
// Note: we're assuming that none of these signal handlers are already trapped.
// If they are, we'll need to modify this code to save the previous handler and
// call it after we restore stdin to its previous state.
memset(&act, 0, sizeof(act));
act.sa_handler = handler;
for (int i = 0; quit_signals[i]; ++i) {
sigaction(quit_signals[i], &act, NULL);
}
}
void set_identity(unsigned uid) {
/*
* Set effective uid back to root, otherwise setres[ug]id will fail
* if uid isn't root.
*/
if (seteuid(0)) {
PLOGE("seteuid (root)");
}
if (setresgid(uid, uid, uid)) {
PLOGE("setresgid (%u)", uid);
}
if (setresuid(uid, uid, uid)) {
PLOGE("setresuid (%u)", uid);
}
}
char *get_command(const struct su_request *to) {
if (to->command)
return to->command;
if (to->shell)
return to->shell;
return DEFAULT_SHELL;
}
/* /*
* Copyright 2013, Tan Chee Eng (@tan-ce) * Copyright 2013, Tan Chee Eng (@tan-ce)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
/* /*
...@@ -21,6 +9,7 @@ ...@@ -21,6 +9,7 @@
* helper functions to handle raw input mode and terminal window resizing * helper functions to handle raw input mode and terminal window resizing
*/ */
#define _GNU_SOURCE
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h> #include <unistd.h>
#include <fcntl.h> #include <fcntl.h>
...@@ -29,6 +18,7 @@ ...@@ -29,6 +18,7 @@
#include <errno.h> #include <errno.h>
#include <pthread.h> #include <pthread.h>
#include "magisk.h"
#include "pts.h" #include "pts.h"
/** /**
...@@ -110,27 +100,27 @@ int pts_open(char *slave_name, size_t slave_name_size) { ...@@ -110,27 +100,27 @@ int pts_open(char *slave_name, size_t slave_name_size) {
// Open master ptmx device // Open master ptmx device
fdm = open("/dev/ptmx", O_RDWR); fdm = open("/dev/ptmx", O_RDWR);
if (fdm == -1) return -1; if (fdm == -1)
goto error;
// Get the slave name // Get the slave name
if (ptsname_r(fdm, slave_name, slave_name_size-1)) { if (ptsname_r(fdm, slave_name, slave_name_size-1))
close(fdm); goto error;
return -2;
}
slave_name[slave_name_size - 1] = '\0'; slave_name[slave_name_size - 1] = '\0';
// Grant, then unlock // Grant, then unlock
if (grantpt(fdm) == -1) { if (grantpt(fdm) == -1)
close(fdm); goto error;
return -1;
} if (unlockpt(fdm) == -1)
if (unlockpt(fdm) == -1) { goto error;
close(fdm);
return -1;
}
return fdm; return fdm;
error:
close(fdm);
PLOGE("pts_open");
return -1;
} }
// Stores the previous termios of stdin // Stores the previous termios of stdin
......
/* /*
* Copyright 2013, Tan Chee Eng (@tan-ce) * Copyright 2013, Tan Chee Eng (@tan-ce)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
/* /*
...@@ -24,6 +12,8 @@ ...@@ -24,6 +12,8 @@
#ifndef _PTS_H_ #ifndef _PTS_H_
#define _PTS_H_ #define _PTS_H_
#include <sys/types.h>
/** /**
* pts_open * pts_open
* *
......
This diff is collapsed.
/* /* su.h - Store all general su info
** Copyright 2010, Adam Shanks (@ChainsDD) */
** Copyright 2008, Zinx Verituse (@zinxv)
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#ifndef SU_h
#define SU_h 1
#include "magisk.h"
#ifndef AID_SHELL
#define AID_SHELL (get_shell_uid())
#endif
#ifndef AID_ROOT #ifndef _SU_H_
#define AID_ROOT 0 #define _SU_H_
#endif
#ifndef AID_SYSTEM #include <limits.h>
#define AID_SYSTEM (get_system_uid()) #include <sys/types.h>
#endif
#ifndef AID_RADIO #define SU_VERSION_STR xstr(VERSION) ":MAGISKSU (topjohnwu)"
#define AID_RADIO (get_radio_uid())
#endif
// Property check for root access
#define ROOT_ACCESS_PROP "persist.sys.root_access" #define ROOT_ACCESS_PROP "persist.sys.root_access"
#define ROOT_ACCESS_DISABLED 0 #define ROOT_ACCESS_DISABLED 0
#define ROOT_ACCESS_APPS_ONLY 1 #define ROOT_ACCESS_APPS_ONLY 1
...@@ -45,22 +19,19 @@ ...@@ -45,22 +19,19 @@
// DO NOT CHANGE LINE BELOW, java package name will always be the same // DO NOT CHANGE LINE BELOW, java package name will always be the same
#define JAVA_PACKAGE_NAME "com.topjohnwu.magisk" #define JAVA_PACKAGE_NAME "com.topjohnwu.magisk"
#define APPLICATION_DATA_PATH "/data/data/"
#define USER_DATA_PATH "/data/user"
// If --rename-manifest-package is used in AAPT, this // If --rename-manifest-package is used in AAPT, this
// must be changed to correspond to the new APK package name // must be changed to correspond to the new APK package name
// See the two Android.mk files for more details. // See the two Android.mk files for more details.
#ifndef REQUESTOR
#define REQUESTOR JAVA_PACKAGE_NAME #define REQUESTOR JAVA_PACKAGE_NAME
#endif
// This is used if wrapping the fragment classes and activities // This is used if wrapping the fragment classes and activities
// with classes in another package. CM requirement. // with classes in another package.
#ifndef REQUESTOR_PREFIX
#define REQUESTOR_PREFIX JAVA_PACKAGE_NAME ".superuser" #define REQUESTOR_PREFIX JAVA_PACKAGE_NAME ".superuser"
#endif #define REQUESTOR_FILES_PATH APPLICATION_DATA_PATH REQUESTOR "/files"
#define REQUESTOR_DATA_PATH "/data/data/"
#define REQUESTOR_FILES_PATH REQUESTOR_DATA_PATH REQUESTOR "/files"
#define REQUESTOR_USER_PATH "/data/user/"
#define REQUESTOR_CACHE_PATH "/dev/" REQUESTOR #define REQUESTOR_CACHE_PATH "/dev/" REQUESTOR
#define REQUESTOR_DAEMON_PATH "\0MAGISKSU"
// there's no guarantee that the db or files are actually created named as such by // there's no guarantee that the db or files are actually created named as such by
// SQLiteOpenHelper, etc. Though that is the behavior as of current. // SQLiteOpenHelper, etc. Though that is the behavior as of current.
// it is up to the Android application to symlink as appropriate. // it is up to the Android application to symlink as appropriate.
...@@ -69,22 +40,9 @@ ...@@ -69,22 +40,9 @@
#define DEFAULT_SHELL "/system/bin/sh" #define DEFAULT_SHELL "/system/bin/sh"
#define xstr(a) str(a)
#define str(a) #a
#ifndef VERSION_CODE
#define VERSION_CODE 8
#endif
#define VERSION xstr(VERSION_CODE) ":MAGISKSU (topjohnwu)"
#define PROTO_VERSION 1
struct su_initiator { struct su_initiator {
pid_t pid; pid_t pid;
unsigned uid; unsigned uid;
unsigned user;
char bin[PATH_MAX];
char args[4096];
}; };
struct su_request { struct su_request {
...@@ -95,7 +53,6 @@ struct su_request { ...@@ -95,7 +53,6 @@ struct su_request {
char *command; char *command;
char **argv; char **argv;
int argc; int argc;
int optind;
}; };
struct su_user_info { struct su_user_info {
...@@ -145,30 +102,33 @@ typedef enum { ...@@ -145,30 +102,33 @@ typedef enum {
ALLOW = 2, ALLOW = 2,
} policy_t; } policy_t;
extern policy_t database_check(struct su_context *ctx); extern int from_uid, from_pid;
extern void set_identity(unsigned int uid); extern int quit_signals[];
extern int send_request(struct su_context *ctx);
extern int send_result(struct su_context *ctx, policy_t policy); // su.c
static inline char *get_command(const struct su_request *to) int su_daemon_main(int argc, char **argv);
{
if (to->command) // su_client.c
return to->command;
if (to->shell) int socket_create_temp(char *path, size_t len);
return to->shell; int socket_accept(int serv_fd);
char* ret = to->argv[to->optind]; void socket_send_request(int fd, const struct su_context *ctx);
if (ret) void socket_receive_result(int fd, char *result, ssize_t result_len);
return ret;
return DEFAULT_SHELL; // activity.c
}
void app_send_result(struct su_context *ctx, policy_t policy);
int run_daemon(); void app_send_request(struct su_context *ctx);
int connect_daemon(int argc, char *argv[], int ppid);
int su_main(int argc, char *argv[]); // db.c
int su_main_nodaemon(int argc, char *argv[]);
// for when you give zero fucks about the state of the child process. policy_t database_check(struct su_context *ctx);
// this version of fork understands you don't care about the child.
// deadbeat dad fork. // misc.c
int fork_zero_fucks();
void setup_sighandlers(void (*handler)(int));
void set_identity(unsigned uid);
char *get_command(const struct su_request *to);
#endif #endif
/* su_client.c - The entrypoint for su, connect to daemon and send correct info
*/
#include <limits.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include "magisk.h"
#include "daemon.h"
#include "utils.h"
#include "su.h"
#include "pts.h"
int from_uid, from_pid;
struct su_daemon_info {
int child;
int client;
};
static void *wait_result(void *args) {
struct su_daemon_info *info = args;
LOGD("su: wait_result waiting for %d\n", info->child);
err_handler = exit_thread;
int status, code;
if (waitpid(info->child, &status, 0) > 0)
code = WEXITSTATUS(status);
else
code = -1;
// Pass the return code back to the client
write_int(info->client, code);
LOGD("su: return code to client: %d\n", code);
close(info->client);
free(info);
return NULL;
}
static void sighandler(int sig) {
restore_stdin();
// Assume we'll only be called before death
// See note before sigaction() in set_stdin_raw()
//
// Now, close all standard I/O to cause the pumps
// to exit so we can continue and retrieve the exit
// code
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
// Put back all the default handlers
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_handler = SIG_DFL;
for (int i = 0; quit_signals[i]; ++i) {
sigaction(quit_signals[i], &act, NULL);
}
}
void su_daemon_receiver(int client) {
LOGD("su: get request\n");
// Fork a new process, the child process will need to setsid,
// open a pseudo-terminal, and will eventually run exec
// The parent process (the root daemon) will open a new thread to
// send the return code back to our client
int child = fork();
if (child < 0) {
PLOGE("fork");
write(client, &child, sizeof(child));
close(client);
return;
} else if (child != 0) {
pthread_t wait_thread;
struct su_daemon_info *info = xmalloc(sizeof(*info));
info->client = client;
info->child = child;
// In parent, open a new thread to wait for the child to exit,
// and send the exit code across the wire.
xpthread_create(&wait_thread, NULL, wait_result, info);
return;
}
LOGD("su: child process started\n");
// ack
write_int(client, 1);
// Here we're in the child
// Set the error handler back to normal
err_handler = exit_proc;
// Become session leader
xsetsid();
// Check the credentials
struct ucred credentials;
socklen_t ucred_length = sizeof(struct ucred);
if(getsockopt(client, SOL_SOCKET, SO_PEERCRED, &credentials, &ucred_length))
PLOGE("getsockopt");
from_uid = credentials.uid;
from_pid = credentials.pid;
// Let's read some info from the socket
int argc = read_int(client);
if (argc < 0 || argc > 512) {
LOGE("unable to allocate args: %d", argc);
exit(1);
}
LOGD("su: argc=[%d]\n", argc);
char **argv = (char**) xmalloc(sizeof(char*) * (argc + 1));
argv[argc] = NULL;
for (int i = 0; i < argc; i++) {
argv[i] = read_string(client);
LOGD("su: argv[%d]=[%s]\n", i, argv[i]);
}
// Change directory to cwd
char *cwd = read_string(client);
LOGD("su: cwd=[%s]\n", cwd);
chdir(cwd);
free(cwd);
// Get pts_slave
char *pts_slave = read_string(client);
LOGD("su: pts_slave=[%s]\n", pts_slave);
// We no longer need the access to socket in the child, close it
close(client);
//Check pts_slave file is owned by daemon_from_uid
int ptsfd;
struct stat stbuf;
int res = xstat(pts_slave, &stbuf);
//If caller is not root, ensure the owner of pts_slave is the caller
if(stbuf.st_uid != credentials.uid && credentials.uid != 0) {
LOGE("Wrong permission of pts_slave");
exit(1);
}
// Opening the TTY has to occur after the
// fork() and setsid() so that it becomes
// our controlling TTY and not the daemon's
ptsfd = xopen(pts_slave, O_RDWR);
free(pts_slave);
// Swap out stdin, stdout, stderr
xdup2(ptsfd, STDIN_FILENO);
xdup2(ptsfd, STDOUT_FILENO);
xdup2(ptsfd, STDERR_FILENO);
close(ptsfd);
su_daemon_main(argc, argv);
}
/*
* Connect daemon, send argc, argv, cwd, pts slave
*/
int su_client_main(int argc, char *argv[]) {
char buffer[PATH_MAX];
int ptmx, socketfd;
// Connect to client
socketfd = connect_daemon();
// Tell the daemon we are su
write_int(socketfd, SUPERUSER);
// Number of command line arguments
write_int(socketfd, argc);
// Command line arguments
for (int i = 0; i < argc; i++) {
write_string(socketfd, argv[i]);
}
// CWD
getcwd(buffer, sizeof(buffer));
write_string(socketfd, buffer);
// We need a PTY. Get one.
ptmx = pts_open(buffer, sizeof(buffer));
watch_sigwinch_async(STDOUT_FILENO, ptmx);
// Send the slave path to the daemon
write_string(socketfd, buffer);
// Wait for acknowledgement from daemon
read_int(socketfd);
setup_sighandlers(sighandler);
pump_stdin_async(ptmx);
pump_stdout_blocking(ptmx);
// Get the exit code
int code = read_int(socketfd);
close(socketfd);
return code;
}
/* su_socket.c - Functions for communication to client
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "magisk.h"
#include "utils.h"
#include "su.h"
int socket_create_temp(char *path, size_t len) {
int fd;
struct sockaddr_un sun;
fd = xsocket(AF_LOCAL, SOCK_STREAM, 0);
if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
PLOGE("fcntl FD_CLOEXEC");
}
memset(&sun, 0, sizeof(sun));
sun.sun_family = AF_LOCAL;
snprintf(path, len, "%s/.socket%d", REQUESTOR_CACHE_PATH, getpid());
snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
/*
* Delete the socket to protect from situations when
* something bad occured previously and the kernel reused pid from that process.
* Small probability, isn't it.
*/
unlink(sun.sun_path);
xbind(fd, (struct sockaddr*) &sun, sizeof(sun));
xlisten(fd, 1);
return fd;
}
int socket_accept(int serv_fd) {
struct timeval tv;
fd_set fds;
int rc;
/* Wait 20 seconds for a connection, then give up. */
tv.tv_sec = 20;
tv.tv_usec = 0;
FD_ZERO(&fds);
FD_SET(serv_fd, &fds);
do {
rc = select(serv_fd + 1, &fds, NULL, NULL, &tv);
} while (rc < 0 && errno == EINTR);
if (rc < 1) {
PLOGE("select");
}
return xaccept(serv_fd, NULL, NULL);
}
#define write_data(fd, data, data_len) \
do { \
uint32_t __len = htonl(data_len); \
__len = write((fd), &__len, sizeof(__len)); \
if (__len != sizeof(__len)) { \
PLOGE("write(" #data ")"); \
} \
__len = write((fd), data, data_len); \
if (__len != data_len) { \
PLOGE("write(" #data ")"); \
} \
} while (0)
#define write_string_data(fd, name, data) \
do { \
write_data(fd, name, strlen(name)); \
write_data(fd, data, strlen(data)); \
} while (0)
// stringify everything.
#define write_token(fd, name, data) \
do { \
char buf[16]; \
snprintf(buf, sizeof(buf), "%d", data); \
write_string_data(fd, name, buf); \
} while (0)
void socket_send_request(int fd, const struct su_context *ctx) {
write_token(fd, "uid", ctx->from.uid);
write_token(fd, "eof", 1);
}
void socket_receive_result(int fd, char *result, ssize_t result_len) {
ssize_t len;
len = xread(fd, result, result_len - 1);
result[len] = '\0';
}
/*
** Copyright 2012, The CyanogenMod Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>
#include <fcntl.h>
#include <errno.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utils.h"
/* reads a file, making sure it is terminated with \n \0 */
char* read_file(const char *fn)
{
struct stat st;
char *data = NULL;
int fd = open(fn, O_RDONLY);
if (fd < 0) return data;
if (fstat(fd, &st)) goto oops;
data = malloc(st.st_size + 2);
if (!data) goto oops;
if (read(fd, data, st.st_size) != st.st_size) goto oops;
close(fd);
data[st.st_size] = '\n';
data[st.st_size + 1] = 0;
return data;
oops:
close(fd);
if (data) free(data);
return NULL;
}
int get_property(const char *data, char *found, const char *searchkey, const char *not_found)
{
char *key, *value, *eol, *sol, *tmp;
if (data == NULL) goto defval;
int matched = 0;
sol = strdup(data);
while((eol = strchr(sol, '\n'))) {
key = sol;
*eol++ = 0;
sol = eol;
value = strchr(key, '=');
if(value == 0) continue;
*value++ = 0;
while(isspace(*key)) key++;
if(*key == '#') continue;
tmp = value - 2;
while((tmp > key) && isspace(*tmp)) *tmp-- = 0;
while(isspace(*value)) value++;
tmp = eol - 2;
while((tmp > value) && isspace(*tmp)) *tmp-- = 0;
if (strncmp(searchkey, key, strlen(searchkey)) == 0) {
matched = 1;
break;
}
}
int len;
if (matched) {
len = strlen(value);
if (len >= PROPERTY_VALUE_MAX)
return -1;
memcpy(found, value, len + 1);
} else goto defval;
return len;
defval:
len = strlen(not_found);
memcpy(found, not_found, len + 1);
return len;
}
/*
* Fast version of get_property which purpose is to check
* whether the property with given prefix exists.
*
* Assume nobody is stupid enough to put a propery with prefix ro.cm.version
* in his build.prop on a non-CM ROM and comment it out.
*/
int check_property(const char *data, const char *prefix)
{
if (!data)
return 0;
return strstr(data, prefix) != NULL;
}
/*
** Copyright 2012, The CyanogenMod Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#ifndef _UTILS_H_
#define _UTILS_H_
#ifndef PROPERTY_VALUE_MAX
#define PROPERTY_VALUE_MAX 92
#endif
/* reads a file, making sure it is terminated with \n \0 */
extern char* read_file(const char *fn);
extern int get_property(const char *data, char *found, const char *searchkey,
const char *not_found);
extern int check_property(const char *data, const char *prefix);
#endif
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