I love Vim too but ...

Vim is a great text editor. It is actually one of the most popular ones among developers and nerds especially if they have experience working with Unix-like operation systems. Most people instantly fall in love with Vim’s key bindings and the philosophy behind its mindset. It allows you to do almost anything without using the mouse.

By default, Vim is just a text editor; however, with the help of a few plugins, you can turn it to an IDE. Plugins like YouCompleteMe and Jedi provide auto completion as you type! NerdTree brings tree-like project structure to Vim and Ctrl-P allows you too simply search through your project files and find the file you’re looking for fast.

It also supports themes! You can download and install your desired theme or simply choose from one of the built-ins. You may want to do some strange things in Vim as well. A friend of mine, checks his emails and plays music in Vim!

These are cool right! You live inside the terminal like you’re living in 70’s and there’s no GUI available. You use Vim because it’s lightweight like your 2019 MacBook Pro has only 32MB of RAM and you’re trying your best saving resources. You behave in a way that your computer is something like below! Oh come on man; this is just insane!

An old computer with 16mb of RAM

Things have changed during the past 3 decades dude! Smartphones now have 16GB of RAM and 1 TB of flash storage. Every CPU now has a powerful GPU built-in which can output up to 8K! The internet connection you’re using to read this post post can download files fast. Developers code in such environments these days:

A modern computer for coding

I love Vim! I really do. I have also published my .vimrc file on Github. But I believe it should be used only if there is no other options. It is the swiss army knife for system administrators because they mostly connect to servers using SSH and need a CLI-based editors get their job done. But as developers, we have much broader options to choose from. That 8GB of memory that is installed on your machine is completely free to use. I don’t want to advertise the text-editor or IDE I’m using myself. It’s completely up to you! You may want to continue using Vim and that’s OK. But just because geeks use Vim for coding doesn’t mean it is the best option and you have to do the same!

If you’re a developer, remember that the job is to develop the software. Your client doesn’t pay you more if you use a geeky text-editor or hard-to-install linux distro. They just want their software to be developed using best-practices and they want it fast. Using CLI-based software doesn’t make you a good developer.

Different ways to split a string in C++

All high-level programming languages provide a large amount of functions for strings manipulation and splitting is one of the most useful ones. Here are some example of how to perform a string split in Python and C# programming languages:

Python:

1
2
3
4
s = 'Hello world'
result = s.split(' ')

# Result is ['Hello', 'world']

C#:

1
2
3
4
var str = "Hello world";
result = str.Split([' ']);

// Result is ['Hello', 'world']

In C++ there is not such built-in functions to split a string by a delimiter; however, it is possible to write your own split function. There are two approaches though:

In classic C way

In C standard library has a <string.h> header file that provides some useful functions for string manipulation and one of them is strtok.

The strtok() function is used to isolate sequential tokens in a null-terminated string, str. These tokens are separated in the string by at least one of the characters in sep.

1
2
3
4
5
6
7
8
9
#include "string.h"
#include "stdio.h"

char* str = "Hello world";
char* splitted = strtok(str, " ");
while (splitted != NULL) {
    printf("%s", splitted);
    splitted = strtok(NULL, " ");
}

In the about example, please consider the following description:

The first time that strtok() is called, str should be specified; subsequent calls, wishing to obtain further tokens from the same string, should pass a null pointer instead. The separator string, sep, must be supplied each time, and may change between calls.

Please also note that if you want to use the above code in a C++ application, you should change the include section string.h to <cstring>.

The modern C++ way

The other approach is to use C++11 std::string class. The new string class provides various useful functions to work with strings. However and as far as I know, it doesn’t have any split functions yet. But you can simply create one using other functions provided in the string class. The following is an implementation of split function in C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <string>
#include <vector>

std::vector<std::string> split(const std::string &str, const std::string &delim)
{
    std::vector<std::string> tokens;
    size_t prev = 0, pos = 0;
    do
    {
        pos = str.find(delim, prev);
        if (pos == std::string::npos)
            pos = str.length();
        std::string token = str.substr(prev, pos - prev);
        if (!token.empty())
            tokens.push_back(token);
        prev = pos + delim.length();
    } while (pos < str.length() && prev < str.length());
    return tokens;
}

