You are currently browsing the category archive for the ‘coding’ category.

Through one of my colleagues I learned yesterday about the infamous iOS SSL bug that resulted in iOS devices accepting any certificates whether they were correct or incorrect. This could allow an attacker or man in the middle to eavesdrop or intercept traffic theoretically secured through, for example, https.

I am not going to write today about what the bug does and the potential impact. I will, however, highlight the fact that this bug seems to have gone unnoticed since iOS 6 in 2012, which is quite scary. If you are interested in the bug and more details on the media burst it has created, you can read about it here, here or here.

I want to focus specifically on what the bug was. This bug that has terrifying consequences is just a basic and simple human mistake, probably originated at a classic copy-paste of code. Let’s look at the code, which I found here and is, in turn, from the Apple’s published open source code (which, obviously, is already fixed).

static OSStatus
SSLVerifySignedServerKeyExchange(SSLContext *ctx, bool isRsa, SSLBuffer signedParams,uint8_t *signature, UInt16 signatureLen)
    OSStatus        err;

    if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
        goto fail;

    if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
        goto fail;
        goto fail;

    if ((err =, &hashOut)) != 0)
        goto fail;

    return err;

Essentially, after the second check, the line of code that goes to fail is repeated. Therefore, the third and last check for the hash is never executed and this subroutine always goes to fail. As you can see, this is not the fanciest bug ever. On the contrary, it is most likely a classic copy-paste human error.

I have always been very particular when coding in C and Java and I ALWAYS use {} for condition statements. So, although this

if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
    goto fail;

is exactly the same as this

