Message Transfer Part (MTP)

The Message Transfer Part (MTP) is part of the Signaling System 7 (SS7) used for communication in Public Switched Telephone Networks. MTP is responsible for reliable, unduplicated and in-sequence transport of SS7 messages between communication partners.

MTP is formally defined primarily in ITU-T recommendations Q.701Q.702Q.703Q.704 and Q.705. Tests for the MTP are specified in theITU-T recommendations Q.781 for MTP2 and in Q.782 for MTP3. These tests are used to validate the correct implementation of the MTP protocol.

Different countries use different variants of the MTP protocols. In North America, the formal standard followed is ANSI T1.111. In Europe, national MTP protocols are based on ETSI EN 300-008-1

The SS7 stack can be separated into four functional levels:

  • Level 1 is the Signalling Data Link Functional Level (Data Link Level).
  • Level 2 is the Signalling Link Functional Level (Link Level).
  • Level 3 is the Signalling Network Functional Level (Network Level).
  • Level 4 is the MTP User and consists of SCCPISUPTUP, or any other MTP User.

Level 1 through Level 3 comprise the MTP, and Level 4 the MTP userMTP Level 3 is sometimes abbreviated MTP3MTP Level 2MTP2. MTP and SCCP are together referred to as the Network Service Part (NSP).

There is no one-to-one mapping of MTP Levels 1 through 3 onto the OSI model. Instead, MTP provides the functionality of layers 12 and part of layer 3 in the OSI model. The part of layer 3 of the OSI model that MTP does not provide, is provided by SCCP or other Level 4 parts (MTP users).

Signalling Data Link Functional Level

MTP Level 1 is described in ITU-T Recommendation Q.702, and provides the Signalling Data Link functional level for narrowband signalling links. For broadband signalling links, ITU-T Recommendation Q.2110 or Q.2111 describe the signalling data link function.

MTP1 represents the physical layer. That is, the layer that is responsible for the connection of SS7 Signaling Points into the transmission network over which they communicate with each other. Primarily, this involves the conversion of messaging into electrical signal and the maintenance of the physical links through which these pass. In this way, it is analogous to the Layer 1 of ISDN or other, perhaps more familiar, protocols.

MTP1 normally uses a timeslot in an E-carrier or T-carrier.

Signalling Link Functional Level

MTP Level 2 is described in ITU-T Recommendation Q.703, and provides the Signalling Link functional level for narrowband signalling links. For broadband signalling links, ITU-T Recommendation Q.2140 and Q.2210 describe the signalling link function referred to as MTP3b. The signalling link functional level may also be provided using the SIGTRAN protocol M2PA described in RFC 4165.

MTP2 provides error detection and sequence checking, and retransmits unacknowledged messages. MTP2 uses packets called signal units to transmit SS7 messages. There are three types of signal units: Fill-in Signal Unit (FISU), Link Status Signal Unit (LSSU), Message Signal Unit (MSU).

Access to the signalling link functional level’s service interface can be provided over SCTP by the SIGTRAN protocol M2UA, described in RFC 3331.

MTP Level 2 is tested using the protocol tester and test specifications described in Q.755Q.755.1Q.780 and Q.781.

Signalling Network Functional Level

MTP Level 3 is described in ITU-T Recommendation Q.704, and provides the Signalling Network functional level for narrowband signalling links and, with only minor modifications described inITU-T Recommendation Q.2210, for broadband signalling links. The functions of MTP Level 3 may also be replaced with the Generic Signalling Transport Service described in ITU-T Recommendation Q.2150.0 as provided by MTP3b (Q.2150.1), SSCOP or SSCOPMCE (Q.2150.2) or SCTP (Q.2150.3). MTP Level 3 functions can also be provided by using the IETFSIGTRAN M3UA protocol, described in RFC 4666, in IPSP mode.

MTP3 provides routing functionality to transport signaling messages through the SS7 network to the requested endpoint. Each network element in the SS7 network has a unique address, thePoint Code (PC). Message routing is performed according to this address. A distinction is made between a Signaling Transfer Point (STP) which only performs MTP message routing functionalities and a Signaling End Point (SEP) which uses MTP to communicate with other SEPs (that is, telecom switches). MTP3 is also responsible for network management; when the availability of MTP2 data links changes, MTP3 establishes alternative links as required and propagates information about route availability through the network.

Access to the signalling network functional level’s service interface (as described in Q.701) can be provided over SCTP by the SIGTRAN protocol M3UA, described in RFC 4666.

MTP Level 3 is tested using the protocol tester and test specifications described in Q.755Q.755.1Q.780 and Q.782.

MTP Users

Level 4 consists of MTP Users. The remaining components of the SS7 stack are all directly, or indirectly, MTP Users. Some examples of parts at Level 4 are SCCPISUP and TUP.[7] The services provided to MTP Level 4 by the MTP (that is, MTP to MTP Users) is described in ITU-T Recommendation Q.701.

 

Reference : http://en.wikipedia.org/wiki/Message_Transfer_Part

Advertisements

Signalling Connection Control Part (SCCP) Protocol

The Signalling Connection Control Part (SCCP) is a network layer protocol that provides extended routingflow control, segmentation,connection-orientation, and error correction facilities in Signaling System 7 telecommunications networks. SCCP relies on the services of MTP for basic routing and error detection.

Routing facilities beyond MTP

Although MTP provides routing capabilities based upon the Point Code, SCCP allows routing using a Point Code and Subsystem number or a Global Title.

A Point Code is used to address a particular node on the network, whereas a Subsystem number addresses a specific application available on that node. SCCP employs a process called Global Title Translation to determine Point Codes from Global Titles so as to instruct MTP on where to route messages.

SCCP messages contain parameters which describe the type of addressing used, and how the message should be routed:

  • Address Indicator
    • Routing indicator
      • Route on Global Title
      • Route on Point Code/Subsystem Number
    • Global title indicator
      • No Global Title
      • Global Title includes Translation Type (TT), Numbering Plan Indicator (NPI) and Type of Number (TON)
      • Global Title includes Translation Type only
    • Subsystem indicator
      • Subsystem Number present
      • Subsystem Number not present
    • Point Code indicator
      • Point Code present
      • Point Code not present
  • Global Title
    • Address Indicator Coding
    • Address Indicator coded as national (the Address Indicator is treated as international if not specified)

Protocol classes

SCCP provides 5 classes of protocol to its applications:

  • Class 0: Basic connectionless.
  • Class 1: Sequenced connectionless.
  • Class 2: Basic connection-oriented.
  • Class 3: Flow control connection oriented.
  • Class 4: Error recovery and flow control connection oriented.

The connectionless protocol classes provide the capabilities needed to transfer one Network Service Data Unit (NSDU) in the “data” field of an XUDT, LUDT or UDT message. When one connectionless message is not sufficient to convey the user data contained in one NSDU, a segmenting/reassembly function for protocol classes 0 and 1 is provided. In this case, the SCCP at the originating node or in a relay node provides segmentation of the information into multiple segments prior to transfer in the “data” field of XUDT (or as a network option LUDT) messages. At the destination node, the NSDU is reassembled.

The connection-oriented protocol classes (protocol classes 2 and 3) provide the means to set up signalling connections in order to exchange a number of related NSDUs. The connection-oriented protocol classes also provide a segmenting and reassembling capability. If an NSDU is longer than 255 octets, it is split into multiple segments at the originating node, prior to transfer in the “data” field of DT messages. Each segment is less than or equal to 255 octets. At the destination node, the NSDU is reassembled.[3]

Class 0: Basic connectionless

