What time is it? Although we do not talk about it much today, Linux systems (and more generically,

13.3 What time is it? Although we do not talk about it much today, Linux systems (and more generically,

Unix systems) have a service running that provides the server’s current date and time. This application, known as a daytime server, typically runs as a daemon, meaning in the background and not connected to a particular shell. For our purposes, we will implement a basic daytime server for Android/Linux, but we won’t worry about turn- ing it into a background service.

This application helps exercise our interest in developing Android/Linux applica- tions. First and most important, this is an application of some significance beyond a simple printf statement. Second, once this application is built we write an Android/ Java application to interact with the daytime server.

13.3.1 Daytime Server application Our Daytime Server application has a very basic function. The application listens on a

TCP port for incoming socket connections. When a connection is made, the applica- tion writes a short textual string representation of the date and time via the socket, closes the socket, and then returns to listening for a new connection.

In addition to the TCP socket interactions, our application logs requests to

a SQLite database. Why? Because we can! The purpose of this application is to demonstrate nontrivial activities in the Android/Linux environment, including the use of the SQLite system library. Let’s get started with examining the Daytime Server application.

13.3.2 daytime.c The Daytime Server application can be broken into two basic functional parts. The

first is the TCP socket server. Our Daytime Server application binds to TCP port 1024 when looking for new con- nections. Ordinarily a daytime service binds to TCP port 13; however, Linux has a security feature where only trusted users can bind to any port below 1023. The second feature is the insertion of data into a SQLite database. Listing 13.8 shows the code for the Daytime Server application.

C HAPTER 13 Hacking Android

Listing 13.8 daytime.c

#include <time.h> #include <stdio.h> #include <string.h> #include <errno.h>

B Required

#include <arpa/inet.h>

headers

#include <netinet/in.h> #include <sys/socket.h> #include <resolv.h> #include "sqlite3.h"

int PORTNUMBER = 1024;

C Listening port number

#define htons(a) ( ((a & 0x00ff) << 8) | ((a & 0xff00) >> 8))

D Define helpful macro

void RecordHit(char * when) {

int rc; sqlite3 *db; char *zErrMsg = 0; char sql[200]; rc = sqlite3_open("daytime_db.db",&db); if( rc ) {

printf( "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return;

SQLite E E

interaction

bzero(sql,sizeof(sql)); sprintf(sql,"insert into hits values (DATETIME('NOW'),'%s');",when); rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg); if( rc!=SQLITE_OK ) {

printf( "SQL error: %s\n", zErrMsg); }

sqlite3_close(db); }

int main(int argc, char **argv) { int listenfd, connfd; struct sockaddr_in servaddr; char buf[100]; time_t ticks; int done = 0; int rc; fd_set readset; int result; struct timeval tv;

printf("Daytime Server\n");

F Set up and listen

listenfd = socket(AF_INET,SOCK_STREAM,0);

on socket

bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = AF_INET;

What time is it?

servaddr.sin_addr.s_addr = INADDR_ANY; servaddr.sin_port = htons(PORTNUMBER);

rc = bind(listenfd, (struct sockaddr *) &servaddr,sizeof(servaddr)); if (rc != 0) {

printf("after bind,rc = [%d]\n",rc); return rc;

F Set up and listen

listen(listenfd,5);

on socket

while (!done) {

printf("Waiting for connection\n"); while (1) {

bzero(&tv,sizeof(tv)); tv.tv_sec = 2; FD_ZERO(&readset); FD_SET(listenfd, &readset); result = select(listenfd + 1, &readset, &readset, NULL, &tv); if (result >= 1) {

printf("Incoming connection!\n"); break;

} else if (result == 0) {

printf("Timeout.\n"); continue;

} else {

printf("Error, leave.\n"); return result;

printf("Calling accept:\n"); connfd = accept(listenfd,

G Accept socket

(struct sockaddr *) NULL, NULL);

connection

printf("Connecting\n"); ticks = time(NULL); sprintf(buf,"%.24s",ctime(&ticks)); printf("sending [%s]\n",buf); write(connfd,buf,strlen(buf)); close(connfd); RecordHit(buf);

H Record activity

} return 0;

As with many C language applications, a number of headers B are required, includ-

ing definitions and prototypes for time functions, SQLite functions, and of course a number of headers required for TCP sockets. Note that the sqlite3.h header file is not provided in the CodeSourcery tool chain. This file was acquired from a sqlite3 distri- bution, and the file was copied into the local directory along with daytime.c. This is

C HAPTER 13 Hacking Android

why the include file is delimited with quotation marks rather than <>, which is used for finding include files in the system or compiler path. The htons function is typically implemented in the library named socket (libsocket.so). Android does not provide this library, nor was this found in any of the system libraries. Therefore htons is

defined here as a macro D . This macro is required to get the network byte ordering

correct. When the application is running, this port can be verified by running net- stat –tcp on the command line in the adb shell.

The standard TCP port for a daytime server is port 13. In C , application is using

port 1024 because our application cannot bind to any port numbered 1023 or below. Only system processes may bind to ports below 1024.

In the RecordHit function, we see SQLite interaction E . The RecordHit() func-

tion is responsible for inserting a record into the SQLite database created for this application.

Jumping into the main function, we see the socket functions in use to listen on a

socket for incoming connections F . When a connection is accepted G , the current

system time is sent to the calling client. After this, the application makes a record of

the transaction by calling the RecordHit function H .

That’s all the code necessary to implement our Android/Linux Daytime Server application. Let’s look next at the SQLite3 database interaction in more detail.

13.3.3 The SQLite database This application employs a simple database structure created with the sqlite3 applica-

tion. We interact with sqlite3 from the adb shell environment, as shown in figure 13.7.

Figure 13.7 Sqlite3 from the command line in the adb shell

What time is it?

The purpose of this database is to record some data each time Daytime Server pro- cesses an incoming request. From a data perspective this sample is a bit boring as it simply records the system time plus the text returned to the client, which is a ctime formatted time string. Though somewhat redundant from a data perspective, the pur- pose is to demonstrate the use of SQLite from our C application, utilizing the Android/Linux resident sqlite3 library, libsqlite.so.

The previous section of code outlined the syntax for inserting a row into the data- base; this section shows how to interact with the database using the sqlite3 tool. The sequence shown in figure 13.7 is broken out and explained in listing 13.9.

Listing 13.9 Interacting with a sqlite database

# pwd pwd /data/ch13

B Connect to our

# sqlite3 daytime_db.db

database file

sqlite3 daytime_db.db SQLite version 3.5.0 Enter ".help" for instructions sqlite> .databases .databases seq name file --- --------------- -------------------------------------------------

0 main /data/ch13/daytime_db.db

Examine database

sqlite> .tables

structure

.tables hits sqlite> .schema hits .schema hits CREATE TABLE hits (hittime date,hittext text);

D The Create statement

sqlite> .header on .header on sqlite> .mode column .mode column sqlite> select * from hits;

E Select rows

select * from hits; hittime hittext ------------------- ------------------------ 2008-07-29 07:31:35 Tue Jul 29 07:31:35 2008 2008-07-29 07:56:27 Tue Jul 29 07:56:27 2008 2008-07-29 07:56:28 Tue Jul 29 07:56:28 2008 2008-07-29 07:56:29 Tue Jul 29 07:56:28 2008 2008-07-29 07:56:30 Tue Jul 29 07:56:30 2008 sqlite> .exit .exit #

The SQLite database operates in a similar fashion to other, modern SQL-based envi- ronments. In listing 13.9 we see the output from an interactive session where the data-

base for this chapter’s sample application is opened B . A series of commands given at the sqlite> prompt C display the contents of the database in terms of structure. The

schema command dumps the Data Definition Language for a particular table. In this

C HAPTER 13 Hacking Android

case, we see the CREATE TABLE instructions for the hits table D . Viewing the data is

simple with the use of the familiar select statement E .

The SQLite database engine is known for its simplicity. This section displayed a sim- ple interaction and just how easy it is to employ. In addition, the SQLite3 database may

be pulled from the Android Emulator and used on the development machine, as shown in figure 13.8.

Figure 13.8 The SQLite database on the development machine

This feature makes Android a very compelling platform for mobile data collection applications because synching data can be as simple as copying a database file that is compatible across multiple platforms.

13.3.4 Building and running Daytime Server To build this application we need to combine the components of the prior few sec-

tions. We know that our application requires a startup component and must also link against multiple libraries. Because the application interacts with the SQLite database, we must link against the sqlite library in addition to the c and android_runtime librar- ies. The full build script is shown in listing 13.10.

Listing 13.10 Daytime application build script

arm-none-linux-gnueabi-gcc -c daytime.c

B Compile daytime.c

arm-none-linux-gnueabi-gcc -c -o crt0.o crt.S

C Compile crt.S

arm-none-linux-gnueabi-ld --entry=_start --dynamic-linker /system/bin/linker -

nostdlib -rpath /system/lib -rpath-link \android\system\lib -L \android\system\lib -l c -l android_runtime -l sqlite -o daytime daytime.o crt0.o

C:\software\google\<path to android sdk>\tools\adb

D Link the application

push daytime /data/ch13

g:\tools\adb shell "chmod 777 /data/ch13/daytime"

E Install application

What time is it?

The build script begins by compiling the main source file, daytime.c B . The next line

compiles the crt.S file, which was introduced in listing 13.7 for our C runtime initial-

ization C . The linker command contains a number of switches to create the desired application. Note the parameter to the linker in D to include the sqlite library. Note

also the inclusion of both daytime.o and crt0.o object files as inputs to the linker. Both are required to properly construct the Daytime Server application. The input files are found in local (to the development machine) copies of the libraries. adb is employed to push the executable file to the Android Emulator and to modify the permissions,

saving a manual step E .

Running the Daytime Server application is the easy and fun part of this exercise. Figure 13.9 shows our Daytime Server running.

Figure 13.9 Daytime Server running in the shell

Here is a rundown of the sequence shown in figure 13.9:

1 Start the shell by running adb shell.

2 Change directories to /data/ch13, where our application resides, previously pushed there with an adb push command.

C HAPTER 13 Hacking Android

3 Run the ./daytime application.

4 The application binds to a port and begins listening for an incoming connection.

5 A timeout occurs prior to a connection being made. The application displays the timeout and returns to look for connections again.

6 A connection is detected and subsequently accepted.

7 The time string is constructed and sent to the client.

8 A record is inserted into the database with the shown sql statement.

9 We kill the application and restart the shell. Note that this is because we did not build a clean way of killing the Daytime Server. A proper version of the applica- tion would be to convert it to a daemon, which is beyond the scope of our inter- est here.

10 Run sqlite3 to examine the contents of our application’s database.

11 Perform a select against the hits table, where we see the recently inserted record.

We have built an Android/Linux application that implements a variant of the tradi- tional daytime server application as well as interacts with a SQL database. Not too shabby when you consider that this is a telephone platform! Let’s move on to examine the Android/Java application used to exercise the Daytime Server, our Daytime Client.