Friday, December 26, 2014

Wildfly EJB With JPA On A Phone

https://www.youtube.com/watch?v=n5dsJ7okcGA













Seconds to the count down:
9 enter Fedora21
8 start Wildfly
7 add database browser
6 Wildfly up
4 database empty
2 run application
0 object in database

My server(my phone) runs the precidio-jndi-calc.tar.gz software, which calculates resonator designs for buyers with their JPA Buyer accounts like this,




. When a visitor does not have an account, the stateful bean creates a temporary account, which can be viewed in the video's H2 console.

The wildfly web interface is http://127.0.0.1:88080 ; database web interface url is  http://127.0.0.1:88080/h2console . JDBC url and password are in /etc/wildfly/standalone/standalone-full.xmljdbc:h2:mem:test and sa respectively.

The precidio-calc.jar's structure is this,
├── Buyer.class
├── META-INF
│   ├── create-script.sql
│   ├── drop-script.sql
│   ├── ejb-jar.xml
│   ├── MANIFEST.MF
│   └── persistence.xml
├── PackagerBean.class
├── PackagerCommonBusiness.class
├── RemoteResonatorCalculator.class
├── RemoteSiliconResonatorCalculator.class
├── ResonatorCalculatorBean.class
└── SiliconResonatorCalculatorBean.class
, which is a standard standalone jar layout, a subset of an EAR. The client layout is this,
├── jndi.properties
├── RemoteCalculatorClient.class
├── RemoteResonatorCalculator.class
└── RemoteSiliconResonatorCalculator.class
, which means that the client does not need to know the bean implementation, just the shell of the different Calculators . The jndi.properties has username and password, which the server side add-user.sh needs to catch up with the client.


