Short: Happy undocumented quirks

Description of AdjustWindowRectEx() on MSDN:

The AdjustWindowRect function calculates the required size of the window rectangle, based on the desired client-rectangle size. The window rectangle can then be passed to the CreateWindow function to create a window whose client area is the desired size.

Description of GetWindowRect() on MSDN:

The GetClientRect function retrieves the coordinates of a window’s client area. The client coordinates specify the upper-left and lower-right corners of the client area. Because client coordinates are relative to the upper-left corner of a window’s client area, the coordinates of the upper-left corner are (0,0).

You would think that these functions are eachothers counterpart, you give a clientrectangle to AdjustWindowRectEx(), say (200×200) and you’ll get something like 214×234 if you have the Vista look active on your window. When you set your window to those dimensions with for example SetWindowPos(), and afterwards you check the size with GetClientRect(), you’ll get 212×232. This works the same with other themes, and if you copy-paste a screenshot into MS Paint, you’ll be able to measure the same 212×232 while the outside of the window is the exact given 214×234 – properly set by SetWindowPos().

The dirty ugly solution of course is to add 2 pixels to whatever you get back from AdjustWindowRectEx() – but surely someone at Microsoft is supposed to Test these functions?

RECT size;
size.left	= myWindowObj->x;
size.top	= myWindowObj->y;
size.right	= size.left + myWindowObj->w;
size.bottom	= size.top + myWindowObj->h;

AdjustWindowRectEx( &size, GetWindowLong(hWND, GWL_STYLE), FALSE, GetWindowLong(hWND, GWL_EXSTYLE) );
SetWindowPos( hWND, NULL, myWindowObj->x, myWindowObj->y, size.right - size.left + 2, size.bottom - size.top + 2, SWP_NOZORDER | SWP_NOACTIVATE );

Add comment July 5, 2009

Probability

*** I’m not a mathematician, the explanation here is probably crap, so have a look on the internet on factorials and sets.

A friend of mine asked me today if I had a script lying around to produce anagrams. After saying no and secretly checking what the heck an anagram was again, I started thinking about what it reminded me of.

My thoughts diverged on the symbol “!”, which is used in probability to calculate what your chance might be when you eliminate your previous results from the equation. So for example if you have a set of [1,2,3,4,5,6] – after rolling 3 with a dice, the set will become [1,2,4,5,6] so you can’t roll 3 again.

Anagrams are a combination of a set of predefined characters, and then mixed around. And while you might think you’ll have 6^6 possibilities, you actually have less, because you can’t use more of the same characters that are available.

Say for example you have a word of “abc”, you can make “acb”, but you can’t make “aab”, because you only have 1 “a”. Thus in the example of [1,2,3,4,5,6] you actually have 6! possibilities. We can write 6! as 6*5*4*3*2*1 = 720 possibilities.

And the rewrite of 6! is exactly what made me think of this simple algorithm:

procedure factorWord( const sBeginning: string; const sWord: string; const lstPermutations: TStrings );
var
  i, c: integer;
begin
  c := Length( sWord );

  if c = 0 then
  begin
    lstPermutations.Add( sBeginning );
  end;

  for i := 1 to c do
  begin
    factorWord( sBeginning + sWord[i], Copy( sWord, 1, i - 1 ) + Copy( sWord, i + 1 ), lstPermutations );
  end;
end;

 

You’ll initially call it for example with factorWord( ”, Edit1.Text, Memo1.Lines ); and you’ll end up with all the possible anagrams. The function works recursively on 2 sets, one that defines the entire set (Edit1.Text), and one thats starts out empty. With every recursion the possibilities of new characters to add gets smaller, while the anagram is filled with the same amount of characters in a different order, and is added to the stringlist when the recursionpath ends up with 0 remaining characters.

The biggest problem however of making anagrams is that there are simply too much possibilities when you go over about 6 characters. The worst of it, and this is after some code rewrites to append the words to a file occasionally to avoid an out-of-memory error, is that a word with 14 characters will make your textfile about the size of 2.4GB until a file streaming error occurs…

14! = 87178291200 lines, multiplied by “14 byte anagrams plus 2 bytes for the crlf”, you’ll end up with 1394852659200 bytes which amounts to 1299GB of data.

Have fun storing that on your desktop pc…

Add comment May 26, 2009

Search cmp to 0

Search: optimization “cmp eax,0″

You don’t have to compare EAX to 0 to know it’s 0, just make sure the item in EAX is edited last, with any opcode that you see in your cpu manual with the appendage that it modifies the ZF. That’s a fancy flag that says a value you just put in a register is zero.