As you can see in the above code, we have used the built-in find and substr functions to implement our own split! Finally we pushed each token to a vector and return it to the user. The reason we have used the vector is because we don’t know how many items would be in our result list.

My first experience with Zoho Mail

If you have your own domain and website, you probably want to have some @yourdomain emails as well. Although some hosting providers offer free email hosting, some simply don’t. You also have to configure your own mail server if you’re owning a VPN or dedicated server.

If you’re setting up a mail server for your company, there are some premium mail providers available such as Microsoft Office 365 and GSuite that offer huge amount of features such as online storage, document editing features and so on. On the other hand, people like me may just need to have an email address on their own domain. They need a good email server but don’t want the extra featured which I have mentioned a couple of them few lines above. At this point you want to give Zoho Mail a try.

Zoho Mail is an email hosting service is offers just I wanted. All you need to do is to sign up. They guide you through the process of setting things up and then you will have the access to your new inbox. The free plan offers up to 5 users for free. This free plan gives you full access to their web panel and well as Zoho Mail app so you can check your email either on you phone or your computer. However, if you need IMAP or POP access, you need to upgrade to a premium plan as low as $1 per month.

Zoho Mail subscription plans

You can find more information other their website at: https://www.zoho.com/mail/

Moving to Jekyll

When I started this blog at 2008, I used BlogEngine blogging platform to publish my posts. I chose BlogEngine because it was (Or maybe is) written in .NET and I was a .NET enthusiast at that time. After a few years of blogging with The BlogEngine platform, I decided to move to WordPress. WordPress the the most popular blogging platform and I was very satisfied with it. It has a very powerful text editor and a feature-rich administrator panel.

The problem starts when I lost all of my posts! I was a GoDaddy user for a couple of years and due to International sanctions against Iran, I couldn’t pay for my subscription and didn’t have backup of my posts.

WordPress is actually an awesome platform; however, to to able to deploy it to your website, You should install a few prerequisites. The first requirement is the PHP programming languages because it is written in PHP. The second is the MySQL database!

This could cause some minor issues when wanting to backup your website data. To create a backup in WordPress, you will need to backup your not only your files but your database as well.

Jekyll

Jekyll is a very simple programmer-friendly blogging platform. I works by compiling markdown files into pure HTML files. All you need to do is to create a markdown file, write your post and then compile it to HTML files. You can then upload those files to your hosting storage or using simply use GitHub Pages and forget about paying for hosting storage since Github gives you unlimited bandwidth and storage.

When using Jekyll with GitHub Pages, you have to git push your files into a Github repository to post them to be able to see them on your website. By doing so, you have also backed up your code as well.

If you’re interested as I do, you can give Jekyll a try . In addition, you can access the source code of this blog by clicking here

Configure and manage VPN connections programmatically in iOS 8

Connecting to VPN servers programmatically had been always an impossible task to do for developers because of Apple’s limitations.

In my previous post I’ve described that Apple introduced a brand-new Network Extension framework which gives developers the opportunity to configure VPN preferences programmatically but I didn’t describe how!

This post is a guide to manage VPN configurations in iOS 8 and OS X (10.10) Yosemite while there’s no official documentation published yet. I Also have to thank quellish who helped me a lot in this.

Requirements

  1. The very first and the most critical things you need is an actual device with iOS 8 beta 1 or above to test the app on! This tutorial cannot be tested on iPhone simulator. If you’re going to write a Mac application, OS X Yosemite Preview 3 or above has to be installed.
  2. Since this test doesn’t work on simulator, you have to be a member of iOS/Mac developer program. Also, you need to make some changes to your provisioning profile. You cannot use your iOS 7 provisioning profiles to develop iOS 8 VPN applications.
  3. Xcode 6 beta. By the time of this post (August 2nd, 2014), Xcode 6 is in beta 4 and just like I’ve mentioned in my previous post, you need to to a member of iOS/Mac program to have access to beta tools.
  4. Last but absolutely not least, you need a Mac since Xcode cannot be run on Windows or Linux machines.

Getting Started

The first thing you need to do before actually start writing any codes is to update your provisioning profiles. If you haven’t created any profiles yet, you need to create one now! To do this, login to your developer account, then click on “Certificate, Identifiers & Profiles”:

Update provision profile

Select Identifiers, then select the application you want to update its provisioning profile. If you don’t have any, you can create one using the plus sign. By selecting an app, a list will be appeared. This is a list of features the app is going to use, for example if you want to have iCloud functionality in your application, you have to turn iCloud feature on; otherwise, you won’t be able to test and deploy your iCloud based apps. The following is showing that list:

Update identifiers

By the introduction of iOS 8, a new item has been added to this list which is “VPN Configuration & Control”. This is exactly what we’re looking for! So enable this feature by clicking on it and then ticking its checkbox. When you turn this feature on a modal window will be displayed which describes its functionality:

Enable VPN functionality

Enable VPN Configuration & Control feature and click “Done”. Then, download the provisioning profile again and replace it with the old one. We’re done here, now lets get back to Xcode.

Note: In this post I assume that you’re familiar with iOS development and Objective-C. If you’ve never developed any app in for iOS or Mac, you may need to learn some basic concepts and then return to this post.

Open Xcode and create a new iOS 8 single view application project. Then, place a button in the middle of screen and then connect it to your ViewController.

What we’re going to do is to setup VPN preferences on viewDidLoad: method and then connect to our specified VPN server when the button is tapped.

Before getting started, you have to know how all this work! If you understand the structure of Network Extension framework, then it will be much easier to develop apps based on it.

NetworkExtension.framework

Apple has done a brilliant job developing this framework. Every app can access system preferences but in its own sandbox; which means you cannot access other apps’ sandboxes.

First of all, saved preferences have to be loaded from OS to be able to be accessed. Once they’re loaded, it’s possible to make your changes. After changes have been made, they need to be saved. Unsaved preferences won’t be applied. Your app’s preferences can also be removed if you no longer need them. As a result, to create a VPN configuration we need to do the following:

  • Load our app’s preferences
  • Make our changes
  • Save preferences

Note that you need to load your app’s preferences even if you haven’t set any configuration yet.

After VPN connection is created we can connect to or disconnect from it.

Network extension contains three major classes:

  • NEVPNManager
  • NEVPNProtocol
  • NEVPNConnection

NEVPNManager is the most important class in this framework. It’s responsible for load, save and remove preferences. In fact, all VPN tasks have to be done through this class.

Create a new VPN connection

To get started a new instance of this class has to be created:

NEVPNManager *manager = [NEVPNManager sharedManager];

After NEVPNManager is initialized, system preferences can be loaded using loadFromPreferencesWithCompletionHandler: method:

[manager loadFromPreferencesWithCompletionHandler:^(NSError *error) {
    // Put your codes here...
}];

As I’ve mentioned in above code, the load method accepts a compilation handler block. This block is fired whenever the load process is completed. This block also has a parameter which is an NSError. the NSError parameter will be nil if the loading operation completed; otherwise, it will be non-nil. Accordingly:

[manager loadFromPreferencesWithCompletionHandler:^(NSError *error) {
    if(error) {
        NSLog(@"Load error: %@", error);
    } else {
        // No errors! The rest of your codes goes here...
    }
}];

After loading process is completed, It’s time to set up our VPN connection.

iOS 8 supports two major protocols. IPSec and IKEv2. It’s the first time that Apple offers IKEv2 protocol in its operating systems. This protocol is supported by all major operating systems including Android, Windows Phone, Windows Desktop, Linux and now iOS and Mac. In this post I’m going to talk about IPSec and in my next posts I’ll talk about IKEv2 as well. In addition to these protocols, Apple gives you the ability to create your own protocol if needed! This feature is a very important features for those who have implemented their own protocol; because now it’s possible to implement that protocol on iOS and Mac as well. OK, lets set up our IPSec protocol:

NEVPNProtocolIPSec *p = [[NEVPNProtocolIPSec alloc] init];
p.username = @"[Your username]";
p.passwordReference = [VPN user password from keychain];
p.serverAddress = @"[Your server address]";
p.authenticationMethod = NEVPNIKEAuthenticationMethodSharedSecret;
p.sharedSecretReference = [VPN server shared secret from keychain];
p.localIdentifier = @"[VPN local identifier]";
p.remoteIdentifier = @"[VPN remote identifier]";
p.useExtendedAuthentication = YES;
p.disconnectOnSleep = NO;