The SCCP Class 0 protocol class is the most basic of the SCCP protocol classes. Network Service Data Units passed by higher layers to the SCCP in the originating node are delivered by the SCCP to higher layers in the destination node. They are transferred independently of each other. Therefore, they may be delivered to the SCCP user out-of-sequence. Thus, this protocol class corresponds to a pure connectionless network service. As a connectionless protocol, no network connection is established between the sender and the receiver.

Class 1: Sequenced connectionless

SCCP Class 1 builds on the capabilities of Class 0, with the addition of a sequence control parameter in the NSDU which allows the SCCP User to instruct the SCCP that a given stream of messages should be delivered in sequence. Therefore, Protocol Class 1 corresponds to an enhanced connectionless protocol with assurances of in-sequence delivery.

Class 2: Basic connection-oriented

SCCP Class 2 provides the facilities of Class 1, but also allows for an entity to establish a two-way dialog with another entity using SCCP.

Class 3: Flow control connection oriented

Class 3 service builds upon Class 2, but also allows for expedited (urgent) messages to be sent and received, and for errors in sequencing (segment re-assembly) to be detected and for SCCP to restart a connection should this occur.

Reference : http://en.wikipedia.org/wiki/Signalling_Connection_Control_Part

SIP Vs. SS7 Protocol

Signalling System No. 7 (SS7) is a set of telephony signaling protocols which are used to set up most of the world’s public switched telephone network telephone calls. The main purpose is to set up and tear down telephone calls. Other uses include number translation, local number portability, prepaid billing mechanisms, short message service (SMS), and a variety of other mass market services.

It is usually referenced as Signalling System No. 7 or Signalling System #7, or simply abbreviated to SS7. In North America it is often referred to asCCSS7, an abbreviation for Common Channel Signalling System 7. In some European countries, specifically the United Kingdom, it is sometimes called C7 (CCITT number 7) and is also known as number 7 and CCIS7 (Common Channel Interoffice Signaling 7). In Germany it is often called as N7 (Signalisierungssystem Nummer 7).

There is only one international SS7 protocol defined by ITU-T in its Q.700-series recommendations.[1] There are however, many national variants of the SS7 protocols. Most national variants are based on two widely deployed national variants as standardized by ANSI and ETSI, which are in turn based on the international protocol defined by ITU-T. Each national variant has its own unique characteristics. Some national variants with rather striking characteristics are the China (PRC) and Japan (TTC) national variants.

The Internet Engineering Task Force (IETF) has also defined level 2, 3, and 4 protocols that are compatible with SS7:

  • Message Transfer Part (MTP) level 2 (M2UA and M2PA)
  • Message Transfer Part (MTP) level 3 (M3UA)
  • Signalling Connection Control Part (SCCP) (SUA)

but use a Stream Control Transmission Protocol (SCTP) transport mechanism. This suite of protocols is called SIGTRAN.

AND

The Session Initiation Protocol (SIP) allows phone calls and similar communication sessions to be made over the Internet, private data networks, or cellular networks. It defines the messages that are sent between parties (signaling) which govern establishment, termination, and other essential elements of a call (or, more generally, a session, hence the name).

SIP is an IETF-defined signaling protocol and is widely used for controlling communication sessions such as voice and video calls over Internet Protocol (IP). The protocol can be used for creating, modifying and terminating two-party (unicast) or multiparty (multicast) sessions. Sessions may consist of one or several media streams, such as voice or video data.

Other SIP applications include video conferencing, streaming multimedia distribution, instant messagingpresence informationfile transfer and online games[citation needed].

SIP is an application layer protocol designed to be independent of the underlying transport layer; it can run on Transmission Control Protocol (TCP),User Datagram Protocol (UDP), or Stream Control Transmission Protocol (SCTP). It is a text-based protocol, incorporating many elements of theHypertext Transfer Protocol (HTTP) and the Simple Mail Transfer Protocol (SMTP).

 

Reference :
http://en.wikipedia.org/wiki/Signalling_System_No._7
http://en.wikipedia.org/wiki/Session_Initiation_Protocol

Session Control Protocol (SCP)

Several heavily used Internet applications such as FTPGOPHER, and HTTP use a protocol model in which every transaction requires a separate TCP connection. Since clients normally issue multiple requests to the same server, this model is quite inefficient, as it incurs all the connection start up costs for every single request.

SCP is a simple protocol which lets a server and client have multiple conversations over a single TCP connection. The protocol is designed to be simple to implement, and is modelled after TCP.

Services

SCP’s main service is dialogue control. This service allows either end of the connection to establish a virtual session over a single transport connection. SCP also allows a sender to indicate message boundaries, and allows a reciever to reject an incoming session.

Design goals

Unconfirmed service without negotiation.
SCP allows data to be sent with the session establishment; the recepient does not confirm successful connection establishment, but may reject unsuccessful attempts. This simplifies the design of the protocol, and removes the latency required for a confirmed operation.
Low overhead
SCP has a fixed overhead of 8 bytes per segment. This overhead is half the size of an IPNG address, and is only incurred once per segment, instead of once per packet.
Simple design
The session protocol should be simple enough to implement for a single application.

Protocol Description

Header Format:

Protocol Operation

Session ID allocation

Each session is allocated a session identifier. Session Identifiers below 1024 are reserved. Session IDs allocated by clients are even; those allocated by servers, odd.

Session establishment

A session is established by setting the SYN bit in the first message sent on that channel.

Graceful release

A session is ended by sending a message with the FIN bit set. Each end of a connection may be closed independently.

Disgraceful release

A session may be terminated by sending a message with the RST bit set. All pending data for that session should be discarded

Message boundaries

A message boundary is marked by sending a message with the PUSH bit set. The boundary is set at the final octet in this message, including that octet.

——

Reference : http://www.w3.org/Protocols/HTTP-NG/http-ng-scp.html

Advanced NFC for Android

This document describes advanced NFC topics, such as working with various tag technologies, writing to NFC tags, and foreground dispatching, which allows an application in the foreground to handle intents even when other applications filter for the same ones.

Working with Supported Tag Technologies


When working with NFC tags and Android-powered devices, the main format you use to read and write data on tags is NDEF. When a device scans a tag with NDEF data, Android provides support in parsing the message and delivering it in an NdefMessage when possible. There are cases, however, when you scan a tag that does not contain NDEF data or when the NDEF data could not be mapped to a MIME type or URI. In these cases, you need to open communication directly with the tag and read and write to it with your own protocol (in raw bytes). Android provides generic support for these use cases with the android.nfc.tech package, which is described in Table 1. You can use the getTechList() method to determine the technologies supported by the tag and create the corresponding TagTechnology object with one of classes provided by android.nfc.tech

Table 1. Supported tag technologies

Class Description
TagTechnology The interface that all tag technology classes must implement.
NfcA Provides access to NFC-A (ISO 14443-3A) properties and I/O operations.
NfcB Provides access to NFC-B (ISO 14443-3B) properties and I/O operations.
NfcF Provides access to NFC-F (JIS 6319-4) properties and I/O operations.
NfcV Provides access to NFC-V (ISO 15693) properties and I/O operations.
IsoDep Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations.
Ndef Provides access to NDEF data and operations on NFC tags that have been formatted as NDEF.
NdefFormatable Provides a format operations for tags that may be NDEF formattable.

The following tag technlogies are not required to be supported by Android-powered devices.

Table 2. Optional supported tag technologies

Class Description
MifareClassic Provides access to MIFARE Classic properties and I/O operations, if this Android device supports MIFARE.
MifareUltralight Provides access to MIFARE Ultralight properties and I/O operations, if this Android device supports MIFARE.

Working with tag technologies and the ACTION_TECH_DISCOVERED intent