The Fedora 21 Wildfly's jar files are split into 2 directories which fails the EJB server startup. To fix it, shell command lines were these, (all these are already done in my Fedora...arm...21-6.tar.gz)
   91  mv /usr/lib/java/hawtjni/* /usr/share/java/hawtjni/
   92  mv /usr/lib/java/hornetq/* /usr/share/java/hornetq/
   93  mv /usr/lib/java/jansi-native/ /usr/share/java/
   94  rmdir /usr/lib/java/hawtjni/
   95  rmdir /usr/lib/java/hornetq/
   96  mv /usr/lib/java/jffi.jar /usr/share/java/
   97  mv /usr/lib/java/jss4.jar /usr/share/java/
   98  mv /usr/lib/java/netty/netty-* /usr/share/java/netty/
   99  rmdir /usr/lib/java/netty/
  100  mv /usr/lib/java/snappy-java/ /usr/share/java/
  101  mv /usr/lib/java/weld-core/* /usr/share/java/weld-core/
  102  rmdir /usr/lib/java/weld-core/
  103  mv /usr/lib/java/wildfly/wildfly-client-all.jar /usr/share/java/wildfly/
  104  cd /usr/lib/java
  106  rmdir wildfly/
  107  cd ../
  108  rmdir java
  109  ln -s /usr/share/java
  129  ln -s /usr/share/java/resteasy/resteasy-json-p-provider-jandex.jar /usr/share/wildfly/modules/system/layers/base/org/jboss/resteasy/resteasy-json-p-provider/main/resteasy-json-p-provider-jandex.jar

I studied the EJB exam and researched on EJB to obtain certification entirely on this phone/tablet/wildfly setting. 

Tuesday, December 9, 2014

An Amazing Dream - typed on the PC phone before getting up

I met my mother in the Starbucks. She got a tan, a toned body, on high heels, approaching my height of 5'11. I walked some yards in my basketball shoes from the plaza of the Home Depot to the Barnes Noble store to meet her and my brother. I asked her about gardening with a species of flower because I didn't know the name of that flower that she used to plant. But she could not recall the name either. I asked my brother , "what is that called in English?" He didn't answer. I said to them that it was time to go back to reading as many books for the afternoon, and maybe one book will reveal the name of the species.

My mother and I embraced and said goodbye, that's how I noticed how tall she was on high heels that day. She tied her hair a pony tail. Her age spot somehow faded blended in with the tanned face. I walked out of the BN store instead of reading the books. The scene was so far all american.

Now it got less american themed, and as I walked back to the plaza of Home Depot back to my car, I tried crossing 2 low fences to shortcut to my car, I got lost in between the parking lots. I started to bump into tall fences and buildings like government facilities. I realized that I ended up in a prison facility. I thought many people must have entered this facility unkowningly or by accident or by a better word here not to be mocked with committing a crime unintentionally. I walked into a house and asked to be pointed to the exit. The prison was in their daily gathering routine. The clerk was a young lady in a blue uniform. She talked to her colleagues saying they have never heard that a person walked in their facility by accident. They started raising suspicion about my identity. She asked me to show my ID. I gave my driver's license, still with my document brief in my underarm, which assured that I was a citizen lay back guy walking down the street.

That was not assuring enough. In side the house, it had partitions made of steel and mesh fences. She told me that she could let me go, but I needed to "reconsider" my action, and "think" clearly. I was confused about the word "think". What did I need to think when I was just walking to my car unless she meant that I was committing a jailbreak? I pulled out my phone with GPS map to figure out how I wound up here. There must be a way to clear the misunderstanding.

Friday, November 28, 2014

Interceptors dependency code path and inherited interceptors

They are 
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
and inside
jboss-interceptors-api_1.1_spec-1.0.0.Final.jar .

For wildfly, the remoting has changed again, port 4447 obsoleted, 8080 now, so the precidio-jndi-calc.tar.gz package is this,
https://drive.google.com/file/d/0B2NfHoyfFf1aRGFlVzdXRXItYVE
, and I have 2 classes, one extends another. My experiment shows that the base object's interceptor is invoked first the the more specific object's interceptor is invoked, like this,
20:58:39,027 INFO  [stdout] (EJB default - 7) *** Intercepting call to baseInterceptor()
20:58:39,029 INFO  [stdout] (EJB default - 7) *** Intercepting call to siliconInterceptor()
.

Calling Stateless Application EJB JARs From Plain Java Code

The stateless application jar is compiled with ejb api. But the invoker should not need the ejb api jars if it can avoid triggering ejb related code, or can it? We have a application for intensive computing farm for intra-red-EM-wave photoresonator calculation of quartz business Precidio Inc. ,


The precidio-jndi-calc.jar has this,
import javax.ejb.Remote;
import javax.ejb.Stateless;

@Stateless
@Remote(RemoteCalculator.class)
public class ResonatorCalculatorBean implements RemoteResonatorCalculator {

    @Override
    public int add(int a, int b) {
        return a + b + 111;
    }

    @Override
    public int subtract(int a, int b) {
        return Math.abs(a - b) - 11;
    }
}
, and we should be able to -cp precidio-calc.jar , instantiate ResonatorCalculatorBean, and run the add command. This is the essence of EJB.

What is the problem, then, when -cp precidio-calc.jar ? 

[root@android01 ~]# cat UseEjb.java 

import CalculatorBean;

public class UseEjb {

public static void main (String [] args) {

System.out.println("ok");

CalculatorBean cb = new CalculatorBean();

System.out.println(cb.add ( 1, 2));

}

[root@android01 ~]# javac -cp precidio-jndi-calc/build/precidio-calc.jar UseEjb.java
UseEjb.java:1: error: '.' expected
import CalculatorBean;
                     ^
UseEjb.java:1: error: ';' expected
import CalculatorBean;
                      ^
2 errors
[root@android01 ~]#
Why? Non-packaged classes can not be imported. Instead, use it without importing it,
[root@android01 ~]# cat UseEjb.java 
public class UseEjb {
public static void main (String [] args) {
System.out.println("ok");
CalculatorBean cb = new CalculatorBean();
System.out.println(cb.add ( 1, 2));
}
[root@android01 ~]# javac -cp precidio-jndi-calc/build/precidio-calc.jar UseEjb.java
jndi.new/build/john-calc.jar(CalculatorBean.class): warning: Cannot find annotation method 'value()' in type 'Remote': class file for javax.ejb.Remote not found
1 warning
[root@android01 ~]# java -cp precidio-jndi-calc/build/precidio-calc.jar:. UseEjb
ok
3
[root@android01 ~]#java -cp precidio-jndi-calc/build/precidio-calc.jar UseEjb
Error: Could not find or load main class UseEjb
[root@android01 ~]# 

As predicted, as long as the invoker don't touch EJB specific workings, the regular java interpreter can invoke ejb jar without incident. It has a warning at compile time.

This exercise actually exposes the defect of java cp. The cp actually disturbs the java interpreter's original work path. Original java interpreter looks at current working directory in search for a class file, UseEjb in this case. So, simple java UseEjb does not have error of "Cloud not find" UseEjb. When -cp argument is in, it erases the default looking at current working directory.

Monday, November 10, 2014

The internals of running Fedora22 in a large screen phone.

All the internals are included in my Fedora...21-6.tar.gz and no need to do it if you just extract my Fedora...22-6.tar.gz .

Stop process killer

If you replace the adjusting of process killing priorities in starts.sh with below one line,
echo '0,0,0,0,0,0' > /sys/module/lowmemorykiller/parameters/minfree
, your desktop mate will not be killed when you switch to android. But with my 2g memory with android 5.1 , I often run out of memory with just 3 apps, like a browser and a map and a music player and the system freezes requiring reset.

Run X with mate session


Put a am start -n com.package.name/com.package.name.ActivityName
in /data/local/fedora/startx.sh .  ActivityName is often “MainActivity”. This is needed because the Startup app often can’t time the startup sequence and the XSDL X app needs time before accepting mate session. startx.sh can also periodically set XSDL priority to -17 to prevent app closing by android system. This is already included in my Fedora22...5.tar.gz,
# cat /mnt/tmp/bin/android-startx.sh
#!/system/bin/sh
am start -n x.org.server/x.org.server.MainActivity
# the 3 minute sleep allows the android's process killer to kill off
# unused apps before we enter the Desktop mode when 000000 cancels
# all killings.
sleep 180
echo '0,0,0,0,0,0' > /sys/module/lowmemorykiller/parameters/minfree

Chroot enter the PC operating system

# cat /mnt/tmp/bin/android-enter-chroot-fedora.sh
#!/system/bin/sh
export fedora="/data/local/chroots/fedora"
/system/xbin/busybox mount -t proc proc $fedora/proc
/system/xbin/busybox mount --bind /sys $fedora/sys
/system/xbin/busybox mount --bind /dev $fedora/dev
/system/xbin/busybox mount -t devpts devpts $fedora/dev/pts
#/system/xbin/busybox mount --bind /storage/sdcard1 $fedora/root/SDCard
export TERM=vt100
export HOME=/root
export PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin:.
export SHELL=/usr/bin/bash
export EDITOR=vi
if [ ! -d /dev/shm ] ; then /system/xbin/busybox mkdir /dev/shm ; fi
/system/xbin/busybox chroot $fedora $SHELL -l



Run Mate' desktop

At chroot entering the PC operating system, which includes login, the root account's bash init script is responsible to invoke mate-session .
[root@android01 ~]# tail .bash_profile
if ! test -d /dev/shm ; then mkdir /dev/shm ; fi
export HOSTNAME=android01
hostname android01
export DISPLAY=:0
if test -z "`pidof sshd`" ; then /usr/sbin/sshd; fi
if test -z "`pidof mate-session`" ; then mate-session & fi 2>/dev/null
if test -z "`pidof Xvnc`" ; then vncserver -geometry 1920x1080 -localhost ; fi
[root@android01 ~]#

Development work 

For smooth terminal without "Queue background data", disable Xperia's Settings->Power Management->Queue background data, disable the Settings->WiFi->Settings-> Advanced->WiFi optimization to save power.
You can't edit source code through WIFI to the phone when vim's key strokes are delayed and come in bursts. Disable the queuing option is a must.

Flash player and chromium browser

Archlinux generously gives out builds at http://us.mirror.archlinuxarm.org/armv7h . And I donated to it multiple times. I have also subscribed to RedHat enterprise for 1 year, which the payout should reach Fedora developers.

 More internal works 

The source image we receive from redhat is often a dd image dump of a working fedora arm installation, and we are expected to be able to mount the filesystem inside the dd raw image when the raw image is burned to a USB flash. In an android phone, the mouting utility may or may not be able to mount ext4 or other file systems due to pared down phone kernel. So, we need to mount it with a desktop pc linux. With a desktop pc, we don't need to burn USB, and we can just mount with offset to the root partition of the raw image. To figure out the offset, use fdisk to look at the raw image. The starting block number of the root partition times the number of bytes per block is the offset.  For example,
mount -o offset=4096 Fedora-sda.raw /tmp/chroots/fedora 
, assuming root partition starts at block 8, and block size is 512.

Tuesday, October 21, 2014

Root xperia 3 times to get through & flashing tips

Rooting

This may make you laugh, but I had to run the Easy Root install.sh 3 times (I need to be honest and blunt. The google hosting says this is infected with virus. I put together xda's zxz0O0 easy root and towel root together. For linux use, I have not experienced any trouble. Maybe the virus is for windows. I don't know how the google virus detection works. Maybe there is no virus at all.)

From the tool's link,
 http://forum.xda-developers.com/showthread.php?t=2784900
.

First run, it would be stuck, so I waited 20 minutes at
------------------------------------------
creating vm (loljavasucks)
------------------------------------------
. I unplugged USB cable to run it the second time, and it would be stuck and I had to waite another 20 minutes at
------------------------------------------
cleaning
------------------------------------------
. Then I unplugged USB cable again to run it the third time, and it would finish quickly.

My tip: I have tried root checker while the install.sh is still stuck and have seen that root is already broken in while the script is hang. The last restart just checks the root. My linux PC is a chromebook with fedora21 https://docs.google.com/file/d/0B2NfHoyfFf1aUFE1ckQ0Ty15MU0/edit?usp=docslist_api(md5 sum ...) in chroot (in the top directory inside the chroot, the startfedora.sh shell script starts fedora and full desktop using the chroot's /root/.bash_profile script).

Flashing Distribution

64bit  adb inside flashtool has problem. So, modify the invoke script,
[root@localhost FlashTool]# diff FlashTool.bak FlashTool
4c4
< export system64=$(uname -m)
---
> export system64='x86'


And the GUI will end up running in 32bit. So, it depends on these 5 32bit rpm packs,
Oct 21 19:23:45 Installed: libXcomposite-0.4.4-4.fc20.i686
Oct 21 19:23:45 Installed: avahi-libs-0.6.31-21.fc20.i686
Oct 21 19:23:45 Installed: 1:cups-libs-1.7.0-4.fc20.i686
Oct 21 19:23:46 Installed: atk-2.10.0-1.fc20.i686
Oct 21 19:23:47 Installed: gtk2-2.24.22-2.fc20.i686

.

In various sources, they say that adb driver is needed, but Fedora has the android-tools rpm package that includes adb. I had to check the "Unknow Source" to enable in android xperia because towel root installs an apk to xperia. The FlashTool says use the "back button" to enter flash mode, but the xperia uses volume down instead.

So, here is the link 
https://drive.google.com/file/d/0B2NfHoyfFf1aWUM3TDNlUlViRHM
to the C6806_14.3 681 Sony distribution.


The flashtool is https://drive.google.com/file/d/0B2NfHoyfFf1aNFYyNnhGRDdzZTg


Flashing Bootloader

The CyanogenMod "recovery" is also a Linux kernel that supports file system listing/mounting so that it can be used to flash a distribution onto the disc. The kernel is the boot.img inside of https://drive.google.com/file/d/0B2NfHoyfFf1aYk1oYnFyTXB5NFk distribution, which is for companion Google apps at https://drive.google.com/file/d/0B2NfHoyfFf1abDlCc1lwV3M5dXc
. The CyanogenMod AOSP distribution does not have DRM which precludes google play's movie/TV app.

The linux command to flash the bootloader is
fastboot flash boot boot.img
, but the bootloader is guarded by the sony corporation using IMEI as a variable. So, it needs extra steps with the fastboot command.

When using the "recovery" to flash the disc, the distribution to use is the said distribution.

Friday, October 17, 2014

SSL BIO research better on armhfp image of Fedora 20 than on x86_64

It is strange that HP's code sample for SSL/BIO programming
http://h71000.www7.hp.com/doc/83final/ba554_90007/ch05s03.html
http://h71000.www7.hp.com/doc/83final/ba554_90007/ch05s04.html
readily compile without error in my Xperia ARM with Fedora 20 and 21 armhfp image.

In Fedora 20 x86, the same code got error about converting char to some struct .

Compile them with gcc -lssl -lcrypto client.c . You need to yum install openssl-devel first.
Generate cert and key with openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes
client.c
#include 
#include 
#include 
#include 
#include 
#ifdef __VMS
#include 
#include 

#include 
#else
#include 
#include 
#include 
#include 
#endif

#include 
#include 
#include 

#define RETURN_NULL(x)                                                         \
  if ((x) == NULL)                                                             \
  exit(1)
#define RETURN_ERR(err, s)                                                     \
  if ((err) == -1) {                                                           \
    perror(s);                                                                 \
    exit(1);                                                                   \
  }
#define RETURN_SSL(err)                                                        \
  if ((err) == -1) {                                                           \
    ERR_print_errors_fp(stderr);                                               \
    exit(1);                                                                   \
  }

static int verify_callback(int ok, X509_STORE_CTX *ctx);

#define RSA_CLIENT_CERT "client.crt"
#define RSA_CLIENT_KEY "client.key"

#define ON 1
#define OFF 0

void main() {
  int err;

  int sock;
  struct sockaddr_in server_addr;
  char *str;
  char buf[4096];
  char hello[80];

  SSL_CTX *ctx;
  SSL *ssl;
  SSL_METHOD *meth;
  X509 *server_cert;
  EVP_PKEY *pkey;

  short int s_port = 5555;
  const char *s_ipaddr = "127.0.0.1";

  /*----------------------------------------------------------*/
  printf("Message to be sent to the SSL server: ");
  fgets(hello, 80, stdin);

  /* Load encryption & hashing algorithms for the SSL program */
  SSL_library_init();

  /* Load the error strings for SSL & CRYPTO APIs */
  SSL_load_error_strings();

  /* Create an SSL_METHOD structure (choose an SSL/TLS protocol version) */
  meth = SSLv3_method();

  /* Create an SSL_CTX structure */
  ctx = SSL_CTX_new(meth);

  RETURN_NULL(ctx);

  /* ------------------------------------------------------------- */
  /* Set up a TCP socket */

  sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

  RETURN_ERR(sock, "socket");

  memset(&server_addr, '\0', sizeof(server_addr));
  server_addr.sin_family = AF_INET;

  server_addr.sin_port = htons(s_port); /* Server Port number */

  server_addr.sin_addr.s_addr = inet_addr(s_ipaddr); /* Server IP */

  /* Establish a TCP/IP connection to the SSL client */

  err = connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr));

  RETURN_ERR(err, "connect");
  /* ----------------------------------------------- */
  /* An SSL structure is created */

  ssl = SSL_new(ctx);

  RETURN_NULL(ssl);

  /* Assign the socket into the SSL structure (SSL and socket without BIO) */
  SSL_set_fd(ssl, sock);

  /* Perform SSL Handshake on the SSL client */
  err = SSL_connect(ssl);

  RETURN_SSL(err);

  /* Informational output (optional) */
  printf("SSL connection using %s\n", SSL_get_cipher(ssl));

  /* Get the server's certificate (optional) */
  server_cert = SSL_get_peer_certificate(ssl);

  if (server_cert != NULL) {
    printf("Server certificate:\n");

    str = X509_NAME_oneline(X509_get_subject_name(server_cert), 0, 0);
    RETURN_NULL(str);
    printf("\t subject: %s\n", str);
    free(str);

    str = X509_NAME_oneline(X509_get_issuer_name(server_cert), 0, 0);
    RETURN_NULL(str);
    printf("\t issuer: %s\n", str);
    free(str);

    X509_free(server_cert);

  } else
    printf("The SSL server does not have certificate.\n");

  /*-------- DATA EXCHANGE - send message and receive reply. -------*/
  /* Send data to the SSL server */
  err = SSL_write(ssl, hello, strlen(hello));

  RETURN_SSL(err);

  /* Receive data from the SSL server */
  err = SSL_read(ssl, buf, sizeof(buf) - 1);

  RETURN_SSL(err);
  buf[err] = '\0';
  printf("Received %d chars:'%s'\n", err, buf);

  /*--------------- SSL closure ---------------*/
  /* Shutdown the client side of the SSL connection */

  err = SSL_shutdown(ssl);
  RETURN_SSL(err);

  /* Terminate communication on a socket */
  err = close(sock);

  RETURN_ERR(err, "close");

  /* Free the SSL structure */
  SSL_free(ssl);

  /* Free the SSL_CTX structure */
  SSL_CTX_free(ctx);
}