Any mathematical, bitwise or just plain MOV into a register, modifies the Zero flag. Skip the CMP and just use either JZ (jump if zero) or JNZ (jump if not zero) to see if the zero flag is set and jump somewhere accordingly.

Add comment May 7, 2009

Search query #92385295

It was nice to read someone around the Internet is googling for “optimize code int a = b * 4″.

Of course, most people would think that it shouldn’t be optimized at all, and you’re sort of right, most compilers will optimize this simple piece of code.

But should you want to do it by yourself, there are two nice ways of doing this.

Before I start, I truly hope no compiler will translate this to a MUL opcode, it will eat your cpu-time like pacman when you have the code inside a loop.

The number 4 is awesome, why? Because it’s a multiple of 2. The extra options you instantly get for both division and multiplication when using a multiple of 2 are the opcodes SHR and SHL. Those commands just simply shift all the bits inside a register to the left or to the right. This effectively means that with a simple and fast opcode you can divide by using SHR (div 2 per bit) and multiply by using SHL (mul 2 per bit).

The problem of SHL and SHR is that not every programming language supports direct translation to these opcodes. In C/C++ however you can use “a = b << 2;” for the equivalent of  ”a = b * 4;”, and in Delphi you can use “a := b shl 2;” (I think).

Some other languages do have a bitwise shift function, but they use the rotation shift opcodes (ROL and ROR), which prepends or appends any bits that might’ve fallen off of the other side of your limits. These aren’t the functions you’ll be looking for when multiplying (and dare I say they rarely have any use in the real world).

A slight hickup about SHL and SHL is that some very very old CPU’s didn’t support shifting by more than 1 bit. But you’ll have trouble finding them old pre-486 cpu’s that didn’t.

So yeah, multiplying by 4 is fun. On the other hand, if you have to use odd numbers like 3 and 5, the only option you could consider is using addition instead of multiplication. I doubt however that you’ll get much speed out of that nowadays, unless you’re recursively/iteratively multiplying previous results like in this post.

So there it is, needing to multiple or divide by 2 – use bitwise opcodes.

Add comment April 14, 2009

Yes, I was wrong

… you can’t make traffic go one way for one port, and another way for some other port.

Why? Because you’re most likely stuck with switched traffic that only sends traffic down one cable when it figures out a certain network-address is connected to that cable.

However, I did manage to subtract one router out of the equation with the wondrous discovery of selective NAT. Aparantly you can change the default source 0.0.0.0 ACL to a specific per port list. The ip’s and ports that don’t match the ACL won’t be translated. Which is exactly what I was looking for.

This does require that with every port forward from your isp’s router to be added to the ACL of the 2nd router, but that won’t be that much of a problem.

Add comment March 21, 2009

And when your internet breaks down…

… you start connecting that console link again and start typing to get that other internet connection to work.

In this post I explained I had made a network of 3 routers so that my web-/database-/whatnot-server was able to serve over

2 different external IP’s via 2 different ISP’s (one broadband, one dsl). It had a hickup however in that the 2nd ISP couldn’t be used for normal Internet surfing etc. This was because it has a NAT configuration upside down to avoid the default-router issue.

lannetwork1

So now I have connected a 4th router to do normal routing between the internal 192.168.0.0 network and the other network 192.168.2.0 to get to the router that connects to the dsl isp (still following?)

It proved to be quite simple (feel a bit silly to use the router for such easy work). It just routes to and from both network interfaces, with the

exception that it blocks all traffic to and from the server (because that one should use the other router with the upside down NAT configuration).

And then it just works. (well, you need to manually set the gateway of your client ofc.) I could probably make the server be able to connect to the other isp as well as long as I make sure the proper ports are blocked… But that’s stuff for at a later time.

Add comment March 14, 2009

To kill time…

Add comment March 14, 2009

insert into education (info) values (:thispost)

Check your input data before inserting it into an SQL Query.

The issue of SQL-Injection has been raised since like 5 years ago, and still there are people who keep ignoring it.

If you’re using PHP to query your database, make sure you’re not inserting crap first.

The easiest things you can do, and you can make it pretty complicated, are the following:

Check integers and ID’s given by the user

    if ( !is_numeric( $userinteger ) ) {
       return false;
    }

Don’t just insert strings, escape them

    $sql = "select * from users where username=':user' and password=SHA1(':pass')";
    $sql = str_replace( ":user", mysql_real_escape_string($user), $sql );
    $sql = str_replace( ":pass", mysql_real_escape_string($pass), $sql );
    $res = mysql_query( $sql );