When a device scans a tag that has NDEF data on it, but could not be mapped to a MIME or URI, the tag dispatch system tries to start an activity with the ACTION_TECH_DISCOVERED intent. The ACTION_TECH_DISCOVERED is also used when a tag with non-NDEF data is scanned. Having this fallback allows you to work with the data on the tag directly if the tag dispatch system could not parse it for you. The basic steps when working with tag technologies are as follows:

  1. Filter for an ACTION_TECH_DISCOVERED intent specifying the tag technologies that you want to handle. SeeFiltering for NFC intents for more information. In general, the tag dispatch system tries to start aACTION_TECH_DISCOVERED intent when an NDEF message cannot be mapped to a MIME type or URI, or if the tag scanned did not contain NDEF data. For more information on how this is determined, see The Tag Dispatch System.
  2. When your application receives the intent, obtain the Tag object from the intent:
    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
  3. Obtain an instance of a TagTechnology, by calling one of the get factory methods of the classes in theandroid.nfc.tech package. You can enumerate the supported technologies of the tag by callinggetTechList() before calling a get factory method. For example, to obtain an instance ofMifareUltralight from a Tag, do the following:
    MifareUltralight.get(intent.getParcelableExtra(NfcAdapter.EXTRA_TAG));

Reading and writing to tags

Reading and writing to an NFC tag involves obtaining the tag from the intent and opening communication with the tag. You must define your own protocol stack to read and write data to the tag. Keep in mind, however, that you can still read and write NDEF data when working directly with a tag. It is up to you how you want to structure things. The following example shows how to work with a MIFARE Ultralight tag.

package com.example.android.nfc;

import android.nfc.Tag;
import android.nfc.tech.MifareUltralight;
import android.util.Log;
import java.io.IOException;
import java.nio.charset.Charset;

public class MifareUltralightTagTester {

    private static final String TAG = MifareUltralightTagTester.class.getSimpleName();

    public void writeTag(Tag tag, String tagText) {
        MifareUltralight ultralight = MifareUltralight.get(tag);
        try {
            ultralight.connect();
            ultralight.writePage(4, "abcd".getBytes(Charset.forName("US-ASCII")));
            ultralight.writePage(5, "efgh".getBytes(Charset.forName("US-ASCII")));
            ultralight.writePage(6, "ijkl".getBytes(Charset.forName("US-ASCII")));
            ultralight.writePage(7, "mnop".getBytes(Charset.forName("US-ASCII")));
        } catch (IOException e) {
            Log.e(TAG, "IOException while closing MifareUltralight...", e);
        } finally {
            try {
                ultralight.close();
            } catch (IOException e) {
                Log.e(TAG, "IOException while closing MifareUltralight...", e);
            }
        }
    }

    public String readTag(Tag tag) {
        MifareUltralight mifare = MifareUltralight.get(tag);
        try {
            mifare.connect();
            byte[] payload = mifare.readPages(4);
            return new String(payload, Charset.forName("US-ASCII"));
        } catch (IOException e) {
            Log.e(TAG, "IOException while writing MifareUltralight
            message...", e);
        } finally {
            if (mifare != null) {
               try {
                   mifare.close();
               }
               catch (IOException e) {
                   Log.e(TAG, "Error closing tag...", e);
               }
            }
        }
        return null;
    }
}

Using the Foreground Dispatch System


The foreground dispatch system allows an activity to intercept an intent and claim priority over other activities that handle the same intent. Using this system involves constructing a few data structures for the Android system to be able to send the appropriate intents to your application. To enable the foreground dispatch system:

    1. Add the following code in the onCreate() method of your activity:
      1. Create a PendingIntent object so the Android system can populate it with the details of the tag when it is scanned.
        PendingIntent pendingIntent = PendingIntent.getActivity(
            this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
      2. Declare intent filters to handle the intents that you want to intercept. The foreground dispatch system checks the specified intent filters with the intent that is received when the device scans a tag. If it matches, then your application handles the intent. If it does not match, the foreground dispatch system falls back to the intent dispatch system. Specifying a null array of intent filters and technology filters, specifies that you want to filter for all tags that fallback to the TAG_DISCOVERED intent. The code snippet below handles all MIME types for NDEF_DISCOVERED. You should only handle the ones that you need.
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
            try {
                ndef.addDataType("*/*");    /* Handles all MIME based dispatches.
                                               You should specify only the ones that you need. */
            }
            catch (MalformedMimeTypeException e) {
                throw new RuntimeException("fail", e);
            }
           intentFiltersArray = new IntentFilter[] {ndef, };
      3. Set up an array of tag technologies that your application wants to handle. Call theObject.class.getName() method to obtain the class of the technology that you want to support.
        techListsArray = new String[][] { new String[] { NfcF.class.getName() } };
    2. Override the following activity lifecycle callbacks and add logic to enable and disable the foreground dispatch when the activity loses (onPause()) and regains (onResume()) focus.enableForegroundDispatch() must be called from the main thread and only when the activity is in the foreground (calling in onResume() guarantees this). You also need to implement the onNewIntent callback to process the data from the scanned NFC tag.
public void onPause() {
    super.onPause();
    mAdapter.disableForegroundDispatch(this);
}

public void onResume() {
    super.onResume();
    mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
}

public void onNewIntent(Intent intent) {
    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    //do something with tagFromIntent
}

See the ForegroundDispatch sample from API Demos for the complete sample.

Reference : http://developer.android.com/guide/topics/connectivity/nfc/advanced-nfc.html

NFC Basics for Android

This document describes the basic NFC tasks you perform in Android. It explains how to send and receive NFC data in the form of NDEF messages and describes the Android framework APIs that support these features. For more advanced topics, including a discussion of working with non-NDEF data, see Advanced NFC.

There are two major uses cases when working with NDEF data and Android:

  • Reading NDEF data from an NFC tag
  • Beaming NDEF messages from one device to another with Android Beam™

Reading NDEF data from an NFC tag is handled with the tag dispatch system, which analyzes discovered NFC tags, appropriately categorizes the data, and starts an application that is interested in the categorized data. An application that wants to handle the scanned NFC tag can declare an intent filter and request to handle the data.

The Android Beam™ feature allows a device to push an NDEF message onto another device by physically tapping the devices together. This interaction provides an easier way to send data than other wireless technologies like Bluetooth, because with NFC, no manual device discovery or pairing is required. The connection is automatically started when two devices come into range. Android Beam is available through a set of NFC APIs, so any application can transmit information between devices. For example, the Contacts, Browser, and YouTube applications use Android Beam to share contacts, web pages, and videos with other devices.

The Tag Dispatch System


Android-powered devices are usually looking for NFC tags when the screen is unlocked, unless NFC is disabled in the device’s Settings menu. When an Android-powered device discovers an NFC tag, the desired behavior is to have the most appropriate activity handle the intent without asking the user what application to use. Because devices scan NFC tags at a very short range, it is likely that making users manually select an activity would force them to move the device away from the tag and break the connection. You should develop your activity to only handle the NFC tags that your activity cares about to prevent the Activity Chooser from appearing.

To help you with this goal, Android provides a special tag dispatch system that analyzes scanned NFC tags, parses them, and tries to locate applications that are interested in the scanned data. It does this by:

  1. Parsing the NFC tag and figuring out the MIME type or a URI that identifies the data payload in the tag.
  2. Encapsulating the MIME type or URI and the payload into an intent. These first two steps are described inHow NFC tags are mapped to MIME types and URIs.
  3. Starts an activity based on the intent. This is described in How NFC Tags are Dispatched to Applications.

How NFC tags are mapped to MIME types and URIs

Before you begin writing your NFC applications, it is important to understand the different types of NFC tags, how the tag dispatch system parses NFC tags, and the special work that the tag dispatch system does when it detects an NDEF message. NFC tags come in a wide array of technologies and can also have data written to them in many different ways. Android has the most support for the NDEF standard, which is defined by the NFC Forum.

NDEF data is encapsulated inside a message (NdefMessage) that contains one or more records (NdefRecord). Each NDEF record must be well-formed according to the specification of the type of record that you want to create. Android also supports other types of tags that do not contain NDEF data, which you can work with by using the classes in the android.nfc.tech package. To learn more about these technologies, see theAdvanced NFC topic. Working with these other types of tags involves writing your own protocol stack to communicate with the tags, so we recommend using NDEF when possible for ease of development and maximum support for Android-powered devices.

Note: To download complete NDEF specifications, go to the NFC Forum Specification Download site and seeCreating common types of NDEF records for examples of how to construct NDEF records.

Now that you have some background in NFC tags, the following sections describe in more detail how Android handles NDEF formatted tags. When an Android-powered device scans an NFC tag containing NDEF formatted data, it parses the message and tries to figure out the data’s MIME type or identifying URI. To do this, the system reads the first NdefRecord inside the NdefMessage to determine how to interpret the entire NDEF message (an NDEF message can have multiple NDEF records). In a well-formed NDEF message, the first NdefRecordcontains the following fields:

3-bit TNF (Type Name Format)
Indicates how to interpret the variable length type field. Valid values are described in described in Table 1.
Variable length type
Describes the type of the record. If using TNF_WELL_KNOWN, use this field to specify the Record Type Definition (RTD). Valid RTD values are described in Table 2.
Variable length ID
A unique identifier for the record. This field is not used often, but if you need to uniquely identify a tag, you can create an ID for it.
Variable length payload
The actual data payload that you want to read or write. An NDEF message can contain multiple NDEF records, so don’t assume the full payload is in the first NDEF record of the NDEF message.

The tag dispatch system uses the TNF and type fields to try to map a MIME type or URI to the NDEF message. If successful, it encapsulates that information inside of a ACTION_NDEF_DISCOVERED intent along with the actual payload. However, there are cases when the tag dispatch system cannot determine the type of data based on the first NDEF record. This happens when the NDEF data cannot be mapped to a MIME type or URI, or when the NFC tag does not contain NDEF data to begin with. In such cases, a Tag object that has information about the tag’s technologies and the payload are encapsulated inside of a ACTION_TECH_DISCOVERED intent instead.

Table 1. describes how the tag dispatch system maps TNF and type fields to MIME types or URIs. It also describes which TNFs cannot be mapped to a MIME type or URI. In these cases, the tag dispatch system falls back to ACTION_TECH_DISCOVERED.

For example, if the tag dispatch system encounters a record of type TNF_ABSOLUTE_URI, it maps the variable length type field of that record into a URI. The tag dispatch system encapsulates that URI in the data field of anACTION_NDEF_DISCOVERED intent along with other information about the tag, such as the payload. On the other hand, if it encounters a record of type TNF_UNKNOWN, it creates an intent that encapsulates the tag’s technologies instead.

Table 1. Supported TNFs and their mappings

Type Name Format (TNF) Mapping
TNF_ABSOLUTE_URI URI based on the type field.
TNF_EMPTY Falls back to ACTION_TECH_DISCOVERED.
TNF_EXTERNAL_TYPE URI based on the URN in the type field. The URN is encoded into the NDEF type field in a shortened form: <domain_name>:<service_name>. Android maps this to a URI in the form: vnd.android.nfc://ext/<domain_name>:<service_name>.
TNF_MIME_MEDIA MIME type based on the type field.
TNF_UNCHANGED Invalid in the first record, so falls back to ACTION_TECH_DISCOVERED.
TNF_UNKNOWN Falls back to ACTION_TECH_DISCOVERED.
TNF_WELL_KNOWN MIME type or URI depending on the Record Type Definition (RTD), which you set in the type field. See Table 2. for more information on available RTDs and their mappings.

Table 2. Supported RTDs for TNF_WELL_KNOWN and their mappings

Record Type Definition (RTD) Mapping
RTD_ALTERNATIVE_CARRIER Falls back to ACTION_TECH_DISCOVERED.
RTD_HANDOVER_CARRIER Falls back to ACTION_TECH_DISCOVERED.
RTD_HANDOVER_REQUEST Falls back to ACTION_TECH_DISCOVERED.
RTD_HANDOVER_SELECT Falls back to ACTION_TECH_DISCOVERED.
RTD_SMART_POSTER URI based on parsing the payload.
RTD_TEXT MIME type of text/plain.
RTD_URI URI based on payload.

How NFC Tags are Dispatched to Applications

When the tag dispatch system is done creating an intent that encapsulates the NFC tag and its identifying information, it sends the intent to an interested application that filters for the intent. If more than one application can handle the intent, the Activity Chooser is presented so the user can select the Activity. The tag dispatch system defines three intents, which are listed in order of highest to lowest priority:

  1. ACTION_NDEF_DISCOVERED: This intent is used to start an Activity when a tag that contains an NDEF payload is scanned and is of a recognized type. This is the highest priority intent, and the tag dispatch system tries to start an Activity with this intent before any other intent, whenever possible.
  2. ACTION_TECH_DISCOVERED: If no activities register to handle the ACTION_NDEF_DISCOVERED intent, the tag dispatch system tries to start an application with this intent. This intent is also directly started (without starting ACTION_NDEF_DISCOVERED first) if the tag that is scanned contains NDEF data that cannot be mapped to a MIME type or URI, or if the tag does not contain NDEF data but is of a known tag technology.
  3. ACTION_TAG_DISCOVERED: This intent is started if no activities handle the ACTION_NDEF_DISCOVERED orACTION_TECH_DISCOVERED intents.

The basic way the tag dispatch system works is as follows:

  1. Try to start an Activity with the intent that was created by the tag dispatch system when parsing the NFC tag (either ACTION_NDEF_DISCOVERED or ACTION_TECH_DISCOVERED).
  2. If no activities filter for that intent, try to start an Activity with the next lowest priority intent (eitherACTION_TECH_DISCOVERED or ACTION_TAG_DISCOVERED) until an application filters for the intent or until the tag dispatch system tries all possible intents.
  3. If no applications filter for any of the intents, do nothing.

Figure 1. Tag Dispatch System

Whenever possible, work with NDEF messages and the ACTION_NDEF_DISCOVERED intent, because it is the most specific out of the three. This intent allows you to start your application at a more appropriate time than the other two intents, giving the user a better experience.

Requesting NFC Access in the Android Manifest


Before you can access a device’s NFC hardware and properly handle NFC intents, declare these items in yourAndroidManifest.xml file:

  • The NFC <uses-permission> element to access the NFC hardware:
    <uses-permission android:name="android.permission.NFC" />
  • The minimum SDK version that your application can support. API level 9 only supports limited tag dispatch via ACTION_TAG_DISCOVERED, and only gives access to NDEF messages via the EXTRA_NDEF_MESSAGESextra. No other tag properties or I/O operations are accessible. API level 10 includes comprehensive reader/writer support as well as foreground NDEF pushing, and API level 14 provides an easier way to push NDEF messages to other devices with Android Beam and extra convenience methods to create NDEF records.
    <uses-sdk android:minSdkVersion="10"/>
  • The uses-feature element so that your application shows up in Google Play only for devices that have NFC hardware:
    <uses-feature android:name="android.hardware.nfc" android:required="true" />

    If your application uses NFC functionality, but that functionality is not crucial to your application, you can omit the uses-feature element and check for NFC avalailbility at runtime by checking to see ifgetDefaultAdapter() is null.

Filtering for NFC Intents


To start your application when an NFC tag that you want to handle is scanned, your application can filter for one, two, or all three of the NFC intents in the Android manifest. However, you usually want to filter for theACTION_NDEF_DISCOVERED intent for the most control of when your application starts. TheACTION_TECH_DISCOVERED intent is a fallback for ACTION_NDEF_DISCOVERED when no applications filter forACTION_NDEF_DISCOVERED or for when the payload is not NDEF. Filtering for ACTION_TAG_DISCOVERED is usually too general of a category to filter on. Many applications will filter for ACTION_NDEF_DISCOVERED orACTION_TECH_DISCOVERED before ACTION_TAG_DISCOVERED, so your application has a low probability of starting. ACTION_TAG_DISCOVERED is only available as a last resort for applications to filter for in the cases where no other applications are installed to handle the ACTION_NDEF_DISCOVERED orACTION_TECH_DISCOVEREDintent.

Because NFC tag deployments vary and are many times not under your control, this is not always possible, which is why you can fallback to the other two intents when necessary. When you have control over the types of tags and data written, it is recommended that you use NDEF to format your tags. The following sections describe how to filter for each type of intent.

ACTION_NDEF_DISCOVERED

To filter for ACTION_NDEF_DISCOVERED intents, declare the intent filter along with the type of data that you want to filter for. The following example filters for ACTION_NDEF_DISCOVERED intents with a MIME type oftext/plain:

<intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="text/plain" />
</intent-filter>

The following example filters for a URI in the form of http://developer.android.com/index.html.

<intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
    <category android:name="android.intent.category.DEFAULT"/>
   <data android:scheme="http"
              android:host="developer.android.com"
              android:pathPrefix="/index.html" />
</intent-filter>

ACTION_TECH_DISCOVERED

If your activity filters for the ACTION_TECH_DISCOVERED intent, you must create an XML resource file that specifies the technologies that your activity supports within a tech-list set. Your activity is considered a match if a tech-list set is a subset of the technologies that are supported by the tag, which you can obtain by calling getTechList().

For example, if the tag that is scanned supports MifareClassic, NdefFormatable, and NfcA, your tech-list set must specify all three, two, or one of the technologies (and nothing else) in order for your activity to be matched.

The following sample defines all of the technologies. You can remove the ones that you do not need. Save this file (you can name it anything you wish) in the <project-root>/res/xml folder.

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <tech-list>
        <tech>android.nfc.tech.IsoDep</tech>
        <tech>android.nfc.tech.NfcA</tech>
        <tech>android.nfc.tech.NfcB</tech>
        <tech>android.nfc.tech.NfcF</tech>
        <tech>android.nfc.tech.NfcV</tech>
        <tech>android.nfc.tech.Ndef</tech>
        <tech>android.nfc.tech.NdefFormatable</tech>
        <tech>android.nfc.tech.MifareClassic</tech>
        <tech>android.nfc.tech.MifareUltralight</tech>
    </tech-list>
</resources>

You can also specify multiple tech-list sets. Each of the tech-list sets is considered independently, and your activity is considered a match if any single tech-list set is a subset of the technologies that are returned by getTechList(). This provides AND and OR semantics for matching technologies. The following example matches tags that can support the NfcA and Ndef technologies or can support the NfcB and Ndef technologies:

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <tech-list>
        <tech>android.nfc.tech.NfcA</tech>
        <tech>android.nfc.tech.Ndef</tech>
    </tech-list>
</resources>

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <tech-list>
        <tech>android.nfc.tech.NfcB</tech>
        <tech>android.nfc.tech.Ndef</tech>
    </tech-list>
</resources>

In your AndroidManifest.xml file, specify the resource file that you just created in the <meta-data> element inside the <activity> element like in the following example:

<activity>
...
<intent-filter>
    <action android:name="android.nfc.action.TECH_DISCOVERED"/>
</intent-filter>

<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
    android:resource="@xml/nfc_tech_filter" />
...
</activity>

For more information about working with tag technologies and the ACTION_TECH_DISCOVERED intent, seeWorking with Supported Tag Technologies in the Advanced NFC document.

ACTION_TAG_DISCOVERED

To filter for ACTION_TAG_DISCOVERED use the following intent filter:

<intent-filter>
    <action android:name="android.nfc.action.TAG_DISCOVERED"/>
</intent-filter>

Obtaining information from intents

If an activity starts because of an NFC intent, you can obtain information about the scanned NFC tag from the intent. Intents can contain the following extras depending on the tag that was scanned:

To obtain these extras, check to see if your activity was launched with one of the NFC intents to ensure that a tag was scanned, and then obtain the extras out of the intent. The following example checks for theACTION_NDEF_DISCOVERED intent and gets the NDEF messages from an intent extra.

public void onResume() {
    super.onResume();
    ...
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (rawMsgs != null) {
            msgs = new NdefMessage[rawMsgs.length];
            for (int i = 0; i < rawMsgs.length; i++) {
                msgs[i] = (NdefMessage) rawMsgs[i];
            }
        }
    }
    //process the msgs array
}

Alternatively, you can obtain a Tag object from the intent, which will contain the payload and allow you to enumerate the tag’s technologies:

Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

Creating Common Types of NDEF Records


This section describes how to create common types of NDEF records to help you when writing to NFC tags or sending data with Android Beam. Starting with Android 4.0 (API level 14), the createUri() method is available to help you create URI records automatically. Starting in Android 4.1 (API level 16), createExternal() andcreateMime() are available to help you create MIME and external type NDEF records. Use these helper methods whenever possible to avoid mistakes when manually creating NDEF records.

This section also describes how to create the corresponding intent filter for the record. All of these NDEF record examples should be in the first NDEF record of the NDEF message that you are writing to a tag or beaming.

TNF_ABSOLUTE_URI

Note: We recommend that you use the RTD_URI type instead of TNF_ABSOLUTE_URI, because it is more efficient.

You can create a TNF_ABSOLUTE_URI NDEF record in the following way:

NdefRecord uriRecord = new NdefRecord(
    NdefRecord.TNF_ABSOLUTE_URI ,
    "http://developer.android.com/index.html".getBytes(Charset.forName("US-ASCII")),
    new byte[0], new byte[0]);

The intent filter for the previous NDEF record would look like this:

<intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:scheme="http"
        android:host="developer.android.com"
        android:pathPrefix="/index.html" />
</intent-filter>

TNF_MIME_MEDIA

You can create a TNF_MIME_MEDIA NDEF record in the following ways.

Using the createMime() method:

NdefRecord mimeRecord = NdefRecord.createMime("application/vnd.com.example.android.beam",
    "Beam me up, Android".getBytes(Charset.forName("US-ASCII")));

Creating the NdefRecord manually:

NdefRecord mimeRecord = new NdefRecord(
    NdefRecord.TNF_MIME_MEDIA ,
    "application/vnd.com.example.android.beam".getBytes(Charset.forName("US-ASCII")),
    new byte[0], "Beam me up, Android!".getBytes(Charset.forName("US-ASCII")));

The intent filter for the previous NDEF records would look like this:

<intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="application/vnd.com.example.android.beam" />
</intent-filter>

TNF_WELL_KNOWN with RTD_TEXT

You can create a TNF_WELL_KNOWN NDEF record in the following way:

public NdefRecord createTextRecord(String payload, Locale locale, boolean encodeInUtf8) {
    byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));
    Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
    byte[] textBytes = payload.getBytes(utfEncoding);
    int utfBit = encodeInUtf8 ? 0 : (1 << 7);
    char status = (char) (utfBit + langBytes.length);
    byte[] data = new byte[1 + langBytes.length + textBytes.length];
    data[0] = (byte) status;
    System.arraycopy(langBytes, 0, data, 1, langBytes.length);
    System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
    NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
    NdefRecord.RTD_TEXT, new byte[0], data);
    return record;
}