server.c
#include 

#include 

#include 
#include 
#include 
#include 
#ifdef __VMS
#include 
#include 
#include 
#include 
#else
#include 
#include 
#include 
#include 
#endif
#include 
#include 
#include 
#define RSA_SERVER_CERT "server.crt"
#define RSA_SERVER_KEY "server.key"
#define ON 1
#define OFF 0
#define RETURN_NULL(x)                                                         \
  if ((x) == NULL)                                                             \
  exit(1)
#define RETURN_ERR(err, s)                                                     \
  if ((err) == -1) {                                                           \
    perror(s);                                                                 \
    exit(1);                                                                   \
  }
#define RETURN_SSL(err)                                                        \
  if ((err) == -1) {                                                           \
    ERR_print_errors_fp(stderr);                                               \
    exit(1);                                                                   \
  }
void main() {
  int err;
  int listen_sock;
  int sock;
  struct sockaddr_in sa_serv;
  struct sockaddr_in sa_cli;
  size_t client_len;
  char *str;
  char buf[4096];
  SSL_CTX *ctx;
  SSL *ssl;
  SSL_METHOD *meth;

  X509 *client_cert = NULL;
  short int s_port = 5555;
  /*----------------------------------------------------------------*/
  /* Load encryption & hashing algorithms for the SSL program */
  SSL_library_init();
  /* Load the error strings for SSL & CRYPTO APIs */
  SSL_load_error_strings();
  /* Create a SSL_METHOD structure (choose a SSL/TLS protocol version) */
  meth = SSLv3_method();
  /* Create a SSL_CTX structure */
  ctx = SSL_CTX_new(meth);
  if (!ctx) {
    ERR_print_errors_fp(stderr);
    exit(1);
  }
  /* Load the server certificate into the SSL_CTX structure */
  if (SSL_CTX_use_certificate_file(ctx, RSA_SERVER_CERT, SSL_FILETYPE_PEM) <=
      0) {
    ERR_print_errors_fp(stderr);
    exit(1);
  }
  /* Load the private-key corresponding to the server certificate */
  if (SSL_CTX_use_PrivateKey_file(ctx, RSA_SERVER_KEY, SSL_FILETYPE_PEM) <= 0) {
    ERR_print_errors_fp(stderr);
    exit(1);
  }
  /* Check if the server certificate and private-key matches */
  if (!SSL_CTX_check_private_key(ctx)) {
    fprintf(stderr, "Private key does not match the certificate public key\n");
    exit(1);
  }
  /* ----------------------------------------------- */
  /* Set up a TCP socket */
  listen_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  RETURN_ERR(listen_sock, "socket");
  memset(&sa_serv, '\0', sizeof(sa_serv));
  sa_serv.sin_family = AF_INET;
  sa_serv.sin_addr.s_addr = INADDR_ANY;
  sa_serv.sin_port = htons(s_port); /* Server Port number */
  err = bind(listen_sock, (struct sockaddr *)&sa_serv, sizeof(sa_serv));
  RETURN_ERR(err, "bind");

  /* Wait for an incoming TCP connection. */
  err = listen(listen_sock, 5);
  RETURN_ERR(err, "listen");
  client_len = sizeof(sa_cli);
  /* Socket for a TCP/IP connection is created */
  sock = accept(listen_sock, (struct sockaddr *)&sa_cli, &client_len);
  RETURN_ERR(sock, "accept");
  close(listen_sock);
  printf("Connection from %lx, port %x\n", sa_cli.sin_addr.s_addr,
         sa_cli.sin_port);
  /* ----------------------------------------------- */
  /* TCP connection is ready. */
  /* A SSL structure is created */
  ssl = SSL_new(ctx);
  RETURN_NULL(ssl);
  /* Assign the socket into the SSL structure (SSL and socket without BIO) */
  SSL_set_fd(ssl, sock);
  /* Perform SSL Handshake on the SSL server */
  err = SSL_accept(ssl);
  RETURN_SSL(err);
  /* Informational output (optional) */
  printf("SSL connection using %s\n", SSL_get_cipher(ssl));
  /*------- DATA EXCHANGE - Receive message and send reply. -------*/
  /* Receive data from the SSL client */
  err = SSL_read(ssl, buf, sizeof(buf) - 1);
  RETURN_SSL(err);
  buf[err] = '\0';
  printf("Received %d chars:'%s'\n", err, buf);
  /* Send data to the SSL client */
  err = SSL_write(ssl, "This message is from the SSL server",
                  strlen("This message is from the SSL server"));
  RETURN_SSL(err);
  /*--------------- SSL closure ---------------*/
  /* Shutdown this side (server) of the connection. */
  err = SSL_shutdown(ssl);
  RETURN_SSL(err);
  /* Terminate communication on a socket */
  err = close(sock);
  RETURN_ERR(err, "close");
  /* Free the SSL structure */
  SSL_free(ssl);
  /* Free the SSL_CTX structure */
  SSL_CTX_free(ctx);
}

