Libs/android_runtime/android_net_wifi_wifi.cpp
Partial JNI interface
Static Jninativemethod gwifimethods[] = {
{"Loaddriver", "() Z", (void *) Android_net_wifi_loaddriver},
{"Setpowermodecommand", "(I) Z", (void*) Android_net_wifi_setpowermodecommand},//Power Management
{"Connecttosupplicant", "() Z", (void *) Android_net_wifi_connecttosupplicant},
{"Waitforevent", "() ljava/lang/string;", (void*) android_net_wifi_waitforevent},
{"Disconnectcommand", "() Z", (void *) Android_net_wifi_disconnectcommand},
...
};
int Register_android_net_wifi_wifimanager (jnienv* env)
{
...
Return Androidruntime::registernativemethods (env,
Wifi_pkg_name, Gwifimethods, Nelem (gwifimethods));//Register JNI
}
Libs/android_runtime/androidruntime.cpp
static const REGJNIREC gregjni[] = {
...
Reg_jni (Register_android_net_wifi_wifimanager),
...
};
int Androidruntime::startreg (jnienv* env)
{
...
Register_jni_procs (Gregjni, Nelem (GREGJNI), env);
...
}
Androidruntime::start
=>startreg (env) is called method int Androidruntime::startreg (jnienv* env)
=============================================================================================================
Wifi_load_driver
Wifi_start_supplicant
=>ensure_config_file_exists
Check to see if the/data/misc/wifi/wpa_supplicant.conf file exists, and if it does not exist, copy it dynamically from/system/etc/wifi/wpa_supplicant.conf
Android_net_wifi_connecttosupplicant
=>wifi_connect_to_supplicant
=
Ctrl_conn = Wpa_ctrl_open (ifname);
Monitor_conn = Wpa_ctrl_open (ifname);
Wpa_ctrl_attach (Monitor_conn);
Android_net_wifi_waitforevent
=>wifi_wait_for_event
=>wpa_ctrl_recv (Monitor_conn, buf, &nread);
=>recv (Ctrl->s, reply, *reply_len, 0);//blocking wpa_supplicant data waiting for NetLink to come over
= = If the received BUF data area, buf[0] is ' < ', then the level information is indicated, so the ' < ' ... ' > ' data is rejected and the Wifi_wait_for_event function returns [ Luther.gliethttp].
Java/android/android/net/wifi/wifimonitor.java
public class Wifimonitor {
...
public void startmonitoring () {
New Monitorthread (). Start ();//Start Java thread
}
Class Monitorthread extends Thread {
Public Monitorthread () {
Super ("Wifimonitor");
}
public void Run () {
for (;;) {
Ensuresupplicantconnection ();//=>wifinative.connecttosupplicant Call JNI function android_net_wifi_connecttosupplicant
String eventstr = wifinative.waitforevent ();//=> calls the JNI function android_net_wifi_waitforevent
private static final int CONNECTED = 1;
private static final int disconnected = 2;
private static final String Eventprefix = "ctrl-event-";
private static final int eventprefixlen = Eventprefix.length ();
private static final String connectedevent = "CONNECTED";
private static final String disconnectedevent = "Disconnected";
String eventName = Eventstr.substring (Eventprefixlen);//Remove "ctrl-event-" string
int nameend = Eventname.indexof (");//Find the next space position, which is sent at wpa_supplicant
#define Wpa_event_connected "ctrl-event-connected", there are already built-in spaces.
if (nameend! =-1)
EventName = eventname.substring (0, NameEnd);
int event;
if (Eventname.equals (connectedevent))//Detect NetLink over the string action type
event = CONNECTED;
else if (eventname.equals (disconnectedevent))
event = disconnected;
...
int ind = Eventstr.indexof ("-");//ctrl-event-connected-connection to ...
if (Ind! =-1)
EventData = eventstr.substring (Ind + 3);
Reject the leading control character and continue processing with the description string after "-" as real data
...
if (event = = State_change) {
Handlesupplicantstatechange (EventData);
} else if (event = = Driver_state) {
Handledriverevent (EventData);
} else {
Handleevent (event, eventData);//For NetLink events such as connected and disconnected, this will be done to handle [luther.gliethttp]
If supplicant is gone, exit the thread
if (event = = terminating) {
Break
}
}
...
void Handleevent (int event, String remainder) {
Switch (event) {
Case disconnected:
Handlenetworkstatechange (NetworkInfo.DetailedState.DISCONNECTED, remainder);
Break
Case CONNECTED:
Handlenetworkstatechange (NetworkInfo.DetailedState.CONNECTED, remainder);//Control Interface display
Break
...
}
public class Wifistatetracker extends Networkstatetracker {
...
public void Starteventloop () {
Mwifimonitor.startmonitoring ();//start the above Monitorthread thread
}
...
}
Java/services/com/android/server/wifiservice.java
public class Wifiservice extends Iwifimanager.stub {
...
Private Boolean setwifienabledblocking (Boolean enable) {
Final int eventualwifistate = enable? wifi_state_enabled:wifi_state_disabled;
...
if (enable) {
if (Wifinative.loaddriver ()) {
LOG.E (TAG, "Failed to load Wi-Fi driver.");
Updatewifistate (Wifi_state_unknown);
return false;
}
if (Wifinative.startsupplicant ()) {
Wifinative.unloaddriver ();
LOG.E (TAG, "Failed to start supplicant daemon.");
Updatewifistate (Wifi_state_unknown);
return false;
}
Mwifistatetracker.starteventloop ();
Start the monitorthread thread, wait for wpa_supplicant to forward NetLink data, and then, depending on the type of NetLink action, further affect the interface display [Luther.gliethttp].
}
...
}
Java/android/android/net/wifi/wifistatetracker.java
Power Management
private void Handleconnectedstate () {
...
Mdhcptarget.obtainmessage (Event_dhcp_start). Sendtotarget ();//pass to the Handlemessage method below
...
}
public void OnChange (Boolean selfchange) {
...
Handleconnectedstate ();
...
}
public class Wifistatetracker extends Networkstatetracker {
...
public void Handlemessage (Message msg) {
Switch (msg.what) {
Case Event_supplicant_connection:
Case event_network_state_changed:
Handleconnectedstate ();//Call
...
Private class Dhcphandler extends Handler {
Private Handler Mtarget;
Public Dhcphandler (Looper Looper, Handler target) {
Super (Looper);
Mtarget = target;
}
public void Handlemessage (Message msg) {
int event;
private static final int driver_power_mode_auto = 0;
private static final int driver_power_mode_active = 1;
Switch (msg.what) {
Case Event_dhcp_start:
Synchronized (this) {
Wifinative.setpowermodecommand (driver_power_mode_active);//Set power mode, call Android_net_wifi_setpowermodecommand
}
LOG.D (TAG, "Dhcphandler:dhcp request Started");
Libs/android_runtime/android_net_netutils.cpp
Static Jninativemethod gnetworkutilmethods[] = {
{"Rundhcp", "(ljava/lang/string; Landroid/net/dhcpinfo;) Z ", (void *) Android_net_utils_rundhcp},
// ...
//};
if (Networkutils.rundhcp (Minterfacename, Mdhcpinfo)) {//Perform DHCP request IP address operation
event = event_interface_configuration_succeeded;
if (LOCAL_LOGD) log.v (TAG, "Dhcphandler:dhcp request succeeded");
} else {
event = event_interface_configuration_failed;
LOG.I (TAG, "Dhcphandler:dhcp request failed:" +
Networkutils.getdhcperror ());
If the DHCPCD assignment IP fails, then Message.obtain (Mtarget, event). Sendtotarget (); Will execute
Wifinative.disconnectcommand (); i.e.: static Jninativemethod gwifimethods[] = {
Android_net_wifi_disconnectcommand send "DISCONNECT" string [luther.gliethttp]
Then execute wpa_supplicant_ctrl_iface_process on the wpa_supplicant server
Wpa_supplicant_disassociate
}
Synchronized (this) {
Wifinative.setpowermodecommand (Driver_power_mode_auto);
}
Message.obtain (Mtarget, event). Sendtotarget ();
Break
}
}
}
...
/**
* Send the Tracker a notification that a connection to the supplicant
* Daemon has been established.
*/
On the public class wifimonitor=>ensuresupplicantconnection above
=
while (!supplicantconnected) {
Boolean connected;
Synchronized (Mwifistatetracker) {
Connected = Wifinative.connecttosupplicant ();//If there is no successful connection, then the while loop attempts until the attempt succeeds, or the oneshot is defined, only one attempt
=>mwifistatetracker.notifysupplicantconnection ();//If Wifinative.connecttosupplicant () succeeds, it will execute
The invocation of Mwifistatetracker.notifysupplicantconnection ();
void Notifysupplicantconnection () {//Send message to Object
Message.obtain (this, event_supplicant_connection). Sendtotarget ();
}
void Notifystatechange (Supplicantstate newstate) {
Message.obtain (This, event_supplicant_state_changed, newstate). Sendtotarget ();
}
...
}
Static Jboolean Android_net_wifi_setpowermodecommand (jnienv* env, Jobject clazz, Jint mode)
{
Char cmdstr[256];
sprintf (Cmdstr, "DRIVER powermode%d", mode);
Return Dobooleancommand (cmdstr, "OK");
}
Android_net_wifi_setpowermodecommand
=>dobooleancommand
=>docommand
=>wifi_command
=>wifi_send_command
=>wpa_ctrl_request
=>send to Wpa_supplicant
Then Wpa_supplicant will do the following receive operation:
System/extra/wpa_supplicant/main.c
=>wpa_supplicant_add_iface
=>wpa_supplicant_init_iface2
=>wpa_supplicant_ctrl_iface_init
= = Registers the Ctrl_conn control port and the Monitor_conn listener Port's handler function
Eloop_register_read_sock (Priv->sock, wpa_supplicant_ctrl_iface_receive, wpa_s, priv);//ctrl_conn handler function for handler port
WPA_MSG_REGISTER_CB (WPA_SUPPLICANT_CTRL_IFACE_MSG_CB);//monitor_conn Port callback handler, processing NetLink data to all monitor_conn listening ports
=>wpa_supplicant_ctrl_iface_receive//for UNIX communication methods
=>wpa_supplicant_ctrl_iface_process
= = If wpa_cli sends a command in the form of WPA_CLI driver xxx, call this function
if (os_strncmp (buf, "DRIVER", 7) = = 0) {//over the first 7, pass the command directly
Reply_len = Wpa_supplicant_driver_cmd (wpa_s, buf + 7, reply, reply_size);
=>wpa_supplicant_driver_cmd
=>wpa_drv_driver_cmd
+ = Custom Driver extension handler, so for the power power management commands that Java passes over, Wpa_drv_driver_cmd will receive a "Powermode 0" or "Powermode 1" string [ Luther.gliethttp]
=============================================================================================================
Jni
=>rundhcp
=>android_net_utils_rundhcp
Libs/netutils/dhcp_utils.c
=>dhcp_do_request
=
static const char daemon_name[] = "DHCPCD";
static const char daemon_prop_name[] = "INIT.SVC.DHCPCD";
static const char dhcp_prop_name_prefix[] = "DHCP";
const char *ctrl_prop = "Ctl.start";
const char *desired_status = "Running";
snprintf (result_prop_name, sizeof (Result_prop_name), "%s.%s.result",
Dhcp_prop_name_prefix,
interface);
Property_set (Result_prop_name, "");//Set dhcp.eth0.result= ""; wait until DHCP is completed successfully.
Property_set (Ctrl_prop, daemon_name);//to a service named DHCPCD, send a "ctrl.start" Start command word, the service in init.rc
Init.rc in DHCPCD service process command word
Service DHCPCD/SYSTEM/BIN/DHCPCD eth0
Disabled
OneShot
Wait_for_property (Daemon_prop_name, Desired_status, 10);
Init.c=>init process
=>HANDLE_PROPERTY_SET_FD called Handle_control_message processing control information because it is a "ctrl.start" command word
=>handle_control_message
=>msg_start
=
struct Service *svc = service_find_by_name (name);
Service_start (SVC);//Start SVC, i.e. execute:/SYSTEM/BIN/DHCPCD eth0
=>service_start
=>pid = fork ();
if (PID = = 0) execve (svc->args[0], (char**) Svc->args, (char**) ENV); Sub-process Execve run/SYSTEM/BIN/DHCPCD, parameter eth0
/= Otherwise the parent process, the INIT process, will
=>notify_service_state (Svc->name, "running"); sets the state of the SVC prop
snprintf (pname, sizeof (pname), "init.svc.%s", name);
Property_set (PName, State);//So the above Wait_for_property (Daemon_prop_name, Desired_status, 10); it will be normal pass[ Luther.gliethttp].
Wait_for_property (Result_prop_name, NULL, 15);//wait for dhcp.eth0.result= non-empty
=============================================================================================================
System/extra/dhcpcd-4.0.0-beta9/dhcpcd.c
Dhcpcd
=>main
# define SYSCONFDIR "/SYSTEM/ETC/DHCPCD"
#define PACKAGE "DHCPCD"
# define CONFIG Sysconfdir "/" package ". conf"
# define LIBEXECDIR "/SYSTEM/ETC/DHCPCD"
# define SCRIPT Libexecdir "/" Package "-run-hooks"
=>strlcpy (options->script, script, sizeof (OPTIONS->SCRIPT));//default options->script= "/SYSTEM/ETC/DHCPCD /dhcpcd-run-hooks "
=>f = fopen (cf. cf:config, "R");//If you do not specify a. conf file, use the default. conf file
=>parse_config_line//parsing the "/system/etc/dhcpcd/dhcpcd.conf" default configuration file
=>parse_option
= If there is a "script" section in "/system/etc/dhcpcd/dhcpcd.conf"
= = then perform strlcpy (Options->script, Oarg, sizeof (Options->script)); direct copy
/*
{"Script", Required_argument, NULL, ' C '},
{"option", Required_argument, NULL, ' O '},
Some of the contents of "/system/etc/dhcpcd/dhcpcd.conf" are as follows:
...
Option Domain_name_servers, domain_name, Domain_search, host_name
...
*/
=>dhcp_run
=>handle_dhcp_packet
=>handle_dhcp
=>bind_dhcp
Reason = "TIMEOUT"; reason = "BOUND"; reason = "REBIND"; reason = "RENEW";
System/extra/dhcpcd-4.0.0-beta9/configure.c
= Configure (iface, Reason, State->new, State->old, &state->lease, Options, 1);
If the DHCP time-out or DHCP succeeds, Exec_script is called to execute the script.
Execute SetProp dhcp.${interface}.result "failed" or
Execute setprop dhcp.${interface}.result "OK"
=>exec_script (options, iface->name, Reason, NULL, old);
/= then configure_env passes the reason to the script through the environment variable
int exec_script (const struct options *options, const char *iface, const char *reason,
const struct Dhcp_message *dhcpn, const struct Dhcp_message *DHCPO)
=>pid = fork ();
=>if (PID = = 0) execve (options->script, argv, env);//child Process Execution script, default "/system/etc/dhcpcd/dhcpcd-run-hooks"
The Dhcpcd-run-hooks script will decide whether to execute the corresponding file in the system/etc/dhcpcd/dhcpcd-hook/* directory based on the level value.
Our system has the following 3 files in the system/etc/dhcpcd/dhcpcd-hook/* directory
95-configured
20-dns.conf
01-test
= = Parent Process returns while (Waitpid (PID, &status, 0) = =-1) waits for child process script execution to complete
System/extra/dhcpcd-4.0.0-beta9/dhcpcd-hooks/20-dns.conf
System/extra/dhcpcd-4.0.0-beta9/dhcpcd-hooks/95-configured
...
SetProp dhcp.${interface}.ipaddress "${new_ip_address}"
SetProp Dhcp.${interface}.result "OK"//Set property to OK
SetProp Dhcp.${interface}.result "Failed"
...
=============================================================================================================
Inet_init, Tcp_prot
Sock->ops->sendmsg (IOCB, sock, msg, size);
=>inetsw_array[]
=>inet_stream_ops
=>tcp_sendmsg
=============================================================================================================
Wpa_cli.c
=>main
=>wpa_cli_interactive
=>wpa_cli_recv_pending (monitor_conn, 0, 0);//Blocking wait for wpa_supplicant to send data.
= = If Action_monitor is true, some simple machining operations will be performed, otherwise the data sent from Wpa_supplicant will be printed directly to the console [Luther.gliethttp].
Original address: http://www.wangchao.net.cn/it/detail_60528.html
How to monitor WiFi network connection, DHCPCD execution and power power control via JNI under Android