the intent filter would look like this:

<intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="text/plain" />
</intent-filter>

TNF_WELL_KNOWN with RTD_URI

You can create a TNF_WELL_KNOWN NDEF record in the following ways.

Using the createUri(String) method:

NdefRecord rtdUriRecord1 = NdefRecord.createUri("http://example.com");

Using the createUri(Uri) method:

Uri uri = new Uri("http://example.com");
NdefRecord rtdUriRecord2 = NdefRecord.createUri(uri);

Creating the NdefRecord manually:

byte[] uriField = "example.com".getBytes(Charset.forName("US-ASCII"));
byte[] payload = new byte[uriField.length + 1];              //add 1 for the URI Prefix
byte payload[0] = 0x01;                                      //prefixes http://www. to the URI
System.arraycopy(uriField, 0, payload, 1, uriField.length);  //appends URI to payload
NdefRecord rtdUriRecord = new NdefRecord(
    NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, new byte[0], payload);

The intent filter for the previous NDEF records would look like this:

<intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:scheme="http"
        android:host="example.com"
        android:pathPrefix="" />
</intent-filter>

TNF_EXTERNAL_TYPE

You can create a TNF_EXTERNAL_TYPE NDEF record in the following ways:

Using the createExternal() method:

byte[] payload; //assign to your data
String domain = "com.example"; //usually your app's package name
String type = "externalType";
NdefRecord extRecord = NdefRecord.createExternal(domain, type, payload);