Tuesday, October 7, 2014

The Red Pill For Modern Phones

https://www.youtube.com/watch?v=BmSwO3DZPsw

A sturdy, portable phone stand that suspends a large screen phone above the keyboard and at comfortable eye level as a home PC monitor exists, and is needed to use a large screen phone as a home PC. It has a US patent number.



Using Google Drawing in this PC phone with Sony Xperia Z Ultra 6.4 inch on the go is a bliss.




Instruction: Start out with installing Busybox Pro by stericson and Android market app XSDL by pelya to run the PC's desktop program set - the task bar, the main menu, the wallpaper, etc. The desktop program set in the above screenshot is the linux Mate' Desktop. You need a terminal emulator app.

Download the chroot package (size is about 2.4GB) https://drive.google.com/file/d/0B2NfHoyfFf1aNkZLUldNSVRiWk0 for Fedora 24. MD5 sum is ff0b47e8...

Fedora-Workstation-armhfp-24-101-chroot.tar.gz is the root filesystem from Fedora24’s ARM main release image plus chromebook chroot utilities from the "crouton" project. It is the bin and chroots branches of crouton layout when you extract the tar gz file. The tar.gz package is not easy to create because it needs unmount /proc to avoid zipping millions of files of the process info files of the entire phone's life processes while frequently mount /proc and others to modify the fedora system. A few other enhancements,
  1. sshd startup is added to chroot login /root/.bash_profile . You need to initiate the sshd system by running sshd-keygen to allow spresenting sh fingerprint of your unique Fedora installation, and set root password to allow login. Set your password with the command line command passwd. The sshd continues to run even after the X server is killed by android operating system or manually closed because sshd is not derived from the XSDL process, rather it is derived from your terminal emulator app that lives throughout the android system's boot life until android reboot. So, the sshd is a 24x7 file server. The file server can serve directories outside the chroot as discussed in another post about the internal machinery of this system.
  2. Installed @mate group software. And mate-session is invoked when entering the chroot with the tar.gz package's bin/android-enter-chroot-fedora.sh . Installed daemonize. Remember the chroot does not have a systemctl, you need to make daemons manually or run with the .bash_profile login script. These are for the everyday use of the system with GUI. The DISPLAY and PULSE_SERVER variables are set in .bash_profile, so that the GUI session as well as sound is delivered to the local phone's screen and speaker/headphone.
  3.  Installed icedtea-web java plugin for Firefox. Wildfly installed, which includes openjdk-devel and all jboss libraries. gcc-c++ installed. openssl-devel installed. These are for a developer's convenience.
  4. Installed gimp, wireshark-gnome, rdesktop, tcl, tk, xterm, liberation narrow fonts. gimp is the photoshop of the Linux world. The narrow fonts allow enlarged text word, like "Computer", to avoid line breaks in the middle of a word.
  5.  8.8.8.8 and 8.8.4.4 and 4.4.4.4 DNS servers have been added to resolv.conf . 
  6. Changed GUI theme to have the thick edge of windows so that mouse cursor can hit the resizing edge in the small phone screen. 
  7. Removed bottom panel to expand desktop height for small phone screen. Moved bottom panel's applets to top panel. Changed top panel's main menu to a single icon menu to save space.
  8. Saved android-enter-chroot.sh and android-startx.sh to android’s /data/local/bin/ . Added the many paths of the android system, like busybox's /system/xbin/ and /system/bin/ to chroot environment variable in android-enter-chroot.sh so that the chroot action can succeed in most android systems where utilities reside in different locations.
  9. Cached whole fedora release software info. Then /etc/dnf/dnf.conf sets metadata_expire=never , so that cell phone internet connection does not poll the whole fedora software package info everytime you want to install or search software. /etc/yum.repo.d/fedora-update.repo set to disabled, so that the system is more stable without changing the base system when you install new software. 
  10.  Installed vncviewer , vncserver. vncserver is started via .bash_profile to serve local connections when the chroot starts. To enable in the server, enter your desired vnc password when you open Terminal Emulator because the vncserver startup is part of the chroot login process in /root/.bash_profile script. To use the local connection from remote client, you need to ssh to the phone with "ssh -L 5901:localhost:5901 root@phone-ip-address" , then vncviewer connect to localhost:1 from the remote host. You can not directly connect vncviewer to phone-ip-address due to Fedora24's default secure configuration of disallowing remote connections. Notice: once you enable the server, the server is very power intensive and drains battery. To disable the server, comment out the last line that starts vncserver in /root/.bash_profile.
