Jumat, 08 Maret 2013

Xathrya Sabertooth

Xathrya Sabertooth


Introduction to Reverse Engineering

Posted: 08 Mar 2013 03:01 AM PST

What is Reverse Engineering?

Some people ask me, what is reverse engineering mean? Well, mostly reverse engineering including cracking a binary program, but it’s not limited to it only.

Reverse engineering is the process of taking a compiled binary and attempting to recreate (at least understand) the original way of program works. The programs are written in higher level languages such as C\C++, Visual Basic, Pascal, etc and understandable enough for human (at least programmer). But the machine is not. Computer doesn’t speak these language. They only knows a language consist of binary logic, 1 or 0. After a programmer write their code, the codes then translated / compiled to the machine specific format. This code is only consist of low level instruction represented by hexadecimal number. Yes, it is not very human friendly and often require great deal of brain power to figure out what the instruction mean.

So why we do reverse engineering?

Reverse engineering is quite useful and can be applied to many areas of computer science. At least there are five categories:

  1. Making it possible to interface to legacy code (where we don’t have the original code source)
  2. Breaking protection.
  3. Studying virus and malware
  4. Evaluating software quality and robustness
  5. Adding functionality to existing softwares

The first category is reverse engineering code to interface with existing binaries when the source code is not available.

The second category (most motivating reason) is breaking protection. This including disabling time trials, disable registration, and basically everything else to get commercial software for free.

The third category is studying virus and malware code. Reverse engineering is required as not a lot of virus coders out there open their source code and write instruction on how they wrote the code. The information such as what it is supposed to accomplish, and how it will accomplish this is hidden in the virus body.

The fourth category is evaluating software security and vulnerabilities. When creating large application or system, reverse engineering is used to make sure that the system does not contain any major vulnerabilities, security flaws, and frankly, to make it as hard as possible to allow crackers to crack the software.

The final category is adding functionality to existing software. Don't like the graphics used in your web design software? Change them. Want to add a menu item to encrypt your documents in your favorite word processor? Add it. Want to annoy your co-workers to no end by adding derogatory message boxes to Windows calculator?

So what knowledge we required?

As you can probably guess, a great deal of knowledge is necessary to be an effective reverse engineer. Fortunately, a great deal of knowledge is not necessary to 'begin' reverse engineering. To have fun with reversing and to get something out of these tutorials you should at least have a basic understanding of how program flow works (for example, you should know what a basic if…then statement does, what an array is, and have at least seen a hello world program). Secondly, becoming familiar with Assembly Language is highly suggested; You can get thru the tutorials without it, but at some point you will want to become a master or at least guru at ASM to really know what you are doing. In addition, a lot of your time will be devoted to learning how to use tools. These tools are invaluable to a reverse engineer, but also require learning each tool's shortcuts, flaws and idiosyncrasies. Finally, reverse engineering requires a significant amount of experimentation; playing with different packers/protectors/encryption schemes, learning about programs originally written in different programming languages (even Delphi), deciphering anti-reverse engineering tricks…the list goes on and on.

But I can highlight that, lot of reading and practicing will help you.

What kinds of tools are used?

There are many different kinds of tools used in reversing. Many are specific to the types of protection that must be overcome to reverse a binary. There are also several that just make the reverser's life easier. And then some are what I consider the 'staple' items- the ones you use regularly. For the most part, the tools fit into a couple categories:

1. Disassemblers