Creating the NdefRecord manually:

byte[] payload;
...
NdefRecord extRecord = new NdefRecord(
    NdefRecord.TNF_EXTERNAL_TYPE, "com.example:externalType", new byte[0], payload);

The intent filter for the previous NDEF records would look like this:

<intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:scheme="vnd.android.nfc"
        android:host="ext"
        android:pathPrefix="/com.example:externalType"/>
</intent-filter>

Use TNF_EXTERNAL_TYPE for more generic NFC tag deployments to better support both Android-powered and non-Android-powered devices.

Note: URNs for TNF_EXTERNAL_TYPE have a canonical format of:urn:nfc:ext:example.com:externalType, however the NFC Forum RTD specification declares that theurn:nfc:ext: portion of the URN must be ommitted from the NDEF record. So all you need to provide is the domain (example.com in the example) and type (externalType in the example) separated by a colon. When dispatching TNF_EXTERNAL_TYPE, Android converts the urn:nfc:ext:example.com:externalType URN to a vnd.android.nfc://ext/example.com:externalType URI, which is what the intent filter in the example declares.

Android Application Records

Introduced in Android 4.0 (API level 14), an Android Application Record (AAR) provides a stronger certainty that your application is started when an NFC tag is scanned. An AAR has the package name of an application embedded inside an NDEF record. You can add an AAR to any NDEF record of your NDEF message, because Android searches the entire NDEF message for AARs. If it finds an AAR, it starts the application based on the package name inside the AAR. If the application is not present on the device, Google Play is launched to download the application.

AARs are useful if you want to prevent other applications from filtering for the same intent and potentially handling specific tags that you have deployed. AARs are only supported at the application level, because of the package name constraint, and not at the Activity level as with intent filtering. If you want to handle an intent at the Activity level, use intent filters.

If a tag contains an AAR, the tag dispatch system dispatches in the following manner:

  1. Try to start an Activity using an intent filter as normal. If the Activity that matches the intent also matches the AAR, start the Activity.
  2. If the Activity that filters for the intent does not match the AAR, if multiple Activities can handle the intent, or if no Activity handles the intent, start the application specified by the AAR.
  3. If no application can start with the AAR, go to Google Play to download the application based on the AAR.

 

Note: You can override AARs and the intent dispatch system with the foreground dispatch system, which allows a foreground activity to have priority when an NFC tag is discovered. With this method, the activity must be in the foreground to override AARs and the intent dispatch system.

If you still want to filter for scanned tags that do not contain an AAR, you can declare intent filters as normal. This is useful if your application is interested in other tags that do not contain an AAR. For example, maybe you want to guarantee that your application handles proprietary tags that you deploy as well as general tags deployed by third parties. Keep in mind that AARs are specific to Android 4.0 devices or later, so when deploying tags, you most likely want to use a combination of AARs and MIME types/URIs to support the widest range of devices. In addition, when you deploy NFC tags, think about how you want to write your NFC tags to enable support for the most devices (Android-powered and other devices). You can do this by defining a relatively unique MIME type or URI to make it easier for applications to distinguish.

Android provides a simple API to create an AAR, createApplicationRecord(). All you need to do is embed the AAR anywhere in your NdefMessage. You do not want to use the first record of your NdefMessage, unless the AAR is the only record in the NdefMessage. This is because the Android system checks the first record of anNdefMessage to determine the MIME type or URI of the tag, which is used to create an intent for applications to filter. The following code shows you how to create an AAR:

NdefMessage msg = new NdefMessage(
        new NdefRecord[] {
            ...,
            NdefRecord.createApplicationRecord("com.example.android.beam")}

Beaming NDEF Messages to Other Devices


Android Beam allows simple peer-to-peer data exchange between two Android-powered devices. The application that wants to beam data to another device must be in the foreground and the device receiving the data must not be locked. When the beaming device comes in close enough contact with a receiving device, the beaming device displays the “Touch to Beam” UI. The user can then choose whether or not to beam the message to the receiving device.

Note: Foreground NDEF pushing was available at API level 10, which provides similar functionality to Android Beam. These APIs have since been deprecated, but are available to support older devices. SeeenableForegroundNdefPush() for more information.

You can enable Android Beam for your application by calling one of the two methods:

An activity can only push one NDEF message at a time, so setNdefPushMessageCallback() takes precedence over setNdefPushMessage() if both are set. To use Android Beam, the following general guidelines must be met:

  • The activity that is beaming the data must be in the foreground. Both devices must have their screens unlocked.
  • You must encapsulate the data that you are beaming in an NdefMessage object.
  • The NFC device that is receiving the beamed data must support the com.android.npp NDEF push protocol or NFC Forum’s SNEP (Simple NDEF Exchange Protocol). The com.android.npp protocol is required for devices on API level 9 (Android 2.3) to API level 13 (Android 3.2). com.android.npp and SNEP are both required on API level 14 (Android 4.0) and later.

Note: If your activity enables Android Beam and is in the foreground, the standard intent dispatch system is disabled. However, if your activity also enables foreground dispatching, then it can still scan tags that match the intent filters set in the foreground dispatching.

To enable Android Beam:

  1. Create an NdefMessage that contains the NdefRecords that you want to push onto the other device.
  2. Call setNdefPushMessage() with a NdefMessage or call setNdefPushMessageCallback passing in aNfcAdapter.CreateNdefMessageCallback object in the onCreate() method of your activity. These methods require at least one activity that you want to enable with Android Beam, along with an optional list of other activities to activate.In general, you normally use setNdefPushMessage() if your Activity only needs to push the same NDEF message at all times, when two devices are in range to communicate. You usesetNdefPushMessageCallback when your application cares about the current context of the application and wants to push an NDEF message depending on what the user is doing in your application.

The following sample shows how a simple activity calls NfcAdapter.CreateNdefMessageCallback in theonCreate() method of an activity (see AndroidBeamDemo for the complete sample). This example also has methods to help you create a MIME record:

package com.example.android.beam;

import android.app.Activity;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.TextView;
import android.widget.Toast;
import java.nio.charset.Charset;


public class Beam extends Activity implements CreateNdefMessageCallback {
    NfcAdapter mNfcAdapter;
    TextView textView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView textView = (TextView) findViewById(R.id.textView);
        // Check for available NFC Adapter
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        // Register callback
        mNfcAdapter.setNdefPushMessageCallback(this, this);
    }

    @Override
    public NdefMessage createNdefMessage(NfcEvent event) {
        String text = ("Beam me up, Android!\n\n" +
                "Beam Time: " + System.currentTimeMillis());
        NdefMessage msg = new NdefMessage(
                new NdefRecord[] { createMime(
                        "application/vnd.com.example.android.beam", text.getBytes())
         /**
          * The Android Application Record (AAR) is commented out. When a device
          * receives a push with an AAR in it, the application specified in the AAR
          * is guaranteed to run. The AAR overrides the tag dispatch system.
          * You can add it back in to guarantee that this
          * activity starts when receiving a beamed message. For now, this code
          * uses the tag dispatch system.
          */
          //,NdefRecord.createApplicationRecord("com.example.android.beam")
        });
        return msg;
    }

    @Override
    public void onResume() {
        super.onResume();
        // Check to see that the Activity started due to an Android Beam
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            processIntent(getIntent());
        }
    }

    @Override
    public void onNewIntent(Intent intent) {
        // onResume gets called after this to handle the intent
        setIntent(intent);
    }

    /**
     * Parses the NDEF Message from the intent and prints to the TextView
     */
    void processIntent(Intent intent) {
        textView = (TextView) findViewById(R.id.textView);
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                NfcAdapter.EXTRA_NDEF_MESSAGES);
        // only one message sent during the beam
        NdefMessage msg = (NdefMessage) rawMsgs[0];
        // record 0 contains the MIME type, record 1 is the AAR, if present
        textView.setText(new String(msg.getRecords()[0].getPayload()));
    }
}