All above points are included in tar.gz . So, just tar -xzf extract the downloaded tar.gz file when you are under the /data/local/ directory.

Release note: The Mate file manager caja has problem recognizing the android flash file system as write-able due to the said no-systemctl situation. So, copying files with caja fails with the local chroot system. To work around, use caja to ssh to the chroot itself at 127.0.0.1 and copy files as a remove system in the local system in caja. Command line terminal is not affected by this caja problem.  

Disclaimer: I am not responsible for damaging your phone with this instruction. Removing the chroot has risks of damaging your phone. Before removing the chroot files, you need to temporarily disable entering chroot and reboot the phone so that the android system's /dev is not mounted when you remove chroot files. Removing /dev files, even if it is mounted to chroot, may damage the phone. 

The fedora chroot can be invoked from Terminal Emulator, which can be, in turn, started by android’s Startup app. The Terminal Emulator needs to have initial command
su -c /data/local/bin/android-startx.sh& sleep 15;
su -c /data/local/bin/android-enter-chroot-fedora.sh; 
, for startup to automatically enter fedora.
Now, restart your PC phone and it will boot directly into PC desktop.


This phone PC setup took me close to re-certify my CCIE using CCDE written the second attempt in year 2014. Also I studied for the Oracle EJB expert exam and researched Wildfly EJB and obtained the certification entirely on this chroot.

The internals of the tar.gz will be in another post. All the internals are included in my tar.gz and no need to read the other post if you just extract it.