Disassemblers attempt to take the machine language codes in the binary and display them in a friendlier format. They also extrapolate data such as function calls, passed variables and text strings.  This makes the executable look more like human-readable code as opposed to a bunch of numbers strung together. There are many disassemblers out there, some of them specializing in certain things (such as binaries written in Delphi). Mostly it comes down to the one your most comfortable with. I invariably find myself working with IDA (there is a free version available http://www.hex-rays.com/), as well as a couple of lesser known ones that help in specific cases.

2. Debuggers

Debuggers are the bread and butter for reverse engineers. They first analyze the binary, much like a disassembler  Debuggers then allow the reverser to step through the code, running one line at a time and investigating the results. This is invaluable to discover how a program works. Finally, some debuggers allow certain instructions in the code to be changed and then run again with these changes in place. Examples of debuggers are Windbg and Ollydbg. I almost solely use Ollydbg (http://www.ollydbg.de/), unless debugging kernel mode binaries, but we'll get to that later.

3. Hex editors

Hex editors allow you to view the actual bytes in a binary, and change them. They also provide searching for specific bytes, saving sections of a binary to disk, and much more. There are many free hex editors out there, and most of them are fine. We won't be using them a great deal in these tutorials, but sometimes they are invaluable.

4. PE and resource viewers/editors

Every binary designed to run on a specific machine has a very specific section of data at the beginning of it that tells the operating system how to set up and initialize the program. It tells the OS how much memory it will require, what support-libraries the program needs to borrow code from, information about dialog boxes and such. This is called the Portable Executable, and all programs designed to run on windows needs to have one.

In the world of reverse engineering, this structure of bytes becomes very important, as it gives the reverser needed information about the binary. Eventually, you will want to (or need to) change this information, either to make the program do something different than what it was initially for, or to change the program BACK into something it originally was (like before a protector made the code really hard to understand). There are a plethora of PE viewers and editors out there. I use CFF Explorer (http://www.ntcore.com/exsuite.php) and LordPE (http://www.woodmann.com/collaborative/tools/index.php/LordPE), but you can feel free to use whichever you're comfortable with.

Most files also have resource sections. These include graphics, dialog items, menu items, icons and text strings. Sometimes you can have fun just by looking at (and altering :P   ) the resource sections. I will show you an example at the end of this tutorial.

5. System Monitoring tools

When reversing programs, it is sometimes important (and when studying virii and malware, of the utmost importance) to see what changes an application makes to the system; are there registry keys created or queried? are there .ini files created? are separate processes created, perhaps to thwart reverse engineering of the application? Examples of system monitoring tools are procmon, regshot, and process hacker. We will discuss these later in the tutorial.

6. Miscellaneous tools and information

There are tools we will pick up along the way, such as scripts, unpackers, packer identifiers etc. Also in this category is some sort of reference to the Windows API. This API is huge, and at times, complicated. It is extremely helpful in reverse engineering to know exactly what called functions are doing.

Interesting?

Secure Shell for Remote Connection

Posted: 08 Mar 2013 01:06 AM PST

Most network administrator manage their servers remotely. A network administrator can remotely control server without need to locally stand beside of the actual machine. This connection of course made using internet media. On earlier era, there are so much application for this purpose. One can mention tools such as telnet, ftp, and application known as r tools such as rsh, rlogin, and rcp. But all of these applications are insecure as any message (even sensitive data such as username and password) are transmitted plain. No encryption at all.

The insecure of telnet and other old application then force people to invent new remote connection system with secure connection. Thus, SSH rises.

Secure SHell or SSH is now notably used for establishing remote connections.  SSH send and receive message over cryptograhic network protocol for secure data communication. This mechanism guarantee a secure channel over insecure network.

In this article we will discuss about Secure Shell and its usage for Remote Connection on Linux and FreeBSD.

Introduction to OpenSSH, The Free SSH implementation

OpenSSH, at beginning developed by OpenBSD, now become popular and free implementation of SSH connectivity. Licensed under BSD License which offer you freedom to use by everyone.

OpenSSH suite has two part: client side and server side. OpenSSH also offer other utilities such as ssh-add, ssh-agent, ssh-keysign, ssh-keyscan, ssh-keygen. SSH also offer sftp and scp for file transferring.

Installation

Most Linux and BSD distribution has included OpenSSH. However if you want to install from source you can go to http://openssh.org/ and download newest version. The compilation is quite straightforward and self explain.

If you have Debian/Ubuntu you can install by:

  aptitude install ssh-server  

Configuration

SSHD (SSH Daemon / Server)

SSH server use a configuration file sshd_config. On Linux, mostly it is located on /etc/ssh/sshd_config  (Slackware64). On BSD (FreeBSD) it is located also on /etc/ssh/sshd_config. The file can be used directly without altering anything. However if you can also modify it at you wish.

For security reason, we should (strongly recommended) to make sure security is handled. In this case, we limit root account so it can’t be used for remote login. Make sure the following option is enabled on configuration file (not commented by #):

  PermitRootLogin no  StrictModes yes  UsePrivilegeSeparation yes  

Strict mode will check whether user has access mode 777, or in other word is permitted to write, read, and execute all files and directories on his home directory. UsePrivilegeSeparation will fork another process to handle incoming connection before the connection is authenticated. After user is authenticated, the login credentials will be transferred to the main sshd process.

SSH (Client)

Similar to sshd, ssh use configuration file and can be use directly. On Linux system, mostly, it is located on /etc/ssh/ssh_config. On BSD, specifically FreeBSD, is is located on /etc/ssh/ssh_config. As a client, it works by making a connection to SSH server. It will lookup for server, maintaining keys used for communication for server, etc.

For security reason too, we should consider following on SSH configuration file:

  CheckHostIP yes  StrictHostKeyChecking ask  

The first directive, CheckHostIP, enforce client to check IP host whether is under DNS spoofing or not. Another directive, StrictHostKeyChecking will enforce client to ask whether public key of remote system will be written to known_host file when initial connection established.

Using the Client

To connect to server using SSH, a connection must be set inside encrypted connection. A connection use a valid account on server side. It means, you are logging to remote server using the account on that server. For example when I have account xathrya on celestial-being.net, I use:

  ssh xathrya@celestial-being.net  

When you do initial connection, you will be asked whether you want to save the host information or not.

The authenticity of host 'hostname (IP)' can't be established.  RSA key fingerprint is <some hexadecimal string>.  Are you sure you want to continue connecting (yes/no)?

If you want to proceed, then you must answer by ‘yes’. Client then will remember the remote host by fingerprinting and stored on a file known_hosts. This file mostly located on ~/.ssh/known_hosts. If you have save the fingerprint, and then the host use different fingerprint, ssh client will give you a warning and prevent you from proceeding. If you are sure you connect to correct server, you should remove associated line on ~/.ssh/known_hosts.

Secure Copy (SCP)

SCP or secure copy works like normal cp (copy) utility, but works on network. SCP copy file(s) of two system across network using SSH connection. At general, the syntax for scp defined as:

  scp [options] [[user1@]host1:[path]]file1 ... [[user2@host2:[path]]file2  

The hosts can be our machine or remote machine. SCP will copy file on first host to second host. Thus we can use scp to copy file from out host to remote server, from remote server to our host, or from remote server to another remote server.

The common options / flags used by scp are:

  • -p: keep date modified information, access, and file mode
  • -r: recursively copies files. Used to copies all directory content
  • -c: activating SSH compression mode

An example:

  scp xathrya@celestial-being.net:/opt/research/gundam00 /home/xathrya/gundam00  

At that example I copy a file gundam00 from remote host (celestial-being.net) on path /opt/research to my machine as /home/xathrya/gundam00. Note that the host1 now defined as remote host and host2 is defined at my host.

Secure File Transfer Protocol (SFTP)

SFTP is another version of FTP run on SSH connection. It is like FTP but provide security. If a server want to use SFTP service, make sure you have following line active on sshd_config file:

  SubSystem sftp /usr/lib/openssh/sftp-server  

Where /usr/lib/openssh/sftp-server is a path to sftp-server on Debian/Ubuntu system. You should find a correct path to sftp if you have no above file.

Using SFTP client is like using any FTP client except SFTP use the same port as SSH does. The default SSH port is 22. Following is a sample SFTP connection established:

  xathrya@BlueWyvern: $ sftp setsuna@celestial-being.net  Connection to celestial-being.net  setsuna@celestial-being.net's password: *******    sftp> put gundam00.pdf  Uploading gundam00.pdf to /home/xathrya/gundam00.pdf  gundam00.pdf     100%    1.5MB 129.4KB/s 00:16  sftp>  

There we have two phase: login, and uploading. User xathrya is initiating connection to celestial-being.net using account setsuna. I passed the authentication then use put to upload a file. You can also use another command such as ls, cd, which are supported by ftp (and also sftp).

If in any case you change the SSH port to a number, for example 1351 then SFTP client cannot connect to remote server. But you can still make a connection by using:

  sftp -oPort=1351 <user>@<site domain>  

Beginning C++: Condition Analysis and Branching (If, Switch)

Posted: 07 Mar 2013 11:39 PM PST

In more complex situation, there is a need for application to run a certain codes in regards of situation. Thus we need to analyze what condition to execute what codes. It is called condition analysis, but widely known as branching. Condition analysis or branching is no more than selecting statement which will be executed. The selection is based on some conditions – represented by one or more boolean expression – applied.

C++ has two type structure to implement branching: if structure and switch structure.

Statements inside of branching block will be executed only if the condition is satisfied / fulfilled. Which in turn, if condition is not achieved, then the statements / codes won’t be executed.

Let’s see a case in real world. Note this sentence:

If Andy passed the exam then Andy will get a prize

This simple sentence tells us what will happen to Andy. As demonstrated here we know that Andy will get prize if he pass the exam. Otherwise, he won’t. The action defined here is Andy will get a prize. But to do the action, there is a condition, which is Andy must pass the exam.

In programming world, similar case applied, of course in some notion. Programming world use a formalized form in which we will discuss in this article.

If Structure

The first structure we will discuss is IF. This structure is the simplest of all things. Let’s see following snippet:

// If there are more than 1 statement
if (condition) {
statement1;
statement2;
}

// If there is only 1 statement
if (condition) statement;

There is the simplest structure we have, if with only one condition analysis. Yes, the statement(s) will be execute if the condition is satisfied. Let’s see how we can use in the actual program.

#include <iostream>
using namespace std;

int main() {
int number;

// Input an integer number from user
cout << "Please input number: " ;
cin >> number;

if (number > 10)
cout << "You give me " << number << ", it’s more than 10 :D " << endl;

return 0;
}

As you can see, the condition is consist of comparison operations. In general, condition can be formed by one or more comparison expression merged by logical operation such as: && (and), || (or). This we call as complex condition structure. Let’s see this example:

#include <iostream>
using namespace std;

int main() {
char c;

// Input a character from user
cout << "Please input a character: " ;
cin >> c;

if ( (c == ‘A’) || (c == ‘a’) ||
(c == ‘I’) || (c == ‘i’) ||
(c == ‘U’) || (c == ‘u’) ||
(c == ‘E’) || (c == ‘e’) ||
(c == ‘O’) || (c == ‘o’))
cout << "You give me a vowel" << endl;

return 0;
}

With a simple analysis, we can see that the statement cout << “You give me a vowel” << endl can be can be executed if one of those multiple condition is satisfied (you can see why).

One or more condition can be made to this structure. In fact, it is easy to write. For a starter, let see how we can analyze two condition:

if (condition) {
statement_if_condition_is_satisfied
} else {
statement_if_condition_is_not_satisfied
}

There we have two situation: a situation if condition is satisfied, and situation where condition is not satisfied. If the application failed to satisfied the condition, the execution will fall to block following else word. In here we will see how we the usage in the real world programming:

#include <iostream>
using namespace std;

int main() {
int number;

// Input an integer number from user
cout << "Please input a number: " ;
cin >> number;

if ( number % 2 == 0 ) {
cout << "You give me an even number" << endl;
} else {
cout << "You give me an odd number" << endl;
}

return 0;
}

There we analyze whether the given number is an even or an odd number. Wee that a number which is not an even number must be an odd number, so we just applied one condition to check and if the condition is not satisfied it will fall to the else block of statement.

Now how if we want to inspect more than that? Simple, we could write something like this:

if (condition-1) {
statement_if_condition_1_satisfied
} else if (condition-2) {
statement_if_condition_2_satisfied
} else if (condition-3) {
statement_if_condition_3_satisfied
} …

} else {
statement_if_no_condition_is_satisfied
}

Yes, we can use else if to analyze other condition that might happen.

Switch Structure

Aside from if structure, C++ offer us another condition analysis structure, switch.

Switch is like an actual switch. Imagine there is an electronic switch which connecting two endpoint. There are two condition for this switch at a time: on or off. On an observation, we could see that if the switch is on, the two endpoint will be connected. Otherwise the two endpoint is disconnected. Therefore we can see there are two different action: connected and disconnect, which is drived by two different condition: on or off.

Similar to that, switch need a variable in which will be observed. Switch then compare the value to the list of value might equal to it.

If we transform the analogy to a C++ snippet, we will get something like this:

switch ( electronic_switch) {
case on:
connected;
break;

case off:
disconnected;
break;

default:
}

As we can see, the variable electronic_switch is being inspected and then it will be compared to two value: on and off. Once it is matched, it will begin to execute whatever code later. Therefore, we must set a stop / break point. This break statement then stop the execution and then finishing the switch statement.

Oh, and don’t forget that the value compared using case keyword must be a constant. You can’t compare the value which is being inspected to a variable.

What if we forgot to give break there? Switch will continue executing codes until it found break or until it reach end of switch statement. Be careful!

Now let see the actual use:

#include <iostream>
using namespace std;

int main() {
int number;

cout << "Input a number (1..7): ";
cin >> number;

switch(number) {
case 1: cout << "You give me one" << endl; break;
case 2: cout << "You give me two" << endl; break;
case 3: cout << "You give me three" << endl; break;
case 4: cout << "You give me four" << endl; break;
case 5: cout << "You give me five" << endl; break;
case 6: cout << "You give me six" << endl; break;
case 7: cout << "You give me seven" << endl; break;
}

return 0;
}

Nested Condition Analysis

Now suppose we want to analyze something after some condition is satisfied. This common situation is called as nested branching / nested condition analysis. You can use if of switch inside of another if or switch structure.

How to do it? Well, I will let you figure it out :P

Installing Android 4.0 in VirtualBox

Posted: 07 Mar 2013 07:33 PM PST

Android, the popular Operating System for smartphones, now come in handy on PC. Some folks at Android-x86 project had port this little Green Buddy into PC. And thanks to them, we can enjoy the Android on our PC.

In this article, we will discuss about Android x86 installation on VirtualBox. For this, I use:

  1. Slackware64 14.0, although any Operating System is fine at least it can run VirtualBox
  2. VirtualBox.
  3. Android x86 ISO file

Obtaining the Materials

As said, we will do installation of Android on virtual machine using VirtualBox. Thus you have to make sure VirtualBox is installed and enable to run properly. For Slackware64, I have create a separated article about how to install VirtualBox on Slackware.

Another material we need is the Android x86 ISO itself. The ISO is provided by http://www.android-x86.org, the official site. The project had made many builds of Android OS for a quite. You can see many version with many architecture supported by them. The one we use is android x86 4.0 RC2 for asus laptop.

For some version provided there, they don’t work very well in VirtualBox. For example the “EEEPC” image for Android 4.0 has issues with the audio drivers and the network (it has no Ethernet support built in), etc. But fortunately, There is an ISO image which has been custom made to match with VirtualBox which I found on another people site. Although he said this is not his made, but thanks Kirsle! You can download the ISO from this site!

Create the Virtual Machine

Now come to the main business. Create a new machine for Android with this (minimum) specification:

  • Machine Name: “Android x86 ICS” (or anyname you want)
  • Machine Type: “Linux
  • Machine Version: “Linux 2.6″
  • Memory: 256 MB (but I use 1024 MB)
  • Hard disk: 12 GB (12 GB is enough, but mine is 16 GB)

Other setting on my Virtual Machine:

  • Networking:
    • Type: NAT
    • Adaptor: “Intel Pro/1000 MT Desktop (8254EM)”
  • Audio: Intel AC’97
  • Storage Layout:
    • IDE Controller: CD Device
    • SATA Controller: Hard disk
  • Video Memory: 16 MB

Boot and Install

Run the virtual machine, you should then see something similar to this:

android1

If you want to try the live CD, you can choose “Live CD – VESA mode” on boot menu. You will then see the screen like this:

android3

Another screenshot for Android x86 4.0:

android2

If you decide to install it, in boot menu (you should restart the machine if you are on Live CD mode) choose “Installation – install Android-x86 to harddisk”. Then you will see bunch of text on console and then be brought to partition menu. OK, get ready.

In this article we will use all the space we have and create only partition. You can also create more than one partition, but we won’t cover that here.

Choose “Create/Modify Partitions” which leads you into cfdisk. To do so do the following:

  1. Choose “[New]“
  2. Choose “[Primary]“
  3. Press enter to accept the default partition size
  4. Choose “[Bootable]“
  5. Choose “[Write]“
  6. Type “yes” to confirm writing
  7. Choose “[Quit]“

Now choose to install on the “sda1 device Linux VBOX HARDDISK”. Format it to “ext3″. Confirm “yes” on formatting. Confirm “yes” when it asks to install GRUB bootloader. Confirm “yes” when it asks to mount /system as read-write.

Now create a fake SD card when it prompts. I made 2074MB (the maximum allowed).

Reboot! Make sure you detach the ISO image from the virtual machine and boot the installed OS. If you still see “Installation” option again, then you are booting form ISO.

Disable Mouse Integration

To interact with GUI, you need to disable mouse integration. This can be done by choosing the “Machine” menu in the VM window and clicking “Disable Mouse Integration”. Another way is pressing HostKey + I.

Perfect Forwarding in C++11

Posted: 07 Mar 2013 05:07 PM PST

C++11 offers a great new features called Perfect Forwarding, which is enabled via the use of rvalue references.

Perfect forwarding allows a function template to pass its arguments through to another function while retaining the original lvalue / rvalue nature of the function arguments. It avoids unnecessary copying and avoids the programmer having to write multiple overloads for different combinations of lvalue and rvalue references. A class can use perfect forwarding with variadic templates to “export” all possible constructors of a member object at the parent’s level.

  class Blob  {    std::vector<std::string> _v;  public:    template<typename... Args>    Blob(Args&&... args)     : _v(std::forward<Args>(args)...)    {  }  };  int main(void)  {    const char * shapes[3] = { "Circle", "Triangle", "Square" };    Blob b1(5, "C++ Truths");    Blob b2(shapes, shapes+3);  }  

The Blob class above contains a std::vector, which has many different constructors. Using a perfect forwarding constructor, the Blob class allows its clients to pass variable number of parameters that different constructors of std::vector would use. For example, object b1 uses std::vector’s constructor that takes a count and an initial value where as object b2 uses the constructor that takes an iterator pair. Also note that std::forward allows us to perfect-forward the parameters.

If you look carefully, actually this example does not require perfect forwarding as Blob constructor could take a std::vector by value and move it into the member vector object. Well, suppose we don’t know.

In practice, however, we would encounter classes that would have several members. Naturally, we may want to “export” their different constructors at its parent’s level. This is particularly true if object construction is heavy and does not support efficient move. The motivation behind this is no different than that of the emplace operations on containers. Just like the standard emplace operations, our perfect forwarding constructor allows us to construct an object in-place. We don’t even pay the cost of a move (which is often negligible for types such as std::vector). An interesting problem arises when we want to perfect forward arguments to more than one constructor. How do we decide which parameters are for which object?

Let see example below. The following Blob class has a vector of strings and a list of doubles. How do we group the parameters to the respective constructors? How do we know the programmer’s intent?

  class Blob  {    std::vector<std::string> _v;    std::list<double> _l;  public:    template<typename... Args>    Blob(Args&&... args)     : _v(???)       _l(???)    {  }  };  int main(void)  {     Blob b3(5, 10, 10.0); // Three parameters and two constructors. How do we group?  }  

<p style=”text-align: justify;”>Fortunately there is a way out and a very interesting one.</p>
<p style=”text-align: justify;”>First of all, we’ve to group the parameters. An obvious candidate comes to mind: std::tuple! We could ask programmers to group the parameters in a sequence of tuples and each parameter grouped in the tuples are passed to the respective constructors.</p>
<p style=”text-align: justify;”>

  Blob b3(std::make_tuple(5), std::make_tuple(10, 99.99));  
The intent of the programmer is pretty clear in the above groupings. The vector will have 5 empty strings and the list will have 10 doubles each initialized to value = 99.99. However, we’ve a new problem now. std::vector and std::list do not accept std::tuple as parameters. We’ve to ungroup them before calling their constructors. This is far from trivial but it also makes the whole thing very interesting.

Note that retrieving values from a std::tuple requires calling std::get<i> where i is a compile-time constant that varies from 0 to the tuple_length-1. Somehow, we’ve to call std::get on each tuple with increasing values of i. To do that, we’ve to create a compile-time list of tuple indices. Here is a way to do it.

  template<unsigned...> struct index_tuple{};  template<unsigned I, typename IndexTuple, typename... Types>  struct make_indices_impl;  template<unsigned I, unsigned... Indices, typename T, typename... Types>  struct make_indices_impl<I, index_tuple<Indices...>, T, Types...>  {    typedef typename      make_indices_impl<I + 1,                        index_tuple<Indices..., I>,                        Types...>::type type;  };  template<unsigned I, unsigned... Indices>  struct make_indices_impl<I, index_tuple<Indices...> >  {    typedef index_tuple<Indices...> type;  };  template<typename... Types>  struct make_indices    : make_indices_impl<0, index_tuple<>, Types...>  {};  

make_indices is a collection of recursive meta-fuctions that compute a list of indices given a tuple type. For example, if you have (42, true, 1.2), which is tuple<int, bool, double>, make_indices<int,bool,double>::type gives index_tuple<0, 1, 2>. Here is how to use make_indices in a simple program.

  template <unsigned... Indices, class... Args, class Ret>  Ret forward_impl(index_tuple<Indices...>,                   std::tuple<Args...> tuple,                   Ret (*fptr) (Args...))  {    return fptr(std::get<Indices>(tuple)...);  }  template<class... Args, class Ret>  Ret forward(std::tuple<Args...> tuple, Ret (*fptr) (Args...))  {     typedef typename make_indices<Args...>::type Indices;     return forward_impl(Indices(), tuple, fptr);  }  int myfunc(int i, bool, double)  {    return 5 + i;  }  int main()  {    std::cout << forward(std::make_tuple(42, true, 1.2), myfunc) << std::endl;  }  

Line #6 above is the place where the actual function is called where the list of indices and the tuple come together and two parameter packs are expanded in lockstep to yield the complete list of parameters. Note that we’re not using perfect forwarding in this case. Moreover, tuple is also copied by value. That’s fine for scalar builtin types like int, bool, and double. For large types, however, unnecessary copies may be created. The above program is simplified for the purpose of illustration.
Back to class Blob

The make_indices utility is pretty clever. But we’re not done yet. We’ve to achieve the same effect while calling the member constructors from the initialization list. We’ve to compute two lists of indices (one for vector and one for list) and expand them with the respective tuples. The question is how do we compute the list of indices before calling member constructors?

Delegated constructors come to rescue!

  class Blob  {    std::vector<std::string> _v;    std::list<double> _l;  public:    template <typename... Args1,              typename... Args2>    Blob(std::tuple<Args1...> tuple1,         std::tuple<Args2...> tuple2)    : Blob(tuple1,           tuple2,           typename make_indices<Args1...>::type(),           typename make_indices<Args2...>::type())    {}  private:    template <typename... Args1,              typename... Args2,              unsigned... Indices1,              unsigned... Indices2>    Blob(std::tuple<Args1...> tuple1,         std::tuple<Args2...> tuple2,         index_tuple<Indices1...>,         index_tuple<Indices2...>)      : _v(std::forward<Args1>(std::get<Indices1>(tuple1))...),        _l(std::forward<Args2>(std::get<Indices2>(tuple2))...)    { }  };  

The new Blob class has a public constructor that delegates to a private constructor that expects not only the tuples but also the list of indices. The private constructor is not only templatized on the tuple arguments but also on the list of indices. Once we’ve the tuples and lists of indices together, passing them to the member constructors is pretty straight forward. We simply expand the two variadic lists in unison.

Astute readers will likely notice that the Blob class is no longer using perfect forwarding because it accepts two tuples by value as opposed to an argument list in a perfect forwarding fashion shown at the beginning. That’s is on purpose. And it is not any less efficient either! Even for large types! How’s that possible?

Well, who says copying a tuple by value means copying its original parameters by value? C++ standard library provides a very convenient helper called forward_as_tuple, which perfect-forwards its parameters types as tuple members. It constructs a tuple object with rvalue references to the elements in arguments suitable to be forwarded as argument to a function. That is, the tuple member types are T&& and copying references is blazing fast. So we can afford to pass the tuples by value. Alternatively, we could use rvalue references to the tuples because in this case they are always (!) created by calling std::forward_as_tuple, which returns a temporary tuple. Here is how we use our final Blob class.

  int main(void)  {    Blob b3(std::forward_as_tuple(5, "C++ Truths"),            std::forward_as_tuple(10, 99.99));    // b3._v has 5 strings initialized to "C++ Truths" and    // b3._l has 10 doubles initialized to 99.99    Blob b4(std::forward_as_tuple(5),            std::forward_as_tuple(10, 99.99));    // b4._v has 5 empty strings and    // b4._l has 10 doubles initialized to 99.99    Blob b5(std::forward_as_tuple(),            std::forward_as_tuple(10, 99.99));    // b5._v is an empty vector    // b5._l has 10 doubles initialized to 99.99  }  

Using std::piecewise_construct

The Blob class looks fine and dandy so far. But the use of forward_as_tuple looks somewhat weird and does not say what it is for: in-place construction of a Blob object from its pieces. So in the final installment of the Blob class, we say what we mean. We just decorate the class with a standard (!) dummy class called std::piecewise_construct_t. The public constructor of the Blob is modified like below. We use std::piecewise_construct, a predefined object of std::piecewise_construct_t, at the call site where we create Blob objects.

  #include <utility>  // ...    template <typename... Args1,              typename... Args2>    Blob(std::piecewise_construct_t,         std::tuple<Args1...> tuple1,         std::tuple<Args2...> tuple2)    : Blob(tuple1,           tuple2,           typename make_indices<Args1...>::type(),           typename make_indices<Args2...>::type())    {}  //...  Blob b3(std::piecewise_construct,          std::forward_as_tuple(5, "C++ Truths"),          std::forward_as_tuple(10, 99.99));  

Obviously, the C++ library working group anticipated such situations. But are there use cases in the standard library that require the piecewise_construct idiom? As it turns out, the std::map and std::unordered_map face a very similar issue while using emplace operations. Note that std::map and std::underorder_map use a std::pair as their value_type. The pair’s .first and .second members must be constructed from a list of perfectly forwarded parameters. Obviously, the question arises what parameters go where. To solve this issue, the parameters of each member’s constructor must be wrapped as a tuple and indicate so using std::piecewise_construct so that the right pair constructor can be invoked.

Enabling Email Subscription using FeedBurner

Posted: 07 Mar 2013 04:40 PM PST

On a news I post before, I have said that I have activated email subscription feature. On default wordpress installation (at least happen to me), there is no email subscription feature thus I have to create it manually. In this article we will discuss about how to enabling email subscription using FeedBurner.

What is Feed and FeedBurner

On short a feed (web feed or news feed) is a data format used for providing users with frequently updated content. Content distributors syndicate a web feed, thereby allowing users to subscribe to it. In other word, it is a mechanism to allow user subscribe to any content made by someone.

Feedburner is one of Feed Syndicate which deliver feed to people who have subscribed. This service is owned by Google and you can sign in using your google account to register your site.

Setup a FeedBurner Feed

First, make sure you have a feedburner feed. If you don’t have one already, do following step:

  1. Go to Feedburner (http://feedburner.com/)
  2. Login using your Google Account (your GMail account is Google Account)
  3. Type your site URL, for example xathrya.web.id to an empty textbox labeled by Burn a feed right this instant.
  4. FeedBurner then will search for RSS feed on your site. Pick one if there are many feeds you have.
  5. Once FeedBurner found your site’s RSS feed, you will be asked two thins: Feed Title and Feed Address. Type in a title – any title you like – and complete the URL you want to identified your feed.
  6. Complete the registration, and you will see a “congratulation” page.

OK, we have got FeedBurner. Once you are logged in, set the feed.

  1. Click on the link that says “My Feeds” (located on top)
  2. Select the feed from the list
  3. Click on “Publicize”
  4. Click on “Email Subscriptions” (located on the left-hand side)
  5. Verify that “Feedburner” is selected and then click “Activate.”
  6. You will then got HTML codes. Copy the code provided in the box.
  7. Login to your WordPress’ administrator site
  8. Click on “Appearance”
  9. Click on “Widgets”.
  10. “Paste” code to a particular widget which display HTML content.

And thus the step for activating email subscription. Enjoy :D

Email Subscription Feature is Now Activated

Posted: 07 Mar 2013 04:14 PM PST

Well, maybe it’s late but not too late.

This morning I have realized there is no facility for subscription via email. So I have made one. You can subscribe yourself with your email account and receive any new article/news from http://xathrya.web.id/.

Thanks for your support, and enjoy the feed :)

Tidak ada komentar:

Posting Komentar