if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0){
    goto fail;

using the latter would have avoided this bug. So, long story short, the conclusion is: always use {}. And a related corollary, vi and vim for Unix are cool and you look very cool and smart using them, but always use an IDE when coding. They are very smart and helpful. An IDE would have highlighted in bright annoying yellow the third hash check and labeled it as “dead code“. If you are a Unix user, I recommend Eclipse.

It took me a while to figure this out. I have an app that I coded and it runs a service in the background. Given a specific event, I want to show an alert on the screen. How to do it?

All the ways I tried would work nicely, but the alert would only pop up when I opened the activity that started the service in the background. My goal was to have a “global alert” that will show up on the screen right then and there, no matter what the user is doing or what activity is controlling the screen. And, if the screen is locked, the alert should be displayed as soon as the user unlocks the phone.

Here is how you do it:

  • First create a new class (activity). We will call it displayAlert:
public class displayAlert extends Activity {

    private boolean doDisplayAlert;

    private static final boolean D = true;
    private static final String TAG = "tagYouUseForYourApp";

    public void onCreate(Bundle savedInstanceState) {

        if(D) Log.i(TAG, "+++ ALERT starting alert class. +++");
        if(D) Log.i(TAG, "+++ ALERT getting Intent. +++");

        //Get intent and boolean "proceed" field within.
        Bundle bundle = getIntent().getExtras();
        displayAlert = bundle.getBoolean("proceed");

        if(D) Log.i(TAG, "+++ ALERT got Intent. +++");

        if(displayAlert == true){

             if(D) Log.i(TAG, "+++ ALERT do display alert. +++");

             // custom dialog
             AlertDialog.Builder dialog = new AlertDialog.Builder(this);
             dialog.setTitle("Write here whatever you want to display in the alert message as title.");
             dialog.setMessage("Text content of the alert message.");

             dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int whichButton) {
                      //Do something when the user clicks OK to close the alert (optional)


             dialog.setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int which) {
                     //Do something if the user chooses to ignore the alert (optional)



             if(D) Log.i(TAG, "+++ ALERT do not display alert. +++");

             //Do something in the case the service does not want you to display an alert.
             //Actually, you can use this code to display two types of alert depending on the
             //value of the boolean that the service passes to this class ("proceed")


  • Now, in the code of your service you will have something running. If you want to display the alert, you use the following code:
if(D) Log.i(TAG, "+++ SERVICE starting displayAlert activity to show an alert. +++");
Intent showAlert = new Intent(applicationContext,displayAlert.class);
showAlert.putExtra("proceed", true);
if(D) Log.i(TAG, "+++ SERVICE displayAlert activity went well. +++");
  • Note that this code needs the context of the parent application (applicationContext). What I do is to pass the context when I create and start the service.
  • Remember to define the class in the manifest file (add this code within the <application>. There should be first your main activity, then the service and then you can add the displayAlert activity)
android:label="@string/AlertActivityName" >
  • That’s it!

I hope this is useful.

Pennywise is on shuffle on Spotify at the moment. Have a good one!

Recently, after a hiatus of about a year and a half, I started developing with OPNET Modeler again (I have been using OPNET for simulations and tests on LTE networks often for the last 2 years and a half, but not really developing at a large scale).

OPNET is a company, recently acquired by Riverbed, that offers a rather long list of products. I have to say that my experience is only with Modeler, the wireless module and many of their models (=code) for LTE, UMTS, IP, WLAN, etc. I will be using a couple more of their products soon, learning new stuff and expanding the potential of what we develop.


I started using OPNET back in 2005 when, in order to fulfill my final degree research project, I joined the Mobile Communications Research Group (Grup de Recerca en Comunicacions Mobils) of the Politechnic University of Catalunya (Telecom-BCN). I worked for a bit over a year on Common Radio Resource Management for heterogeneous GSM(EDGE)+UMTS networks. Back then, I learned how to program and develop in OPNET and I was hooked. Going back to my roots now is bringing me back so many memories. OPNET development is hard at the beginning but, once you get it, you see through the code and the GUI like Neo sees through Matrix.

OPNET is, in my humble opinion, not a very popular/widespread tool among academia. It might be because of its cost (though I know for a fact that they have free licenses for academia so the cost is literally zero… I can’t remember if there was such free licenses back in 2005). I have also heard people sometimes telling me that they do not “trust” results generated by OPNET. The reason I have been given is that OPNET models networks based on what (for example) standards say and the results could differ a lot from a real production network. I totally agree. However, the people who make this claims (and many other people too) often use other “simulation platforms” for their research, i.e. Matlab, C++, Java, Python, etc. I do not see why a simulation on another “platform” (i.e. Matlab, C++, Java, Python, etc) would be more accurate or better than with OPNET. Actually, I think that with OPNET it will probably be better because it is much easier (I can’t even imagine trying to simulate an LTE network – eUTRAN + RAN – using Python). By the way, I want to comment here that I have never used NS-2 or NS-3 so I am not trying to imply at all that OPNET is better or worst than those two.

OPNET offers a great platform to develop very realistic and efficient network simulations. I agree that the results might differ from a real production network but, using another simulation platform, in the best case scenario you’ll get results as accurate as with OPNET. The only way to improve them is to actually get your hands on a real network. In that specific case, I happen to be very lucky to work where I work and have access to such a cool lab network. However, in order to achieve realistic results at a big network scale (hundreds of thousands of mobile devices talking over a very (very) large network) one needs an unrealistically (very very unrealistically) huge lab network. In this case, I don’t know anything better than OPNET.

(Again, I have not tried NS-2 or NS-3. Maybe if I did I would change my mind. Any thoughts?)

If you are a grad student working on research related to networking, wireless, cellular or something like that, you might want to check this out (free license for academia research) and speak with your advisor.

Obviously, and as usual, the opinions I post here are my own and have nothing to do with my employer or anybody else.

I just posted the source code of a school project I worked on back in 2003. This was the final project for a programming class back as an undergrad. Essentially, it is an online chat client and server where a user can choose an “old school” sprite and then move around a 2D scenario. Once you step in front of another user, the button “chat” becomes active and you can do IM with that other user. Contains all types of GUI Java constructions, socket programming, servers, etc.

You can find it in the code section of my website.

As some of you, I am an amateur Android developer, who is getting better and better. For work it’s good to have demos of certain projects running on a phone and it is always useful to have actual implementation results when submitting a paper. I learned Android literally in 2 days because I was already decent in Java and because, as in Java, pretty much everything is done for you and you just have to put pieces together. I am able to code simple apps with all types of functionalities.

(At this point I want to take a quick break to share the fact that I am listening to Don’t Tread On Me by Metallica, an awesome song, and it is thanks to the glorious agreement between Metallica and Spotify)

So far I had been able to, with a decent amount of work and time, figure out everything I needed for all kind of apps. However, I needed to move on and have things running in the background as a service. It took me 3 days of struggle and headaches to get it done. And the Android developer guide did not help at all. So I have decided to share this with whoever is interested. This is how you have a simple service running in the background. Adding any extra code and functionality to this should be trivial.

Simple background service in Android step by step

(Note that most of the functions and code is from the official Android sample files. I am not giving any proprietary code or anything that is my new creation. I just explain well step by step how to put all the pieces from Android sample code together. Android’s developer site does a very poor job at it.)

(Note that this is a simple amateur way to do it. I am sure there are other ways that are way more efficient)

  • You should have an activity already coded and working well
  • Create a new class that extends service. In this example we will call it
  • In the app’s Android manifest file add this after </activity>:

<service android:enabled="true"

  • Add to your activity the following variables:

private static final String TAG = "testService"; //For debugging

private boolean serviceOn; //Boolean that logs if the service is ON or OFF

Messenger messengerToService = null; //To send messages to the service

//Class for interacting with the main interface of the service (Extracted from <a href="">the official Android sample code</a>)
private ServiceConnection mConnection = new ServiceConnection() {
     public void onServiceConnected(ComponentName className, IBinder service) {
          // This is called when the connection with the service has been
          // established, giving us the object we can use to
          // interact with the service.  We are communicating with the
          // service using a Messenger, so here we get a client-side
          // representation of that from the raw IBinder object.
          messengerToService = new Messenger(service);

          Log.e(TAG, "+++ Connected to service +++");

     public void onServiceDisconnected(ComponentName className) {
          // This is called when the connection with the service has been
          // unexpectedly disconnected -- that is, its process crashed.
          messengerToService = null;

          Log.e(TAG, "+++ Disconnected from service +++");

  • Implement the following methods in your activity:

void doBindService() {
         // Establish a connection with the service.  We use an explicit
         // class name because there is no reason to be able to let other
         // applications replace our component.
         bindService(new Intent(this,TestService.class), mConnection, Context.BIND_AUTO_CREATE);
         serviceOn = true;
         Log.e(TAG, "+++ Binding to service +++");

void doUnbindService() {
     if (serviceOn) {
          // If we have received the service, and hence registered with
          // it, then now is the time to unregister.

          // Detach our existing connection.
          serviceOn = false;
          Log.e(TAG, "+++ Unbinding from service +++");

  • Now you just have to add the following code where you want to turn ON or OFF your service. Note that the service will run in the background until you either turn it off manually with this code or your activity is destroyed. In other words, the service still runs in the background even if you minimze the activity or you open another app or whatnot. However, I am sure that this is not really efficient so do not use it for an app you want to make commercial. This is mostly an “amateur” solution.

//Bind to service (To turn service ON)
if (serviceOn == false){
     if(D) Log.e(TAG, "+++ Executing doBindService +++");
     mConversationArrayAdapter.add("WEIRD.Already connected...");

//Unbind from service (To turn service OFF)
if (serviceOn == true){
       mConversationArrayAdapter.add("WEIRD.Already disconnected...");

  • Now let’s look at the service class you created. You will need the following variables:

private static final String TAG = "testService"; //For debugging

//Target we publish for clients to send messages to IncomingHandler.
final Messenger mMessenger = new Messenger(new IncomingHandler());

//CODES (the messages you want to be able to send from the activity to the service. I am showing 2 examples, but they could be anything)
static final int MSG_SAY_HELLO = 1;
static final int MSG_SAY_BYE = 2;

  • These are the methods you will need:

public void onCreate () {
    //One-time set-up procedures
    Log.e(TAG, "+++ SERVICE ON CREATE +++");


public void onDestroy () {
    //Close files, disconnect stuff, etc
    //If the service wants to autodestroy itself, the code should call stopSelf()
    Log.e(TAG, "+++ SERVICE onDestroy +++");

    // Tell the user we stopped.
    Toast.makeText(this, R.string.remote_service_stopped, Toast.LENGTH_SHORT).show();

public IBinder onBind(Intent intent) {
    Log.e(TAG, "+++ SERVICE onBind +++");
    return mMessenger.getBinder();

private void handleCommand(Intent intent) {
    // TODO Auto-generated method stub


class IncomingHandler extends Handler {
    public void handleMessage(Message msg) {
    switch (msg.what) {
        case MSG_SAY_HELLO:
            Log.e(TAG, "+++ SERVICE received order to say hello +++");
            Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
        case MSG_SAY_BYE:
            Log.e(TAG, "+++ SERVICE received order to say bye +++");
            Toast.makeText(getApplicationContext(), "bye!", Toast.LENGTH_SHORT).show();

  • And that’s it. Now, when you do doBindService() in your activity the service starts. To stop it, just use doUnbindService() in your activity.
  • To send a message to the service to make it say hello or by (as per the example used here), just use this code in your activity:

if (serviceOn){
    Message msg = Message.obtain(null, TestService.MSG_SAY_HELLO, 0, 0);
    try {
    } catch (RemoteException e) {

And that’s it. Simple and easy.

(The Struggle Within is playing now… have a nice weekend everyone!)

Today’s post will sound a bit random. Lately I have been very busy for various reasons (among them a deadline, let’s cross our fingers…) and I haven’t posted in a couple of weeks. In order to get back to my blog, I decided to share some thoughts on a few things I have been working on for fun over the last few months…

For a while I had been wanting to learn how to program apps. Everybody does it so, why not me? Given that I have an iPhone and that I love anything related to the iPhone and the iPad. However, when I was ready to start, I found out something that, to me, sounds ridiculous and stupid: You need a MAC computer to program apps for iOS. I immediately decided that I would not lear to program apps for iOS and added this Apple “feature” to the list of things I really dislike from Apple. Very close to the top. Very close to the overpriced and unnecessary accessories (Not only they force people to use this to connect to a display when every single non-MAC computer has a VGA connection, but they also charge you 30$ for it).

I decided to move on to Android. I liked it right from the moment I started. I already knew a bit of Java and it is really like programming in that language. Everything is already programmed for you, literally anything, you just need to put the pieces together. Once I understood the xml files, how to create a layout and how to “reference” layout sections from within the code, I was able to program decently complex apps.

Over the last 6 months I have been using Python a lot. I still dislike it quite much (I wrote a couple of posts about it earlier this year), but I have to admit that it is way faster than Matlab processing data. I am able to read and digest massive files of a couple of Gb very fast, something just impossible with Matlab. It is also much better than Matlab in digesting files with a non-standard or predefined format. The only thing I miss is that, beyond the Python documentation itself (very useful but extremely limited) there is no good big sources for samples of code. So, I end up looking up for stuff on Stack Overflow all the time.

I have been playing with the Arduinos lately. I love them. So easy to code and so many libraries and pre-coded functions and features. Like in Android/Java, it is just a matter of putting pieces together.

That’s it. Nothing new in this post. I just wanted to share some thoughts and get back into the blogging mode. I will try to post something at least a couple of times per week. And now, for you geeks out there like me, let’s all go watch The Avengers this weekend!

I hadn’t posted in a while and I decided to do a quick – and geeky – post on something that just annoyed me quite a bit:

As you probably assumed from some posts in this blog, I often code with Matlab. It is quick, easy and works well. Anything I need to simulate or quickly code and test responds very well to Matlab. Recently I have started coding also in Python and C++ for some specific projects. I installed Visual C++ 2008 and after a couple of hours I noticed something that seemed bizarre to me: the code line numbers were not displayed! How is this even possible? It sounds stupid.

My first reaction was “calm down, calm down”. I am sure that if you click anywhere in the code, somewhere on the screen – usually bottom, right – you will see the line and column number. This was indeed the case but, still, I find it quite annoying that the code line number is not shown by default. It was even more annoying when I spent a few minutes trying to find out how to activate this “option”. And I could not.

I had to Google for the solution and this is what I found:

To display line numbers in the code window (aka. Text Editor) do this …

1. Tools > Options > Text Editor > All Languages > General

2. On the right, under Display section, put tick mark for Line numbers.

3. Press OK.


I have been thinking about this for years and, when I started thinking about it because something I am coding, I decided to go for a geek post on this.

I really like Matlab. It is very easy, simple, decently fast and you can do literally anything with it. Yes, it is expensive, but usually somebody pays for it so you can use it. Also, months ago, I blogged about Columbia University students having access to a free Matlab license plus the software itself. I like Matlab mostly because sometimes I am working on a project, I have an idea, and I want to test it quick. A very simplified simulation of a large problem. And I can have that in a day or two with Matlab – and if I want the full implementation, I can do that with Matlab too… with time -.

For the ones of you like me – we code sort of often but we are not really SW developers – you might face this problem all the time. Oh, by the way, I am aware this might sound like an aberration for a real SW developer – who takes care of security of your code, bugs and pays special attention to optimize the code – but in my case I just want the simulation to run and give me the results.

So, my code – and I assume everyone’s too – has quite a few loops. There is usually a main loop that is the number of iterations or repetitions of the experiment, so you can average the results at the end. For the kind of work I do – wireless communications – the second main loop is time. And then there might be other loops inside – users, cells in my system, sub-carriers in OFDMA, etc. -. Within these loops, there are certain variables – arrays – that are filled and emptied. And here is where the problem comes.

Some arrays are known from the beginning. Results, for example. I know before starting to run that I want a sample of, for example, bit error rate for each time slot (time loop) per each iteration (experiment repetitions loop). So, if I am doing M repetitions and I will simulate N seconds of time, I need an MxN matrix pre-allocated for the results. And we all know – or should know – that pre-allocating is good and speeds up your code A LOT. What to do when my pre-allocated matrix needs to be (10^9 x 10^9), that’s a different problem…

Some other arrays, though, are not known initially. For example, if I am simulating data communications, with sessions initiated following a Poisson Process – with inter-arrival time exponentially distributed – and with the amount of data transmitted per session being random. If I need to store the data packets transmitted, I cannot know in advance the size of the matrix I need. So, what should I do? Pre-allocate a huge chunk of memory from the beginning – and possibly running out of memory – or just initiate the matrix empty ( matrix=[]; ) and just increase it each time I create a new data packet?

Another example, even more complex. Throughout my simulation I generate packets that need to be processed. Once a packet is created it is stored in an array. Once it is processed it is removed from that array. Here not only does the array grow, but it also shrinks during the simulation. What to do here?

It is a tricky question, and I am open to any kinds of suggestions. So far, unless I am in a hurry to see the results, I rather have the simulation run for a couple of days in a server. I keep growing arrays until I run out of memory. This way, once I have no more memory, at least I have stored the results so far in a big matrix. If I start pre-allocating a huge chunk of memory, Matlab might complain and not let me even start running the simulation.

PS. Yes, you guessed right. There is a poor server somewhere having a hard time running a very inefficient simulation launched by me that keeps growing and shrinking arrays at each iteration… I am working in optimizing it in parallel, but if it runs fast enough I’ll just leave it the way it is.

About me:

Born in Barcelona, moved to Los Angeles at age 24, ended in NYC, where I enjoy life, tweet about music and work as a geek in security for wireless networks.
All the opinions expressed in this blog are my own and are not related to my employer.
About me:

Blog Stats

  • 147,509 hits

Twitter feed

Enter your email address to follow this blog and receive notifications of new posts by email.