In the first line, I’ve created a new instance of NEVPNProtocolIPSec. This class is inherited from NEVPNProtocol class. NEVPNProtocol class is an abstract class you can use to create your own protocols.

Then, we specified our username and password in the second and third line. Notice that the password is a reference from Keychain; so, you need to store your password in Keychain first and then retrieve it.

The fourth line is our server address. Server address can be an IP, a host name or a URL.

Next is authentication method. iOS 8 supports three authentication methods

  • NEVPNIKEAuthenticationMethodNone: Do not authenticate with IPSec server.
  • NEVPNIKEAuthenticationMethodCertificate: Use a certificate and private key as the authentication credential.
  • NEVPNIKEAuthenticationMethodSharedSecret: Use a shared secret as the authentication credential.

As you can see, I’ve used Shared Secret method; but, you can use whatever method you want.

The next line is Shared Secret reference. Again it’s reference from Keychain; so, you need to get Shared secret from there. If you’re going to use certificate rather than shared secret. There’s no need to fill sharedSecretReference property; instead, you have to fill identityData property. Identity data is the PKCS12 data for the VPN authentication identity. The value for this property must be a NSData in PKCS12 format:

p.identityData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"clientCert" ofType:@"p12"]];

The next two lines are local and remote identifiers. These two are strings identifying the local and remote IPSec endpoints for authentication purposes.

The next property we need to set is useExtendedAuthetication. This is a flag indicating if extended authentication will be negotiated. This authentication is in addition to the IKE authentication used to authenticate the endpoints of the IKE session. For IKE version 1, when this flag is set X-Auth authentication will be negotiated as part of the IKE session, using the username and password properties as the credential. For IKE version 2, when this flag is set EAP authentication will be negotiated as part of the IKE session, using the username, password, and/or identity properties as the credential depending on which EAP method the server requires.

The last property to set is disconnectOnSleep. This boolean indicates whether the VPN connection must be disconnected when the device goes to sleep or not.

OK that’s enough for protocol. The next thing we have to do is to assign the protocol we’ve just created to the VPN manager. To do so, the setProtocol: method can be used.

[manager setProtocol:p];

IPSec and IKEv2 protocols have a very cool feature called On-demand. This feature enable connect to connect automatically whenever user attempted to connect to the internet. In iOS 8, it’s possible to enable on-demand on the connection. But, I’m going to cover this feature in another post; therefore, lets leave it for now and set the onDemandEnabled property to NO for now.

[manager setOnDemandEnabled:p];

The last thing we must set is the description of VPN preference we’re going to create. To do so, just set its localized description property by using setLocalizedDescription: method

[manager setLocalizedDescription:@"[You VPN configuration name]"];

We’re almost done. We’ve set up the configuration but haven’t saved it yet. To save the configuration simply call the saveToPreferencesWithCompletionHandler: method:

[manager saveToPreferencesWithCompletionHandler:^(NSError *error) {
    if(error) {
        NSLog(@"Save error: %@", error);
    }
    else {
        NSLog(@"Saved!");
    }
}];

This method simply saves your specified configuration to the system settings.

Connect to the VPN connection we’ve just created

Now that you’ve saved your settings to system’s preferences, it’s time to connect to it. NEVPNManager has a property called connection. This property is an object of NEVPNConnection class. It holds information which is responsible for VPN connection. To connect to VPN server you’ve just created, simply call startVPNTunnelAndReturnError: method of NEVPNConnection class just like below:

- (IBAction)buttonPressed:(id)sender {
    NSError *startError;
    [[NEVPNManager sharedManager].connection startVPNTunnelAndReturnError:&startError];

    if(startError) {
        NSLog(@"Start error: %@", startError.localizedDescription);
    } else {
        NSLog(@"Connection established!");
    }

}

Run the application on your device and you’ll see and new connection will be create and you can connect to it by tapping the button. Also, you can disconnect from VPN server programmatically as well by calling stopVPNTunnel method of NEVPNConnection:

If you have any idea, suggestion or anything else regarding this post, please leave your comments down below. I’ll blog about IKEv2 and On-demand features in the near future. Stay tuned.