Monday, March 30, 2015

Writing a DJango App - Part I


The example is to create a poll application. There are two parts of this application 

1. A public site that lets people view polls and vote in them 
2. An Admin site that lets admin to add polls , delete them 

To know whether Django is installed properly, below is the command that can be used 

python -c “import Django; print(django.get_version())”

If Django is installed, it will show the version number. For me, it shown as 1.9. 

Now to create a new Project, we need to run the command below 

django-admin.py startproject mysite

However, this was giving a lot of errors like below 

dministrators-MacBook-Pro-3:~ retheesh$ django-admin.py startproject mysite
Traceback (most recent call last):
  File "/usr/local/bin/django-admin.py", line 2, in
    from django.core import management
  File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 68
    commands = {name: 'django.core' for name in find_commands(__path__[0])}
                                      ^
SyntaxError: invalid syntax

Investigating more on this, it looked like the Python version in which Django got installed is old version. 1.9 version of Django seems to require any python version greater than 3.x. Below few lines can identify in which python the django is installed. In my case, the python version that was installed from dmg file downloaded from python website was 3.4 

administrators-MacBook-Pro-3:~ retheesh$ python3.4
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
Traceback (most recent call last):
  File "", line 1, in
ImportError: No module named 'django'
>>> 

In the above, it says no module django found. At the same time, if run like below 

administrators-MacBook-Pro-3:~ retheesh$ python
Python 2.7.6 (default, Sep  9 2014, 15:04:36) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> 

The above is the default system python which is in 2.7.6 and it successfully able to import django because django is installed in that python. 

Next series, need to work on installing the django on python 3.4 ! 

References: 

Sunday, March 29, 2015

IMS I-CSCF and S-CSCF

I-CSCF which is, Interrogating Call Session Control Function is one of the main elements in the IMS hardware architecture. I-CSCF is used to forward the SIP requests to the S-CSCF. There may be several S-CSCF in a network, I-CSCF helps to find out a right one. This acts as key element in Roaming methodology. 

The I-CSCF must find an S-CSCF in two instances

1. a P-CSCF forwards a SIP register request to the I-CSCF based on the home domain of the user. 
2. An S-CSCF forwards the SIP INVITE to the I-CSCF based on the domain of the called party. 

In both cases,  a CSCF node extracts the home domain of the originating or terminating endpoint and consults a DNS server to determine IP address of the I-CSCF 

Below is overall architecture of an IMS network. 




References:

Saturday, March 28, 2015

Android Launching System Apps

As part of my experiments, i had to launch two system apps Music Player and Map. Some notes from experience wrote down here. 

Below are few ways to launch native Android default applications from a Google play available application


Launching Music Player

 Intent intent = new Intent(MediaStore.INTENT_ACTION_MUSIC_PLAYER);
 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 startActivity(intent);

This was working perfectly, however, in the code it was saying MediaStore.INTENT_ACTION_MUSIC_PLAYER is deprecated. 

The replacement for this was CATEGORY_APP_MUSIC 

As per the documentation, this Category should be used along with the ACTION_MAIN to launch music application. The activity should be able to play, browse, or manipulate music files stored on the device. 

This should not be used as a primary key for the intent since it will not result in the app launching with correct action and category. instead, we should use this with makeMainSelectorActivity(String, String) to generate a main intent with this category in the selector. 

However, below code was resulting in No Activity Found 

 Intent intent = new Intent();
                        intent.makeMainSelectorActivity(intent.ACTION_MAIN,
                                Intent.CATEGORY_APP_MUSIC);
                        startActivity(intent);

For time being decided to stay with the old approach itself. 

Launching google Map Application 

 String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?daddr=%f,%f (%s)", 12.914081f, 77.609953f, "Cafe Coffee day");
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                        intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
                        try
                        {
                            startActivity(intent);
                        }
                        catch(ActivityNotFoundException ex)
                        {
                            try
                            {
                                Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                                startActivity(unrestrictedIntent);
                            }
                            catch(ActivityNotFoundException innerEx)
                            {
                                //Toast.makeText(this, "Please install a maps application", Toast.LENGTH_LONG).show();
                            }
                        }

The above code launches the map and shows the navigation view. 

Uri gmmIntentUri = Uri.parse("geo:?z=15");
                        Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
                        mapIntent.setPackage("com.google.android.apps.maps");
                        startActivity(mapIntent);

The above code just launches the map view with zoom level as 15 and focuses the map with the current location of the user. 

References:

Thursday, March 26, 2015

iOS Silent Push notifications

This is a good feature especially as it helps apps to decide whether there is any thing valid in the message that is coming from the server. 

This needs both the client and server changes. the app specific changes are below 

1. Include the background run requirement as content update available. Below is the mode. “App downloads content in response to push notifications”

This is easy because we can just include this from Capabilities tab of the project. which will add this to the plist file. 