Note that this code comments out an AAR, which you can remove. If you enable the AAR, the application specified in the AAR always receives the Android Beam message. If the application is not present, Google Play is started to download the application. Therefore, the following intent filter is not technically necessary for Android 4.0 devices or later if the AAR is used:

<intent-filter>
  <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
  <category android:name="android.intent.category.DEFAULT"/>
  <data android:mimeType="application/vnd.com.example.android.beam"/>
</intent-filter>

With this intent filter, the com.example.android.beam application now can be started when it scans an NFC tag or receives an Android Beam with an AAR of type com.example.android.beam, or when an NDEF formatted message contains a MIME record of type application/vnd.com.example.android.beam.

Even though AARs guarantee an application is started or downloaded, intent filters are recommended, because they let you start an Activity of your choice in your application instead of always starting the main Activity within the package specified by an AAR. AARs do not have Activity level granularity. Also, because some Android-powered devices do not support AARs, you should also embed identifying information in the first NDEF record of your NDEF messages and filter for that as well, just in case. See Creating Common Types of NDEF records for more information on how to create records.

Reference : http://developer.android.com/guide/topics/connectivity/nfc/nfc.html

What is Remote Authentication Dial In User Service (RADIUS)?

Remote Authentication Dial In User Service (RADIUS) is a networking protocol that provides centralized Authentication, Authorization, and Accounting (AAA) management for computers to connect and use a network service. RADIUS was developed by Livingston Enterprises, Inc., in 1991 as an access server authentication and accounting protocol and later brought into the Internet Engineering Task Force (IETF) standards.[1]

Because of the broad support and the ubiquitous nature of the RADIUS protocol, it is often used by ISPs and enterprises to manage access to theInternet or internal networkswireless networks, and integrated e-mail services. These networks may incorporate modemsDSLaccess points,VPNsnetwork portsweb servers, etc.[2]

RADIUS is a client/server protocol that runs in the application layer, using UDP as transport. The Remote Access Server, the Virtual Private Network server, the Network switch with port-based authentication, and the Network Access Server (NAS), are all gateways that control access to the network, and all have a RADIUS client component that communicates with the RADIUS server. The RADIUS server is usually a background process running on a UNIX or Microsoft Windows server.[3] RADIUS serves three functions:

  1. to authenticate users or devices before granting them access to a network,
  2. to authorize those users or devices for certain network services and
  3. to account for usage of those services.

AAA

RADIUS servers use the AAA concept to manage network access in the following two-step process, also known as an “AAA transaction”. AAA stands for “authentication, authorization and accounting”. Authentication and Authorization characteristics in RADIUS are described in RFC 2865 while Accounting is described by RFC 2866.

Authentication and authorization

The user or machine sends a request to a Remote Access Server (RAS) to gain access to a particular network resource using access credentials. The credentials are passed to the RAS device via the link-layer protocol – for example, Point-to-Point Protocol (PPP) in the case of many dialup or DSL providers or posted in an HTTPS secure web form.

In turn, the RAS sends a RADIUS Access Request message to the RADIUS server, requesting authorization to grant access via the RADIUS protocol.[4]

This request includes access credentials, typically in the form of username and password or security certificate provided by the user. Additionally, the request may contain other information which the RAS knows about the user, such as its network address or phone number, and information regarding the user’s physical point of attachment to the RAS.

The RADIUS server checks that the information is correct using authentication schemes like PAPCHAP or EAP. The user’s proof of identification is verified, along with, optionally, other information related to the request, such as the user’s network address or phone number, account status and specific network service access privileges. Historically, RADIUS servers checked the user’s information against a locally stored flat file database. Modern RADIUS servers can do this, or can refer to external sources—commonly SQLKerberosLDAP, or Active Directory servers—to verify the user’s credentials.

RADIUS Authentication and Authorization Flow

The RADIUS server then returns one of three responses to the RAS : 1) Access Reject, 2) Access Challenge or 3) Access Accept.

  • Access Reject – The user is unconditionally denied access to all requested network resources. Reasons may include failure to provide proof of identification or an unknown or inactive user account.
  • Access Challenge – Requests additional information from the user such as a secondary password, PIN, token or card. Access Challenge is also used in more complex authentication dialogs where a secure tunnel is established between the user machine and the Radius Server in a way that the access credentials are hidden from the RAS.
  • Access Accept – The user is granted access. Once the user is authenticated, the RADIUS server will often check that the user is authorised to use the network service requested. A given user may be allowed to use a company’s wireless network, but not its VPN service, for example. Again, this information may be stored locally on the RADIUS server, or may be looked up in an external source like LDAP or Active Directory.

Each of these three RADIUS responses may include a Reply-Message attribute which may give a reason for the rejection, the prompt for the challenge, or a welcome message for the accept. The text in the attribute can be passed on to the user in a return web page.

Authorization attributes are conveyed to the RAS stipulating terms of access to be granted. For example: the following authorization attributes may be included in an Access-Accept.

  • The specific IP address to be assigned to the user
  • The address pool from which the user’s IP should be chosen
  • The maximum length that the user may remain connected
  • An access list, priority queue or other restrictions on a user’s access
  • L2TP parameters
  • VLAN parameters
  • Quality of Service (QoS) parameters

Accounting

RADIUS Accounting Flow

Accounting is described in RFC 2866.

When network access is granted to the user by the NAS, an Accounting Start (a RADIUS Accounting Request packet containing an Acct-Status-Type attribute with the value “start”) is sent by the NAS to the RADIUS server to signal the start of the user’s network access. “Start” records typically contain the user’s identification, network address, point of attachment and a unique session identifier.[5]

Periodically, Interim Update records (a RADIUS Accounting Request packet containing an Acct-Status-Type attribute with the value “interim-update”) may be sent by the NAS to the RADIUS server, to update it on the status of an active session. “Interim” records typically convey the current session duration and information on current data usage.

Finally, when the user’s network access is closed, the NAS issues a final Accounting Stop record (a RADIUS Accounting Request packet containing an Acct-Status-Type attribute with the value “stop”) to the RADIUS server, providing information on the final usage in terms of time, packets transferred, data transferred, reason for disconnect and other information related to the user’s network access.

