Shuva's blog
Using the goto statement in C effectively. 
Tuesday, April 29, 2008, 11:48 AM - Programming
Talking of the goodness of the goto statement in C programming is often considered evil. People would just rubbish you the moment you say “We can use a goto statement to do this .....”. The common cited usage of goto is to implement a break out of more than one level of for or while. I think I have realized another good situation to use the goto statement from my own experience.

Take this example:
int function() {
SOME_STRUCT someStruct;
char* file = NULL;
char* folder = NULL;
char* drive = NULL;
HANLDE *ptr = NULL;

ptr = AtleastDoThat(file, folder, drive, & someStruct));
if (ptr == NULL) {
CloseHandle(ptr);
return 1;
}

file = new char[100];
if (!DoSomething(ptr, file)) {
CloseHandle(ptr);
delete[] file;
return 1;
}

folder = new char[100];
if (!DoSomethingElse(ptr, file, folder)) {
CloseHandle(ptr);
delete[] file;
delete[] folder;
return 1;
}

drive = new drive[100];
if (!AtleastDoThis(ptr, drive, file, folder)) {
CloseHandle(ptr);
delete[] file;
delete[] folder;
delete[] drive;
return 1;
}

return 0;
}

In the above example we have a bunch of local variables which gets allocted progressively and its this function’s responsibility to clean before exit. There can be multiple exit points and you have to make sure to clean all of those variables that you have allocated some resource. In real time, this function will look very dirty and not as clean as simple new and delete[]. The problems with this code are:

1. As this function adds more code, there is a risk that the programmer will miss to clean up as he has to put the cleanup code at multiple places.
2. Readability is bad.
3. The reader has to un-necessary go through all the cleanup code while reading the actual logic. Attention is diverted.

Now take a look at this:

int function() {
SOME_STRUCT someStruct;
char* file = NULL;
char* folder = NULL;
char* drive = NULL;
HANDLE *ptr = NULL;

ptr = AtleastDoThat(file, folder, drive, & someStruct));
if (ptr == NULL) {
goto error;
}

file = new char[100];
if (!DoSomething(ptr, file)) {
}

folder = new char[100];
if (!DoSomethingElse(ptr, file, folder)) {
goto error;
}

drive = new drive[100];
if (!AtleastDoThis(ptr, drive, file, folder)) {
goto error;
}

return 0;

error:
ptr?CloseHandle(ptr):NULL;
file?delete[] file:NULL;
folder?delete[] folder:NULL;
drive?delete[] drive:NULL;
return 1;
}

The idea of discouraging goto is that people tend to misuse it by not writing elegant conditional jumps thereby reducing readability. In this case I find it increases readability. Many programmers use this technique. Thoughts?

Happy branching.//

add comment ( 154 views )   |  0 trackbacks   |  permalink   |   ( 3 / 44 )
5 new development features (C++) in Windows Vista 
Friday, April 18, 2008, 07:44 AM - Design concepts
Powered By ReadTheWords.com
Over the last few days I have been doing some reading and have come across articles talking about the goodness of Windows Vista and Windows Server 2008. Its not about the 100 reasons why Vista is good. I came across some reasons why Vista would be good from a software developer point of view. Its very difficult to get a list of all the new C++ new features in Vista. Here is a list of some of the items I could gather and most of them are related to interprocess communication, security and threading (coz thats what I am currently working on).


Conditional variable: A condition variable is typically used by a thread to make itself wait until an expression involving shared data attains a particular state. They are also called Monitor objects by many authors. In Linux, this is supported by “pthread_cond_t”. See man pthread_cond_init. See this article from Microsoft to understand Conditional Variables in Vista. See this API page for an example and the exact APIs.