Change the code to include the new call back like below. 

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler
{
    NSLog(@"--- Application received remote notification ---");
    NSLog(@"-- User Info Received :%@",userInfo);
    
    UILocalNotification *notification = [[UILocalNotification alloc]init];
    notification.repeatInterval = NSDayCalendarUnit;
    [notification setAlertBody:@"Hello world"];
    [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
    [notification setTimeZone:[NSTimeZone  defaultTimeZone]];
    [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
    
}

2. Modification to the server. 
On the server side, in general the “content-available:1” to be added in the payload. 

So the pay load could be something like this 

{
    "aps": {
        "content-available": "1",
        "sound": ""
    },
    "count": "1",
    "type": "1"
}

Below are few notes from the testings done

- If  app is running in background, when server sends a silent push, app receives it in background and app can do some task in background for a finite amount of time. And it can post a local notification or sit silent if no update to be given to the user 
- If the app was not running in the background or foreground, then OS invokes the app to give this notification payload and app can do brief operations.  
- IF the app was killed by user previously, the notification won’t be delivered to the app.  
- If the app was killed due to memory on device or device restarted for some reason etc, the app will be given the notificaton payload even if user don’t launch the app. 
- If the app was running in the foreground, then notification is directly delivered to the app. 


The page in the reference below, having good amount of nice content explaining the same thing. Nice pictures too on it !! 

References:

Wednesday, March 25, 2015

What is Django?


It is a high level Python Web Framework that encourages rapid development and clean pragmatic design. To install the framework, the reference link under reference section needs to be downloaded and installed. 

minimal Installation steps were given in the docs/install/install.text file. The steps to be followed in general are below 

1. Install python 
First of all, get the python framework from the link https://www.python.org/download/ 
The download gave a package 

And it gave the installation success like this below 

Apparently, there seems to be a Java Python implementation also, which is called Jython downloadable from http://www.jython.org/ 

To verify whether the python is installed, type “python” in terminal, it was giving something like below 

Python 2.7.6 (default, Sep  9 2014, 15:04:36) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 

Now, we need to import django, before installation, tried to run the django command it gave error like below 

>>> import django
Traceback (most recent call last):
  File "", line 1, in
ImportError: No module named django
>>> 

Now for the installation, this text file was not giving any specific info, So after a search, it gave the below https://docs.djangoproject.com/en/1.7/topics/install/ 

and the installation is simple once after downloading the django package. enter the below command 

sudo python setup.py install 

after this, running the django command was giving like below. 

>>> import django
>>> print(django.get_version())
1.9
>>> 

References:


Monday, March 23, 2015

SIP Learning - Part IX - Registrar Flow diagram

Below is the overall logic at the Registrar end for processing a REGISTER request.



References:
https://www.ietf.org/rfc/rfc3261.txt Section 10.3 

Sunday, March 22, 2015

iOS checking WiFi Data usage

The data usage of a WiFi Device can be calculated like below. 

Below code snippet can help to get the data counters. 

BOOL   success;
    struct ifaddrs *addrs;
    const struct ifaddrs *cursor;
    const struct if_data *networkStatisc;
    
    int WiFiSent = 0;
    int WiFiReceived = 0;
    
    int WiFiPacketsSent = 0;
    int WiFiPacketsReceived = 0;
    
    int WWANSent = 0;
    int WWANReceived = 0;
    
    NSString *name=[[NSString alloc]init];
    
    success = getifaddrs(&addrs) == 0;
    if (success)
    {
        cursor = addrs;
        while (cursor != NULL)
        {
            name=[NSString stringWithFormat:@"%s",cursor->ifa_name];
            NSLog(@"ifa_name %s == %@\n", cursor->ifa_name,name);
            // names of interfaces: en0 is WiFi ,pdp_ip0 is WWAN
            
            if (cursor->ifa_addr->sa_family == AF_LINK)
            {
                if ([name hasPrefix:@"en"])
                {
                    networkStatisc = (const struct if_data *) cursor->ifa_data;
                    WiFiSent+=networkStatisc->ifi_obytes;
                    WiFiReceived+=networkStatisc->ifi_ibytes;
                    
                    WiFiPacketsSent+= networkStatisc->ifi_opackets;
                    WiFiPacketsReceived+= networkStatisc->ifi_ipackets;
                    



The complete code can be found here 

https://drive.google.com/file/d/0B0ZgwdHsnw1bTDhOVFNBekJIaDg/view?usp=sharing 

References:



SIP Learning Part VII - adding Bindings


The REGISTER request sent to a registrar incldues the contact address to which the SIP requests for the address-of-record should be forwarded. The AOR is included in the To header field of the REGISTER request. 

The Contact header field values of the request typically consists of SIP or SIPS URIs that identify particular SIP endpoints (for e.g. “sip:carol@cube22412a.chicago.com”, but MAY use any URI scheme. A SIP UA can choose to register telephone numbers (with the tel URL) or email addresses for e.g. 

Once a client has established bindings at the registrar, it MAY send subsequent registrations containing new bindings or modifications to existing bindings as necessary. The 2xx response to REGISTER request will contains, in a Contact header field, a complete list of bindings that have been registered for this address of record at this registrar. 

Setting expiration interval of Contact Addresses
When a client sends a REGISTER request, it MAY suggest an expiration interval that indicates how long the client would like the registration to be valid. 

There are two ways in which a client can suggest an expiration interval for a binding: through an expires header field or an “expires” Contact header parameter. The latter allows expiration intervals to be suggested on a per-binding basis when more than one bindings is given in a single REGISTER request. 

Preferences Among Contact Addresses
If more than one contact is sent in a REGISTER request, the registering UA intends to associate all of the URIs in these contact header field values with the address-of-record present in the To field. The list can be prioritised with the “q” parameter in the Contact header field. The “q” parameter indicates the relative perforce for the particular Contact header field value compared to other bindings for this address-of-record. 

Removing Bindings 
Registrations are soft stage and expire unless refreshed, but can also be explicitly removed. A client can attempt to influence the expiration interval selected by the Registrar. A UA requests the immediate removal of a binding by specifying an expiration interval of “0” for that contact address in a REGISTER request. UAs SHOULD support this mechanism so that the bindings can be removed before their expiration interval has passed. 

The use of * Contact header field value allows a registering UA to remove all bindings associated with an address-of-record without knowing their precise values. 

Fetching Bindings 
A success response to any REGISTER request contains the complete list of existing bindings, regardless of whether the request contained a Contact header field. If no Contact header field is present in a REGISTER request, the list of bindings is left unchanged. 

Refreshing Bindings
Each UA is responsible for refreshing the bindings that it has previously established. A UA SHOULD NOT Refresh bindings set up by other UAs. 

The 200 OK response from the registrar contains a list of Contact fields enumerating all current bindings. The UA compares each contact address to see if it created the contact address, using comparison rules in section 19.1.4. 

The UA SHOULD use the same Call-ID for all registrations during a single boot cycle. 

Setting internal Clock
If the response for a REGISTER request contains a Date header field, the client MAY use this header to learn the current time in order to set any internal clocks. 

Discovering a Registrar
UAs can use three ways to determine the address to which to send registrations. by configuration, using address-of-record, and multicast. The UA should use the host part of the address-of-record as the request-URI and address  the request there, using the normal SIP server location mechanism. For e.g. the user sip:carol@chicago.com addresses the REGISTER request to sip:chicago.com 

A UA can be configured to use multicast. Multicast registrations are addressed to the well-known “all SIP servers” multicast address “sip:mcast.net” (224.0.1.75 for IPV4). No well known IPV6 multicast address has been allocated. such an allocation will be documented separately when needed. 

SIP UAs MAY listen to that address and use it to become aware of the location of other local users; however they do not respond to the request. 

Transmitting a Request
Once the REGISTER method has been constructed, and the destination of the message identified, UACs follow the procedures described in section 8.1.2 to hand off the REGISTER to the transaction layer. IF the transaction layer returns timeout error because the REGISTER yielded no response, the UAC SHOULD NOT immediately reattempt a registration to the same registrar. 

Error responses: 
If the UA Receives 423, interval too brief, it MAY retire the registration after making the expiration interval of all contact addresses in the REGISTER request equal to or greater than the expiration interval within the Min-Expires header field of the 423 response. 

Refernces:
 https://www.ietf.org/rfc/rfc3261.txt Sections 10.2.1 - 10.2.8 


SIP Learning Part VI - Constructing Register Request


A REGISTER request can add a new binding between an address-of-record and one or more contact 
addresses. Registration on behalf of a particular address- of - record can be performed by a suitably authorised third party. A client can also remove previous bindings or query to determine which bindings are currently in place for an address-of-record. 

A REGISTER request does not establish a dialog. A UAC may include a Route header filed in a REGISTER request based on a pre-existing route set as described in section 8.1. The Record-Route header field has no meaning in a REGISTER request or response. and MUST be ignored if present. In particular, the UAC MUST NOT Create a new route set based on the presence or absence of a Record-Route header field in any response to a REGISTER request. 

The following header fields except Contact, MUST Be included in a REGISTER request. A contact header field MAY be included. 

Request-URI: This names the domain of the location service for which the registration is meant. (for e.g. sip:chicago.com). The user info and “@” components of the SIP URI MUST NOT be present. 

To: The To header field contains the address of record whose registration is to be created, queried or modified. The To header field and the Request-URI field typically differ, as the former contains a user name. This address-of-record MUST be a SIP URI or a SIPS URI 

From : The From Header field contains the address-of-record of the person responsible for the registration. The Value is the same as the To header field unless the request is a third party registration 

Call-ID : All registrations from a UAC SHOULD use the same Call-ID header field value for registrations sent to a particular registrar. 

If the same client were to use different call-id values, a registrar could not detect whether a delayed REGISTER request might have arrived out of order. 

CSeq: The CSeq value guarantees proper ordering of REGISTER requests. A US MUST increment the CSEq value by one for each REGISTER request with the same Call - ID. 

Contact: REGISTER MAY include a contact Header field with zero or more values containing address bindings. 

UAs MUST NOT send a new registration (that is, containing a new Contact header field values, as opposed to retransmission) until they have received a final response from the registrar for the previous one or the previous REGISTER request has timedout. 

The following Contact header params have a special meaning in REGISTER requests. 

action: The “action” parameter from RFC 2543 has been deprecated. UACs SHOULD NOT use the action parameter. 

expires: The expires parameter indicates how long the UA would like the binding to be valid. The value is a number indicating seconds. IF this parameter is not provided, the value of the expires header filed is used instead.  Implementations MaY treat values larger than 2**32-1 (4294967295 seconds for 136 years) as equivalent to 2**32-1. Malformed values SHOULD be treated as equivalent to 3600. 

REferences: 

SIP Learning Part V - Registrations overview

SIP offers a discovery capability. IF a user wants to initiate a session with another user, SIP must discover the current host(s) at which the destination user is reachable. This dsicovery process is frequently accomplished by SIP network elements such as proxy servers and redirect servers which are responsible for receiving a request, determining where to send it based on knowledge of the location of the user. and then sending it there. To do this, SIP network elements consult an abstract service known as a location service, which provides address bindings for a particular domain. These address bindings map an incoming SIP or SIPS URI, sip:bob@biloxi.com for e.g. to one or more URIs that are somehow closer to the desired user agents at which the desired recipients is currently residing.  

Registration creates bindings in a location service for a particular domain that associates an address-of-record URI with one or more contact addresses. Thus when a proxy for that domain receives a request whose Request-URI matches the address of record, the proxy will forward the request to the contact addresses registered to that address-of-record. 

There are many ways by which the contents of the location service can be established. One way is administratively. For e.g. IF bob is known to be a member of engineering department though access to a corporate database. However, SIP provides a mechanism for a UA to create a binding explicitly. This mechanism is known as registration. 

Registration entails sending a REGISTER request to a special type of UA known as registrar. A registrar acts as the front end to the location service for a domain, reading and writing mappings based on the contents of REGISTER requests. This location service is then typically consulted by proxy server that is responsible for routing requests for that domain. 


To note, Registrar and Proxy can be a single device. For explanatory purposes, it most of the times depicted as two different entities.  It can also be noted that UAs may reach the Registrar via proxy servers. 

References: 
https://www.ietf.org/rfc/rfc3261.txt Section 10

Saturday, March 21, 2015

SIP Learning Part IV - Headers and Tags


The From field of the response MUST equal the From header field of the request. The Call-ID header of the response MUST equal the Call-ID header field of the request. The CSeq header field of the response MUST equal to the CSeq field of the request. The Via header field values in the response MUST equal the Via header field values in the request and MUST contain same ordering . 

If the request contained a To tag in the request, the To header field in the response MUST equal to that of the request. However, if it did not contain a tag, the URI in the to field must be equal to that of request and in addition, UAS must add tag to the To header field in the response. The exception to this is 100 trying, in which tag necessarily not present. The same tag MUST be used for all the responses to that request, both final and provisional.  

references:

Android - Detecting Config Changes in an Activity

As part of the project, had to have a Grid view and the grid view had to have 3 columns in landscape while only 2 columns in portrait mode. Implementing this was fairly simple and mainly two steps to do this:

1. Declare the Activity for accepting the configuration changes 
2. once the configuration changed is called back, set the grid column to the number desired 

Below is the code snippet to be placed in the activity for declaring config changes. 


 
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:configChanges="orientation|screenSize">
       

Note that if we have only “orientation” in the value, then the callback was not happening, had to give screenSize as well. 

in the app, below is the code 

@Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.v("RR:--","Main activity onConfigurationChanged "+newConfig);
        GridView gridview = (GridView) findViewById(R.id.gridview);
        if(gridview != null) {
            gridview.setNumColumns(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ? 3 : 2);
            super.onConfigurationChanged(newConfig);
        }
    }

references: 

SIP Learning Part III - Essential headers continued


C-Seq Header 

this header is used to identify the order of transactions. It consits a sequence number and a method. The method must match that of the request. For non-REGISTER requests outside of a dialog, the sequence number is arbitrary. The sequence number MUST be expressible as 32 bit unsigned integer and MUST be less than 2**31. 

for e.g. CSeq : 4711 INVITE 

Max - Forwards 

This header limits the number of hops a request can transit on the way to its destination. It consists of an integer that is decremented by one at each hop. If the Max-forwards value reaches 0 before the request races its destination, it will be rejected with a 483 (too many hops) error response. 

When UAC constructs a request, Max-Forwards header is set as 70, which is chosen value sufficient enough to safely reach the destination on a network without any loops. Lower values should be used with caution and only in networks where topologies are known by the UA. 

Via header 
The Via header filed indicates the transport used for the transaction and identifies the location where the response to be seen. When UAC creates a request, it MUST insert a Via into that request. The protocol name and protocol version in the header field MUST be sip 2.0, respectively. The Via header field must contains a branch parameter. This parameter is used to identify the transaction created by that request. this parameter is used by both client and server. 

The branch parameter must be unique for each of the request client generates except for Cancel and ACK. these request must contain the branch value of the request that it Cancels or ACKs. 

The branchId inserted by an element compliant with this specification MUST always begin with the characters “z9hG4bK” which is known as magic cookie that ensrure the uniqueness of the number. 

Contact 
The Contact header filed provides a SIP or SIPs URI that can be used to contact that specific instance of the UA for subsequent requests. The contact header field must be present and exactly one SIP or SIPS URI in any request that can result in the establishment of a dialoag. 

If the request-URI or the top most Route header field contains a SIPS URI, the n the contact header also should contain a SIPS URI. 

Supported and Require
If the UAC supports extensions to SIP that can be applied by the server to the response, the UAC SHOULD include a supported header field in the request listing the option tags for those extensions. The Options tags listed MUST only refer to prevent servers from insisting that clients implement nonstandard vendor - defined features in order to receive service. If the UAC want to insist that any proxies through which the request is traversed should understand the extension, then it can include a Proxy-Require header for this purpose. 

Additional Message Components
After a new request has been created, and the header described as mandatory are properly constructed, any additional optional header fields are added, as are any header fields specific to the method. 

SIP Requests may contain MIME encoded body regardless of the body that a  request contains , certain header fields must be formulated to characterize the contents of the body. 

references:

Friday, March 20, 2015

SIP Learning Part II - Generating SIP Request Essential Headers


From Header
From header indicates logical identify of the initiator of the request, possibly the user’s address-of-record. Like the To header field, it contains a URI and optionally a display name. It is used by the SIP elements to determine which processing rules to apply to a request for e.g. automatic call rejection. As such, the from uri should not contain the IP address or FQDN of the host on which the UA is running, since these are not logical names. 

If the identity of the client to be hidden, UA should use the “Anonymous” word for the display name and an invalid but yet syntactically correct sip address for e.g. thesis@anonymous.invalid 

The From header field MUST contain a new “tag” parameter, chosen by the UAC. 

Some of the examples of From header area below 

From : “Bob” ; tag=148s
From : sip+12312321@phone2net.com;tag=23432
From: Anonymous ; tag=hysa

Call - ID
Call ID header field acts as a unique identifier to group together a series of messages. It must be the same for all the requests and responses sent by either UA in a dialog. IT should be the same in each registration from a UA. 

In a new request created by a UAC of any dialog, the call-id header field must be selected by the UAC as a globally unique identifier over space and time unless overridden by the method specific behaviour. If suppose a 401 error is received by the UA and then a retry is done with correct authorisation, then the call id should not change. 

Use of cryptographycally random identifiers in the generation of Call-IDs is recommended. Implementation may use localid@host. Call ids are case sensitive and are just compared byte by byte. 

e.g. for Call ID is Call-ID : fasdas-sdasd-sd@foo.bar.com


references:

SIP Learning Part I - Essential Headers

For a valid SIP request, there are 6 header fields at least minimum required. They are To, From, CSeq, Call-ID, Max-Forwards, and Via. These headers are in addition to the Request line, which contains the method, Request-URI, and SIP version 

Request - URI 
The initial Request-URI should be set as the value of URI in the To Field. One notable exception is the REGISTER method. In some circumstances, the presence of pre-existing route set can affect the Request-URI of the message. A pre-existing route set is an ordered set of URIs that identify a chain of servers, to which a UAC will send outgoing requests that are outside of a dialog. Commonly they are configured on a UA with the by user or service provider manually, or through some other non-SIP mechanism. When a provider wishes to configure a UA with an outbound proxy, it is recommended that this be done by providing it with a pre-existing route set with a single URI, that of outbound proxy. 

When a pre-existing route set is present, the procedure for populating the request-URI and route header field detailed in section 12.2.1.1. must be followed using the desired Request-URI as the remote target URI. 

To Header
The To header field first and foremost specifies the desired “logical” recipient of the request, or the address-of-record of the user or resource that is the target of this request. This may or may not be the ultimate recipient of the request. The To header may contain SIP or SIPS URI, but it may also make use of other URI schemes. e.g. tel when appropriate. The To header field also allows display name. 

The UAC can form the To header in a number of ways. either via human interface perhaps inputting manually or from a contact lis. Using the string to form the user part of the SIPS URI implies tat the UA wishes to communicate securely and that name to be resolved in the domain to the RJS of the at sign. The RHS will be frequently be the home domain of the requester, which allows for the home domain to process the outgoing request. This is useful for features like speed dial that requrire interpretation of the user part in the home domain. The tel uri may be used when the UA does not wish to specify the domain that should interprest a telephone nu,her that has been input by the user. 

A use case would be a user in an airport might log in and send requests through an outbound proxy in the airport.If they enter 411 (local directory assistance in US) that needs to be interpreted and processed by the outbound proxy in the airport, not the user’s home domain. In this case, tel:411 would be right choice. 

A request outside of a dialog MUST not contain a To tag; the tag in the To field of a request identifies the peer of the dialog. Since no dialog established, no tag is present. 

References:

Thursday, March 19, 2015

WiFi Calling on iOS 8.x

From iOS 8.0 onwards Apple has introduced WiFi Calling on iOS 8.0 devices and that can be enabled via the below settings 

- Settings > Phone > Wi-Fi Calling 
- Toggle the Wi-Fi calling switch to ON
- If the carrier does not have the user’s registered emergency address, one will be asked to add it before the feature is activated. 

was browsing through the API additions in iOS 8.0 and finds that there are a few such as 

However, there did not seem to have a way to capture the QoS or packet rate on the device. 

On the Router, we could probably set the QoS like mentioned below 



References: 

WiFi Signal Strength in iOS

As part of a project, had to investigate if we can get wifi signal strength. and it looks like for 3rd party developers no APIs are exposed to do this function. 
However, there are few apps out there which can detect the signal strength by other secondary factors, such as networkk throughput. such as speedtest.net
Another App is Network Multi meter uses the similar design but displays the information in real time as a user walking around the house. these apps does this by
actual data through put and network ping. 

REferences:

REGISTER processing at the registrar end

There are mainly 8 steps in processing the REGISTER message at the registrar end. 
1. The registrar inspects the Request-URI to determine whether it has access to bindings for domain identified in the Request-URI. If not, and if the server also acts as proxy server, the server SHOULD forward the request to the addressed domain, following the general behaviour for proxying messages described in section 16 of https://www.ietf.org/rfc/rfc3261.txt 

2. To guarantee that the registrar supports any necessary extension, the registrar MUST process the Require header field value as described for UAS in section 8.2.2 of https://www.ietf.org/rfc/rfc3261.txt 

3. A Registrar SHOULD authenticate the UAC. Mechanism for the authentication of SIP user agents are described in section 22 of https://www.ietf.org/rfc/rfc3261.txt . The Registrar behaviour in no way overrides the generic authentication framework for SIP. IF no authentication mechanism available, the registrar MAY take the from address as the asserted identity of the originator of the request. 

4. The registar SHOULD determine if the authenticated user is authorised to modify registrations for this address-of-record. For e.g. a registrar might consult an authorisation database that maps user names to a list of addresses-of-record for which that user has authorization to modify bindings. If the authenticated user is not authorised to modify bindings, the registrar MUST return 403 (forbidden) and skip the remaining steps. 

In architectures that support third party registration, one entity may be responsible for updating the registrations associated with the multiple addresses-of-record. 

5. The registrar expected the address-of-record from the To header of the request. If the address-of-record is not valid for the domain in the request URI, the registrar MUST send a 404 (Not Found) response and skip the remaining steps. The URI must then be converted to canonical form. To do that, all URI parameters MUST be removed (including the user-param) and any escaped characters MUST be converted to their unescaped form. The result serves as an index into the list of bindings. 

6. The registrar checks whether the request contains the Contact header field. If not, it skips to the last step. If the contact header field is present, the registrar checks if there is one Contact field value that contains the special value “*” and an expires field. If the request has additional contact fields or an expiration time other than zero, the request is invalid and the server MUST send a 400 Invalid request and skip the remaining steps. If not, the registrar checks the Call-ID agrees wit the value stored for each binding. If not, it MUST remove the binding. If it does agree, it MUST remove the binding only if the CSeq in the request is higher than the value stored for that binding. Otherwise the update MUST be aborted and the request fails. 

7. The Registrar now processes each contact address in the Contact header field in turn. For each address, it determines the expiration interval as follows. 
- If the field value as an expires parameter, that value MUST be taken as the requested expiration 
- IF there is no such parameter, but the request has an Expires header field, that value MUST be taken as the requested expiration. 
- IF there is neither, a locally-configured default value MUST be taken as the requested expiration. 

The registrar may choose an expiration less than the requested expiration interval. If and only if the requested expiration interval is greater than zero and smaller than one hour AND less than a registrar—configured minimum, the registrar MAY reject the registration with a response 423 (Interval too brief) This response MUST contain a Min-Expires header field that states the minimum expiration interval the registrar is willing to honour. It then skips the remaining steps. 

Allowing the restorer to set the registration interval protects it against excessively frequent registration refreshes while limiting the state that it needs to maintain and decreaging the likelyhood of registrations going stale. The expiration interval of registration is frequently used in the creation of services. An example is a follow-me service, where the user may only be available at a terminal for a brief period. Therefore registrats should accept brief registrations; a request should only be rejected if the interval is so short that the refreshes would degrade registrar performance. 

For each address, the registrar then searches the list of current bindings using the URI comparison rules. If the bindings does not exist, it is tentatively added. IF the binding does exist, the registrar checks the call - ID value. If the call - ID value in the existing binding differs  from the call - id value in the request, the binding MUST be removed if the expiration time is zero and updated otherwise. If they are the same, the registrar compare the CSeq value. If the value is higher than that of the existing binding, it MUST update or remove the binding as above. If not , the update MUST be aborted and the request fails. 

This algoritm ensures that out-of-order requests from the same UA are ignored. 

Each binding updates MUST be committed ( that is , made visible to the proxy or redirect server) if and only if all binding updates and the additions succeed. IF any one of them fails (for e.g. because the backend databse commit failed) the request MUST fail with 500 (Server error) response and all tentative bindings updates MUST be removed. 

8. The registrar returns 200 OK response. The response MUST contain contact header field values enumerating all current bindings. Each contact value must feature and expires parameter indicating its expiration interval chosen by the registrar. The response SHOULD include a Date header field. 

Refernces: 

Tuesday, March 17, 2015

IMS Architectural components - Part II CSCF


CSCF - Call Session Control Function 

Several roles of SIP proxies are collectively called as CSCF which are used to process SIP signalling packets in IMS. 

Proxy-CSCF (P-CSCF) is a SIP pro that is the first point of contact for the IMS terminal. it can be located either in the visited network (in full IMS networks) or in the home network (when the visited network is not IMS Compliant yet) . Some networks may use SDB for this function. The P-CSCF is at the core a specialised SBC for the User-Netwrok interface which not only protected the network but also the IMS terminal. The use of an additional SBC between the IMS terminal and the P-CSCF is un-necessary and infeasible due to the signalling being encrypted on this leg. The terminal discovers its P-CSCF with either DHCP, or it may be configured (e.g. during initial provisioning or via 3PP IMS management Object (MO)) or in the ISIM or assigned in the PDP context (in GPRS) 

- It is assigned to an IMS terminal before registration, and does not change for the duration of registration. 
- It sits in the path for all the signalling and can inspect every signal; the IMS terminal must ignore must ignore any other unencrypted signalling. 
- It provides subscriber authentication and may establish IPSec or TLS security association with the IMS terminal. This prevents spoofing attacks and replay attacks and protects the privacy of the subscriber. 
- It inspects the signalling and and ensures that the IMS terminals do not misbehave (e.g. change the signalling routes, do not obey home networks routing policy) 
- It can also compress and de-cpmpress SIP messages using SigComp, which reduces the round trip over the slow radio links. 
- It may include a policy decision function (PDF) which authorises the media plane resources for e.g. QoS over the media plane. It is used for policy control, bandwidth management, etc. The PDF can also be a separate function. 
- It also generates charging records. 


References: 
http://en.wikipedia.org/wiki/IP_Multimedia_Subsystem

Wednesday, March 11, 2015

Trying out Quick start for IMSDroid

First of all, it required to have SIP account created. The site is recommending to use sip2sip.info website for creating an account. The registration page is given in the references.
After creating the account, it sent a mail with the details for accessing it. 

Next was SIP configuration 
The page for sip configuration for each of the server services were given separately, and for the sip2sip it was https://code.google.com/p/imsdroid/wiki/sip2sip_info 


The setup was quite straight forward, once after getting the sip credentials from sip2sip.info.,

wen into the Indentity tab and configured Display name, public identity, private Identity, password, realm, 

and in the network setting, Proxy-CSCF host, port, transport as UDP. 

a screenshot after it logged in given below



03-12 07:53:36.349    4769-5787/? I/tinyWRAP *INFO:
    RECV SIP Message:SIP/2.0 401 Unauthorized
    Via: SIP/2.0/UDP 192.168.1.2:55102;received=115.118.146.17;branch=z9hG4bK1661612924;rport=55102
    From: ;tag=1006014735
    To: ;tag=e7d4d6b46afb9bf88242924a8d869ebf.4922
    Call-ID: 323cff89-1b8f-7462-e9cd-c69cec5edebc
    CSeq: 1540698044 REGISTER
    WWW-Authenticate: Digest realm="sip2sip.info", nonce="5500f955101f5690fa5e3815cbe0de726e8a61d4"
    Server: SIP Thor on OpenSIPS XS 1.9.0
    Content-Length: 0
03-12 07:53:36.350    4769-5787/? I/tinyWRAP *INFO: State machine: tsip_dialog_register_InProgress_2_InProgress_X_401_407_421_494
03-12 07:53:36.351    4769-5787/? I/tinyWRAP *INFO:
    SEND SIP Message:REGISTER sip:sip2sip.info SIP/2.0
    Via: SIP/2.0/UDP 192.168.1.2:55102;branch=z9hG4bK1246479370;rport
    From: ;tag=1006014735
    To:
    Contact: ;expires=1700;+g.oma.sip-im;language="en,fr";+g.3gpp.smsip;+g.oma.sip-im.large-message;audio;+g.3gpp.icsi-ref="urn%3Aurn-7%3A3gpp-application.ims.iari.gsma-vs";+g.3gpp.cs-voice
    Call-ID: 323cff89-1b8f-7462-e9cd-c69cec5edebc
    CSeq: 1540698045 REGISTER
    Content-Length: 0
    Max-Forwards: 70
    Authorization: Digest username="mrrathish",realm="sip2sip.info",nonce="5500f955101f5690fa5e3815cbe0de726e8a61d4",uri="sip:sip2sip.info",response="f114c73ee9b5eb724fd0c6b032c05674",algorithm=MD5
    Allow: INVITE, ACK, CANCEL, BYE, MESSAGE, OPTIONS, NOTIFY, PRACK, UPDATE, REFER
    Privacy: none
    P-Access-Network-Info: ADSL;utran-cell-id-3gpp=00000000
    User-Agent: IM-client/OMA1.0 android-ngn-stack/v2.0.491 (doubango r701 - Spice Mi-498)
    P-Preferred-Identity:
    Supported: path
03-12 07:53:36.352    4769-5786/? D/org.doubango.ngn.services.impl.NgnSipService OnDialogEvent ((un)REGISTER request successfully sent.,1)
03-12 07:53:36.556    4769-5787/? I/tinyWRAP *INFO:
    RECV SIP Message:SIP/2.0 200 OK
    Via: SIP/2.0/UDP 192.168.1.2:55102;received=115.118.146.17;branch=z9hG4bK1246479370;rport=55102
    From: ;tag=1006014735
    To: ;tag=e7d4d6b46afb9bf88242924a8d869ebf.7c4f
    Call-ID: 323cff89-1b8f-7462-e9cd-c69cec5edebc
    CSeq: 1540698045 REGISTER
    Contact: ;expires=1700;received="sip:85.17.186.7:5060;target=%73%69%70:%31%31%35.%31%31%38.%31%34%36.%31%37:%35%35%31%30%32"
    Server: SIP Thor on OpenSIPS XS 1.9.0
    Content-Length: 0
    @x;T0


References

Tuesday, March 10, 2015

Components of IMS Architecture


HSS (Home Subscriber Server) - or USPF (user profile server function) is a master user database that supports the IMS network entities that actually handles the calls. It contains subscriber information, performs authentication and authorization of the user and can provide information about the subscribers location and IP information. It is similar to GSM HLR (Home location register) and Authentication Centre (AuC) A Subscriber Location Function (SLF) is needed to map user addresses when multiple HSS are used. 

User Identities 
Various identities may be associated with IMS, IP Multimedia Private Identity (IMPI), IP Multimedia Public Identity (IMPU), Globally Routable User Agent URI (GRUU), Wildcard Public User Identity. Both IMPU and IMPI are not phone numbers or other series of digits, but they are URIs that can be digits ( a tel url such as tel:+1-555-123-4567) or alphanumeric identifiers (a sIP URI such as sip:john.doe@example.com)

IP Multimedia Private Identity (IMPI)
IMPI is IP Multimedia Private Identity which is a permanently allocated global identity assigned by the home network operator and is used for example for Registration, Authorisation, Administratio and Accounting purposes. Every IMS user will have one IMPI 

IP Multimedia Public Identity (IMPU)
IMPU is used by any user for requesting communication to other users (e.g. this might be included on a business card). There can be multiple IMPUs per IMPI. The IMPU can be shared with another phone, so that both can be reached with same identity (for e.g. single phone number for entire family) 

Globally Routable User Agent URI 
Globally routable User Agent URI is an identify that identifies a unique combination of IMPU and UE instance. There are two types of GRUU, Public-GRUU and temporary GRUU/ 

P-GRUU - lives longer and reveals the IMPU 
T-GRUU - do not reveal IMPU and are valid only until the contact is explicitly de-registered or the current registration expires. 

Wild Card Public User Identity 
This expresses a set of IMPUs grouped together. The HSS subscriber database contains the IMPU, IMPI, IMSI, MISDN, subscriber service profiles, service triggers, and other information. 

References: 

Xcode project, finding number of lines

I was trying to get the total number of lines present in a project and below are some of the results from investigation.

The utility can be downloaded from  source forge at the link here http://cloc.sourceforge.net/


perl cloc-1.62.pl .//

running the above gave results like this. 

176 text files.
176 unique files.
4 files ignored.

http://cloc.sourceforge.net v 1.56  T=2.0 s (86.0 files/s, 10838.0 lines/s)
-------------------------------------------------------------------------------
Language                     files          blank        comment           code
-------------------------------------------------------------------------------
Objective C                     80           3848           1876          11844
C/C++ Header                    92            980           1716           1412
-------------------------------------------------------------------------------
SUM:                           172           4828           3592          13256

-------------------------------------------------------------------------------

references:

http://stackoverflow.com/questions/2003534/how-to-find-out-how-many-lines-of-code-there-are-in-an-xcode-project

Sunday, March 8, 2015

Java Sockets - Client and Server

Creating a socket server and socket client is easy as below.

Server

import java.net.*;
import java.io.*;
public class KnockKnockServer
{
public static void main (String a[])
{
        int portNumber = Integer.parseInt(a[0]);
        try
        {
             ServerSocket serverSocket = new ServerSocket(portNumber);
             Socket clientSocket = serverSocket.accept();
             PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             String inputLine, outputLine;
            
            // Initiate conversation with client
            KnockKnockProtocol kkp = new KnockKnockProtocol();
            outputLine = kkp.processInput(null);
            out.println(outputLine);
            
            while ((inputLine = in.readLine()) != null) {
                outputLine = kkp.processInput(inputLine);
                out.println(outputLine);
                if (outputLine.equals("Bye."))
                    break;
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
}
}
Client 
Client is pretty simple as well, just give the hostname and the ip at which the server listens. 

String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);

try (
Socket kkSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(kkSocket.getInputStream()));
)

references:
http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html