Typically, the client sends Accounting-Request packets until it receives an Accounting-Response acknowledgement, using some retry interval.

The primary purpose of this data is that the user can be billed accordingly; the data is also commonly used for statisticalpurposes and for general network monitoring.

Roaming

Roaming using a proxy RADIUS AAA server.

RADIUS is commonly used to facilitate roaming between ISPs, for example:

  • by companies which provide a single global set of credentials that are usable on many public networks;
  • by independent, but collaborating, institutions issuing their own credentials to their own users, that allow a visitor from one to another to be authenticated by their home institution, such as in Eduroam.

RADIUS facilitates this by the use of realms, which identify where the RADIUS server should forward the AAA requests for processing.

Realms

A realm is commonly appended to a user’s user name and delimited with an ‘@’ sign, resembling an email address domain name. This is known as postfix notation for the realm. Another common usage is prefix notation, which involves prepending the realm to the username and using ‘\’ as a delimiter. Modern RADIUS servers allow any character to be used as a realm delimiter, although in practice ‘@’ and ‘\’ are usually used.

Realms can also be compounded using both prefix and postfix notation, to allow for complicated roaming scenarios; for example, somedomain.com\username@anotherdomain.com could be a valid username with two realms.

Although realms often resemble domains, it is important to note that realms are in fact arbitrary text and need not contain real domain names.

Proxy operations

When a RADIUS server receives an AAA request for a user name containing a realm, the server will reference a table of configured realms. If the realm is known, the server will then proxy the request to the configured home server for that domain. The behaviour of the proxying server regarding the removal of the realm from the request (“stripping”) is configuration-dependent on most servers. In addition, the proxying server can be configured to add, remove or rewrite AAA requests when they are proxied.

Security

Roaming with RADIUS exposes the users to various security and privacy concerns. More generally, some roaming partners establish a secure tunnel between the RADIUS servers to ensure that users’ credentials cannot be intercepted while being proxied across the internet. This is a concern as the MD5 hash built into RADIUS is considered insecure.[6]

Packet structure

RADIUS packet data format.

The RADIUS packet data format is shown to the right. The fields are transmitted from left to right, starting with the code, the identifier, the length, the authenticator and the attributes.

RADIUS Codes (decimal) are assigned as follows:

Code Assignment
1 Access-Request
2 Access-Accept
3 Access-Reject
4 Accounting-Request
5 Accounting-Response
11 Access-Challenge
12 Status-Server (experimental)
13 Status-Client (experimental)
255 Reserved

The Identifier field aids in matching requests and replies.

The Length field indicates the length of the entire RADIUS packet including the Code, Identifier, Length, Authenticator and optional Attribute fields.

The Authenticator is used to authenticate the reply from the RADIUS server, and is used in encrypting passwords; its length is 16 bytes.

Attribute value pairs

RADIUS AVP layout.

The RADIUS Attribute Value Pairs (AVP) carry data in both the request and the response for the authentication, authorization, and accounting transactions. The length of the radius packet is used to determine the end of the AVPs.

AVP Type Assignment
1 User-Name
2 User-Password
3 CHAP-Password
4 NAS-IP-Address
5 NAS-Port
6 Service-Type
7 Framed-Protocol
8 Framed-IP-Address
9 Framed-IP-Netmask
10 Framed-Routing
11 Filter-Id
12 Framed-MTU
13 Framed-Compression
14 Login-IP-Host
15 Login-Service
16 Login-TCP-Port
17 (unassigned)
18 Reply-Message
19 Callback-Number
20 Callback-Id
21 (unassigned)
22 Framed-Route
23 Framed-IPX-Network
24 State
25 Class
26 Vendor-Specific
27 Session-Timeout
28 Idle-Timeout
29 Termination-Action
30 Called-Station-Id
31 Calling-Station-Id
32 NAS-Identifier
33 Proxy-State
34 Login-LAT-Service
35 Login-LAT-Node
36 Login-LAT-Group
37 Framed-AppleTalk-Link
38 Framed-AppleTalk-Network
39 Framed-AppleTalk-Zone
40 Acct-Status-Type
41 Acct-Delay-Time
42 Acct-Input-Octets
43 Acct-Output-Octets
44 Acct-Session-Id
45 Acct-Authentic
46 Acct-Session-Time
47 Acct-Input-Packets
48 Acct-Output-Packets
49 Acct-Terminate-Cause
50 Acct-Multi-Session-Id
51 Acct-Link-Count
52-59 (reserved for accounting)
60 CHAP-Challenge
61 NAS-Port-Type
62 Port-Limit
63 Login-LAT-Port

[edit]Vendor-specific attributes

RADIUS is extensible; many vendors of RADIUS hardware and software implement their own variants using Vendor-Specific Attributes (VSAs). Microsoft has published some of their VSAs.[7] VSA definitions from many other companies remain proprietary and/or ad-hoc.

UDP port numbers

RADIUS has been officially assigned UDP ports 1812 for RADIUS Authentication and 1813 for RADIUS Accounting by the Internet Assigned Numbers Authority (IANA). However, prior to IANA allocation of ports 1812 and 1813, ports 1645 and 1646 (authentication and accounting, respectively) were used unofficially and became the default ports assigned by many RADIUS Client/Server implementations of the time. The tradition of using 1645 and 1646 for backwards compatibility continues to this day. For this reason many RADIUS Server implementations monitor both sets of UDP ports for RADIUS requests. Microsoft RADIUS servers default to 1812 and 1813. Cisco RADIUS servers listen on RADIUS ports UDP 1645 and UDP 1812 for authentication; on ports 1646 and 1813 for accounting and can be configured with non-standard ports. Juniper Networks‘ RADIUS servers listen on both unofficial and official ports 1645, 1812, 1646 and 1813 by default but can be configured with arbitrary ports.SBR

Security

The RADIUS protocol does not transmit passwords in cleartext between the NAS and RADIUS server (not even with PAP protocol). Rather, a shared secret is used along with the MD5 hashing algorithm to obfuscate passwords. Because this particular implementation is not considered to be a very strong protection of the user’s credentials,[8] additional protection – such as IPsec tunnels or physically secured data-center networks – should be used to further protect the RADIUS traffic between the NAS device and the RADIUS server. Additionally, the user’s security credentials are the only part protected by RADIUS itself, yet other user-specific attributes such as tunnel-group IDs or vlan memberships passed over RADIUS may be considered sensitive (helpful to an attacker) or private (sufficient to identify the individual client) information as well.[citation needed] The RadSec protocol claims to solve aforementioned security issues.

RADIUS history

RADIUS was originally specified in an RFI by Merit Network in 1991 to control dial-in access to NSFnet. Livingston Enterprises responded to the RFI with a description of a RADIUS server. Merit Network awarded the contract to Livingston Enterprises that delivered their PortMaster series of Network Access Servers and the initial RADIUS server to Merit. RADIUS was later (1997) published as RFC 2058 and RFC 2059 (current versions are RFC 2865 and RFC 2866).[1]

Now, several commercial and open-source RADIUS servers exist. Features can vary, but most can look up the users in text files, LDAP servers, various databases, etc. Accounting records can be written to text files, various databases, forwarded to external servers, etc. SNMP is often used for remote monitoring and keep-alive checking of a RADIUS server. RADIUS proxy servers are used for centralized administration and can rewrite RADIUS packets on the fly (for security reasons, or to convert between vendor dialects).

The Diameter protocol is the planned replacement for RADIUS. Diameter uses SCTP or TCP while RADIUS uses UDP as the transport layer.

Reference : http://en.wikipedia.org/wiki/RADIUS