Reader/Writer Locks: Imagine you have N threads and a critical data that they use. If of these N threads, it generally happens that only a few would be updating the data and the rest would just be reading the data. Most programmers would simple use a critical section around both read and write operations on this critical data. The truth however is that, if there is currently no write operation on the critical data, then all the readers CAN have access to the critical section simultaneously. This increases performance. Windows Vista introduces native support of this concept via Reader/Writer Locks. See this MSDN page for the exact API. A Unix implementation exists as rwlock_t. See man rwlock_init .

SetProcessDEPPolicy Function: This changes data execution prevention (DEP) and DEP-ATL thunk emulation settings for a 32-bit process. What the hell is this? Lets first do a quick revision on the layout of a program(an .EXE file). The point to revise is that code segments and data segments are two separate things in the memory at run time. Most buffer-overrun attacks are done by overriding data with some malicious code. Now if the CPU was designed never to execute instructions which lie in the data section, then these nasty buffer overrun attacks will be stopped. This capability is supported by the NX feature in the CPU. The good news is that almost every CPU now a days supports NX capability. You can link your C++ program with the /NXCompat linker option to enable this for your executable. Vista adds an API also which you can call in your program to do this. Read this MSDN page for more.

Randomization of the heap: There is something called ASLR (Address Space Layout Randomization), meaning that the OS randomizes the address space of your program so that it become difficult to predict location of vulnerabilities in a running image. In Vista, this randomization is extended to your program heap also.

Thread Pool API: Vista introduces Thread Pool API for C/C++ programmers. I have been using Boost thread pool(actually an extension of the Boost thread library) which is a cross-platform implementation. Just by looking at the Microsoft Thread Pool API, it appears that we need quite a bit of reading/understanding than what is traditionally considered enough to understand thread pool.

Happy Programming.//


add comment ( 86 views )   |  0 trackbacks   |  permalink   |   ( 3 / 37 )
Perl script to authenticate and send email 
Tuesday, April 15, 2008, 06:36 AM - Programming
Powered By ReadTheWords.com
In all my jobs as a software developer there was always a need to write a script that would send me an email notification for an automated job. I had always used Perl to send me the email via the SMTP server. If you do a simple Google search you would find numerous examples of such a Perl script. But it is unlikely that you would find an example that tells you how to authenticate yourself to the mail server. Many SMTP mail servers are configured to require authentication only to get emails and not send. Some require authentication both ways.

Below is a simple Perl script that would authenticate to the SMTP server before sending the mail.

#!/usr/bin/perl

use Net::SMTP;

sub send_mail {
my $to = $_[0];
my $subject = $_[1];
my $body = $_[2];

my $from = 'yourmailboxname';
my $password = 'yourpassword';

my $smtp;


if (not $smtp = Net::SMTP->new('mailservername',
Port => 25,
Debug => 1)) {
die "Could not connect to server\n";
}


$smtp->auth($from, $password) || die "Authentication failed! $! \n";

$smtp->mail($from . "\n");
$smtp->to($to . "\n");
$smtp->data();
$smtp->datasend("From: " . $from . "\n");
$smtp->datasend("To: " . $to . "\n");
$smtp->datasend("Subject: " . $subject . "\n");
$smtp->datasend("\n");
$smtp->datasend($body . "\n");
$smtp->dataend();
$smtp->quit;
}

&send_mail('deb_shuva@emc.com', 'Test email', 'Some more detail');


Happy Emailing.//
add comment ( 54 views )   |  0 trackbacks   |  permalink   |   ( 2.9 / 37 )
How to send email from your command prompt. 
Thursday, April 10, 2008, 11:42 AM - Tips and Tricks
Below is an example of how to send an email via your Microsoft Exchange Server using your command prompt. The text in bold is the user input and the other is the response from the server. An explanation of the user input is given below this.

First we need to connect to your Exchange server. The default SMTP port is 25.