And stop using MD5.

Add comment February 23, 2009

Hacking a filter for Twitter

The following php script fetches a Twitter RSS feed and filters out all the irrelevant comments you made.

<?
// replace url with your twitter rss feed
$lines = file( "http://twitter.com/statuses/user_timeline/1234567890.rss" );

$skip = false;
$c = count( $lines );
for ( $i = 0; $i < $c; $i++ ) {
    $line = $lines[$i];

    $p = strpos( $line, "<item>" );
    if ( $p !== false ) {
        // Replace YourName with your twitter account name
        $p2 = strpos( $lines[$i+1], "YourName: @" );
        if ( $p2 !== false ) {
            $skip = true;
        }
    }

    if ( $skip ) {
        if ( strpos( $line, "</item>" ) !== false ) {
            $skip = false;
        }
    } else {
        echo $line;
    }
}
?>

2 comments February 22, 2009

Serving over multiple external IP’s

Normal people tend to just rely on 1 single internet connection to do both websurfing and server hosting, and some might even wonder if 2 internet connections is even going to work.

Let me explain why you can’t use 2 external ip’s in a normal 2x modem-router-network configuration.

To make things easy, I’ll give the actors some names in this example;

  • Alice is the person who’s visiting your website
  • Fred is the name of your internal web server
  • Lucy is the name of the first router, and is the default router for outgoing traffic
  • Peter is the name of the second router

When you configure Peter to forward/translate a specific port (eg tcp 80 for http) you supply the internal IP address Fred, and everything just works. Peter copy/pastes Fred’s mac-address into the IP-packet, changes the port number if needed, and sends it to your network. The external source IP address of Alice is still there in the packet, and Fred will use that IP address to send packets back Alice containing your website and other things.

When Fred tries to figure out on how to reach Alice, he figures he should just use the default router that is supplied in his network configuration, so he puts the MAC address of Lucy into a packet along with Alice her IP address and sends it. Lucy has NAT to go onto the big bad internet, so instead of Fred’s IP, she puts her own external IP address into the packet and adds some reference material into her memory so she knows that returning packets will have to go to Fred.

However, when Alice finds out that the external IP address is from Lucy when she wanted to see the website that Peter promised, she hits the panic button and tells Lucy to leave her alone, and tries to talk to Peter again – ignorant of the fact that Lucy was just relaying the same website.

Solution 1

Get a very expensive router that has 2 seperate WAN ports that remembers which way a certain stream of packets was going and sends things back on the same path. Unfortunately I don’t have one of those, so I can’t tell you how that exactly works, nor if it actually does work.

Solution 2

Get a third router and set it up to serve with a not so very logical NAT configuration.

From the example given you can see one occasion where a router does actually remember information about previous packets. Lucy masks her outgoing packets to pretend the packets are coming from her external IP address instead of an internal IP address. And you can abuse this exact mechanism to force webserver Fred to send his packets to the right router.

How that exactly works:

  • outside has an external IP
  • inside has an internal IP
  • NAT masks packets going from the inside to the outside
outside        outside
 Peter          Lucy
inside         inside
   |             |
   |             |
   |        192/168.0.0/24
   |             |
192.168.2.0/16   |
   |             |
   |             |
 inside          |
 Markus          |
outside          |
   |             |
    \            |
      \          |
      192.168.0.10
         Fred

When Alice requests a website via Lucy’s outside IP address, Lucy directly sends it to Fred, and Fred has Lucy has his default router and thus sends it back through that route.

When Alice requests a website via Peter’s outside IP address, Peter wants to send it to Fred, but he can’t find Fred. Markus however tells Peter to just give it to him, and he’ll give it to Fred. Then Markus masks Alice her IP address with his own outside IP address, and sends the packet to Fred. When Fred wants to send something back, he thinks Markus sends the packet, and just sends it to him. But Markus checks his memory and remembers he should send it to Alice. All Markus needs to know now is that he needs to send things through Peter to get to Alice.

The downside

The unfortunate by-product of using a third router is that you can’t connect the 2nd internet connection directly to your local network, because then traffic wouldn’t be masked. So to use the 2nd internet connection as a Backup internet gateway, you’ll have to use a 4th router with a very careful routing scheme to not conflict with the internal nat router. I haven’t tried that out yet, but I have another Cisco 1841 lying here I might give it a go with as soon as I can get my hands on another switch…

Add comment February 22, 2009

Previous Posts


RSS Twitter

 

July 2009
S M T W T F S
« May    
 1234
567891011
12131415161718
19202122232425
262728293031  

Categories

Blogroll

Meta