telnet mailserver 25
220 mailserver.domain.com Microsoft ESMTP MAIL Service, Version: 6.0.3790.1830 ready at Thu, 10
Apr 2008 07:21:40 -0400
ehlo
250- mailserver.domain.com Hello [198.144.308.198]
250-TURN
250-SIZE 15682560
250-ETRN
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-8bitmime
250-BINARYMIME
250-CHUNKING
250-VRFY
250-X-EXPS GSSAPI NTLM LOGIN
250-X-EXPS=LOGIN
250-AUTH GSSAPI NTLM LOGIN
250-AUTH=LOGIN
250-X-LINK2STATE
250-XEXCH50
250 OK
auth login
334 VXNlcm5hbWU6
eW91IGRvbnQgZ2V0IG15IHVzZXIgbmFtZSBqdXN0IGxpa2UgdGhhdA==
334 UGFzc3dvcmQ6
bmVpdGhlciBkbyB5b3UgZ2V0IG15IHBhc3N3b3JkIHNvIGVhc2lseQ==
235 2.7.0 Authentication successful.
mail from: shuva @something.com
250 2.1.0 shuva @something.com....Sender OK
rcpt to: shuva @something.com
250 2.1.5 shuva @something.com
data
354 Start mail input; end with <CRLF>.<CRLF>
Subject: Hello
This is a test email sent from the DOS prompt. I am loving this.
.

250 2.6.0 <Jpj00001ceb@mailserver.domain.com> Queued mail for delivery



Please note that, to end your message you press Enter, then enter a full-stop, then press enter again. (354 Start mail input; end with <CRLF>.<CRLF>)

<Press Ctrl + ] to close this connection >

Now let see all the user commands one by one.

elho : This is an initial greeting to your mail server. SMTP uses helo and ESMTP uses ehlo. You can find if your server is SMTP or ESMTP as soon as you do a telnet to post 25 of your server.

auth login : You are telling the email server that you would be sending your username and password now. (Many email servers don’t require login credentials to send emails, but some do). You username is your mailbox name and not necessarily your email address. In most corporate world it is generally your Windows login id. Example, EMC\shuva and your password is, of course, your password. However the mail server takes in your user name and password in BASE-64 encoded format only. So you need to encode your username and password using a base 64 encoder. There are many online ones. Try any one of them. There are a few links at Wikepedia. I used this one. First type in your encoded username, press enter. If you get the number 334 as the next line, then its good. Then enter your encoded password. You should get the line saying “Authentication successful”.

I guess the rest of the stuff is self explanatory.

In a few days I will post a Perl program that will do the same stuff.

Happying emailing.//

add comment ( 337 views )   |  0 trackbacks   |  permalink   |   ( 3 / 31 )
Trying to remove God 
Thursday, April 10, 2008, 07:58 AM - Just a thought
Powered By ReadTheWords.com

Can you explain the stuff below?

[root@shuvavmrhel ~]# who am i
root pts/2 Apr 10 13:13 (shuva)
[root@shuvavmrhel ~]# ll God
-rw-r--r-- 1 root root 0 Apr 10 13:16 God
[root@shuvavmrhel ~]# chmod 777 God
chmod: changing permissions of `God': Operation not permitted
[root@shuvavmrhel ~]# rm -f God
rm: cannot remove `God': Operation not permitted
[root@shuvavmrhel ~]# cp God satan
[root@shuvavmrhel ~]# ll God satan
-rw-r--r-- 1 root root 0 Apr 10 13:16 God
-rw-r--r-- 1 root root 0 Apr 10 13:18 satan
[root@shuvavmrhel ~]# rm -f satan
[root@shuvavmrhel ~]# ll God satan
ls: satan: No such file or directory
-rw-r--r-- 1 root root 0 Apr 10 13:16 God
[root@shuvavmrhel ~]# rm -f God
rm: cannot remove `God': Operation not permitted
[root@shuvavmrhel ~]# who am i
root pts/2 Apr 10 13:13 (shuva)
[root@shuvavmrhel ~]#

Does God really exist?

add comment ( 64 views )   |  0 trackbacks   |  permalink   |   ( 3 / 50 )

<<First <Back | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | Next> Last>>