Author Archives: Pablo Yabo

A comparison of Deviare and EasyHook

December 16th, 2008 | Posted by Pablo Yabo in Deviare | opinion | products - (3 Comments)

We are comparing our hooking engine Deviare with some of the other products available, so that you can get an idea of what each engine can provide.
Here is a comparison of Deviare against Easy Hook.

Functionality Deviare EasyHook
Database with Functions and Data Types Yes No
Intercept multiple functions with a single handler Yes No
Selective Handler for each Function Yes Yes
Relocation of Relative ASM Instructions (RIP) Yes No
Save & access Call Function Context Yes No
Access registers & flags Yes No
Access return address Yes Yes
Get/Set win32 last error Yes Yes
Monitor COM Objects creations Yes Partially
Hook COM Objects Yes No
Provides COM Interfaces accessible from any language Yes No
Enumerate process’ modules Yes Yes
Enumerate module’s exported functions Yes No
Get module path and info Yes Yes
Automated call of original function Yes No
Thread Deadlock Block Yes Yes
64 bits support No Yes
Thread Safe Hook Install Yes No
Native Support Yes Partially
Inter-Process Communication Yes Partially
Custom Library Injection Yes Yes
Stealth Support No Yes
Kernel Mode Hook No Yes
Driver Installation No Yes
Relocation of Instruction Pointer Yes No
Requires .Net Framework No Yes
Use System Runtimes (CRT) Yes No
Hook Terminal Sessions No Yes
Full unload before target termination. Yes No
Execute As Service No Yes
Prevent execution inside OS Loader No Yes
Thread selection filter No Yes
StackTrace Yes Yes
User-mode Wide Hook Yes No

We all remember when Ole Automation came out. We were all impressed how simple it was to implement a few COM Interfaces, place a toolbar and interact with the office package. Soon the competition began to show who could create the best and most creative Add-on. How many times did you wonder how that other plug-ins “did that”? What if now you can even know how Outlook, or any Office application operates? Well, my friend, take a closer a look…

This Deviare example is implemented as an Outlook Add-on. We have used C# .Net, but you can use any language that supports Component Object Model.

We are using 2 threads to avoid freezing the application. The first one is the standard thread where Outlook report its events to us. The second is our worker thread where we create an output window to print our messages and a Deviare Event Proxy to process functions’ calls.

sc1

From the events Outlook provides us to work with we are only interested in OnStartupComplete. Here we know that Outlook is done with all its initialization and we can start hooking its interfaces. As a regular plug-in we ask for the Outlook Application, Active Explorer, CommandBars and create a CommandBarButton. We are going to intercept all of them and see how their members are used.

sc2

Notice that to obtain the interface we don’t use the class implementation, but the underlying interface definition. That’s why, when calling HookInterface, we send the Type of Outlook._Application and not Outlook.Application. The second one, is the .Net wrapper, and the first one is the Ole Interface.

To intercept these objects, Deviare needs some information. The necessary elements are the COM Object Interface (that would be its virtual table), which members we are interested in (specified by index), and the name of the Interface. Identifying the interface by name, will let Deviare find all the information it needs during the call, so you can handle its parameters the same way we did with any function hook. To gather all this the .Net Framework provides us with marshaling facilities (System.Runtime.InteropServices.Marshal), this makes our lives pretty easy ;) .

sc3

And that’s all. We print our calls, and see our results:

sc4

Cheers, and happy coding!

Open source software

November 11th, 2008 | Posted by Pablo Yabo in firefox | opensource | opinion - (2 Comments)

Everyone likes something for free, but open source is free as in freedom not as in beer.

Lots of companies use open source software and many put a lot back into the open source world but just how much do they put back?

It is impossible to find a definitive answer to this so we are just pointing out some ethical issues, when a “leecher” takes the work of others without giving back its detrimental to the open source movement.

In 1993 Apple’s Operating System was seriously in need of an upgrade. Their internal development of a new OS was not going well, so they looked externally for an OS.  BeOS and NeXTSTEP were the main candidates,  BeOS was a completely new OS developed from scratch and NextSTEP was an OS built on top of BSD.  They went with NextStep and acquired the company behind it NeXT for $429 million.  BeOS was later bought by Palm, inc after which they discontinued BeOS.  BeOS users without a viable upgrade path and BeOS developers with programs stranded on an unsupported platform then decided to develop Haiku, an Open Sourced operating system.

NeXTSTEP then went on to become MacOS X.  Apple released the Open Sourced Darwin, The core components of MacOS X, in 2000 under the Apple Public Source License.  This release spawned OpenDarwin, a project designed to create a stand alone Darwin operating system.  This failed with the developers stating OpenDarwin had “become a mere hosting facility for Mac OS X related projects.  Availability of sources, interaction with Apple representatives, difficulty building and tracking sources, and a lack of interest from the community have all contributed to this.” There is a new project called PureDarwin which is currently trying to complete a release based on Darwin 9.

Apple used to distributed a binary release of Darwin themselves but stopped in 2005.  Currently they only release the source code of Darwin, Although within this they include proprietary drivers of their AirPort wireless cards.  They also exclude Carbon, Cocoa, Quartz Compositor and the Aqua user interface.  This prevents users from running MacOS X software.  There were good reasons for Apple to go via the closed source route for these but when taking so much from the Open Sourced Community surely it would be nice to give more back? Although some people say Apple have saved BSD.

Microsoft is a company well known for their closed source software.  Originally network protocols were an add on to their operating systems and it wasn’t until windows 95 that the TCP/IP Stack became part of the operating system.

Originally they tried their own protocol Netbeui and then reverse engineered Novell’s IPX protocol but finally they adopted the BSD’d TCP/IP (you can see the BSD license within their source here.) There is nothing ilegal in Microsoft using the BSD code for their implementation of TCP/IP but because the code was under the BSD license any changes they made were not released for the benefit of the rest of us.  If the code had been under the GPL license would they have used it?  Who knows but it would have forced them to release any updates they made.  Maybe they would have developed an alternative protocol and the internet would not be as it is today!

Flock is an interesting case of a company using open source for the basis of their product.  Flock itself is an open sourced project where

“Yes, Flock will be open source.  We may incorporate some proprietary technologies into our browser and releases some features under a commercial license, but all of our initial code, and the vast majority of our code going forward, will be open source.”

We know the Flock developers want to keep Flock compatible with Firefox and it may be based on Firefox, but they are two separate projects.  Code will increasingly change and although extensions currently work on both browsers as the code develops we’ll see extensions working with either Firefox or Flock.  What will happen if Firefox decide to implement some of Flock’s ideas differently?  Will Flock go to their source and follow the way Firefox have implemented the idea?

Would it have been possible for the Flock developers to have just released an extension that just adds the tools that Flock adds?  With the creation of a new browser they have potentially forked the developers of extensions for Firefox.  Flock has investors to keep happy,  is it possible for them to do that whilst keeping extension compatible with Firefox?

What about Google’s File system? This is a customized file system that writes LARGE chunks of data and sits above a standard Linux file system.  What changes have Google made to the “standard” Linux file system? Are they going to give the open source community their code? As the software is running on a server and not being distributed they don’t need to share the code but should they?

We all know Google also uses a stripped down optimized version of the Linux Kernel for high performance without which they couldn’t possibly exist.  What changes have they made that they’re not sharing with the rest of us? The hiring of Andrew Morton does help though.

For example there are a number of companies that use dmoz.org data the most well known being Google Directories which combines the dmoz data with its own pagerank. Does this make dmoz irrelevant? How are they contributing to the dmoz project?

When money becomes involved it isn’t uncommon for a project to move from open source to closed source.  Activecollab was one such project,  originally released under an open source license, it has since moved to a closed source commercial project.
“When it was first released, activeCollab came with an open source license and that was what attracted me to the project. I thought it held promise of being a very powerful and useful project management application if developed by an active community of users.
But the developer has decided to stop open source development on the project. Development will now be closed source, at least on the core features. The next release, version 1.0 due out next week, will also not have a free version. Your only options for activeCollab 1.0 are SmallBiz ($199) and Corporate ($399).”

Although a fork has been started the move to closed source will have alienated a lot of developers and users.

It is interesting to watch Mozilla to see how their creation of a “for profit” corporation which supports the popular Firefox Web browser and Thunderbird E-mail client as well as developing custom software based on open sourced products.  This happened in 2005 now 3 years later has much changed?

“the Mozilla Corporation is not a typical commercial entity and will only pursue revenue-generating activities that are consistent with offering end-users with the best experience possible.”

Mozilla did ask the public for money in a 2 page advert on December the 16th 2004.  This was before the creation of their commercial wing but with reports of as much as $72 million being poured into Mozilla Corporate from Google for carrying Google advertisements why are they still asking for donations?

Should the people who donated before the corporate side was formed be considered shareholders of Mozilla corporate? What about new donators?  Why should you donate to an organization that has a very wealthy corporate company behind it?

Will all the contributors to Firefox and Thunderbird be given shares or money for their work that the Mozilla corporation are profiting off?

We can see that Firefox and Thunderbird are both still available for free from the Mozilla website, Both currently supported by Google’s Ad money and donations, but for how long?  With Firefox being the cashcow for Mozilla Corporate will Thunderbird fall by the wayside?  There are rumors that it will find itself under a different company with Mozilla Corporate becoming Firefox Corporate.

One companies solution is the advent of dual licenses.  They release their software as both open source under the GPL and as a commercial product.  This allows them to employ staff full time to work on the product, It also allows companies that wish to use the software and modify it but not share their code with others that opportunity.

In the Games Market id Software also license their older game engines under the GPL as well as offering the opportunity to use their engines under a commercial license. Other companies such as 3d Realms and Parallax Software have released the source code for some of their games but without a commercial option for their engines.  The dual license here obviously benefits companies wishing to add to the source code to the detriment of being forced to release possible upgrades to the original open source engines.

Another place where Open Source software has taken off is in Web services. Many companies are taking advantage of Open Source software on the Web but they’re not obligated to publish their code if they make any changes because they are not redistributing the software in a package as either a download or a physical medium.  The web is a new distribution medium for them.

A License has been developed to apply to the software that is in this loophole, The Affero GPL.  This licenses software that is ran on a server.  One such project is in the UK where petitions to the Prime Minister is ran on Open Sourced AGPL v3 software.

What is the fair value of return to the open source if you earn a lot of money?

“IBM says to a customer, ‘Do you want proprietary or open software?’ Then if they want open source they say ‘OK, you want IBM open source.’  It is always IBM or Sun or HP open source,”

“Companies are using the potential of communities as subcontractors — the open source community today is a subcontractor of American multinational” said Jesús Villasante, head of software technologies at the European Commission

in reply James Baty, a vice-president at Sun, said that companies such as his have a responsibility to contribute to the open source community.  Sun itself contributes to a number of open source projects, including the open source productivity application OpenOffice.org.

“There are companies that are takers from the open source community, other companies are taking the attitude that they have to contribute, Open source should be seen as an opportunity, not as something to capture and abuse.”

We know major corporations have made valuable contributions to open source software, as well as persuading businesses and IT professionals that it is a credible alternative to proprietary options, but do they take more than they provide?

We here at Nektra Believe Open Source will always have an important place in the world and provide CookiePie under GPL, NKT WAB under LGPL and Trappola under LGPL, but it is essential that the Open Source community is not taken advantage off and valuable contributions are put back into the community.

Deviare COM Spy Console is out!

October 28th, 2008 | Posted by Pablo Yabo in C# | C++ | Deviare | programming | videos - (0 Comments)

Today we have released a console for monitoring and spying on applications using Microsoft’s Component Object Model. This technology is used in many professional applications and now you are able to watch them in action too!

Deviare’s last integration is the ability to intercept COM interfaces. Using this technology and heuristics to discover this interfaces, the console lets you see which interfaces are being used by an application, and how they made their calls.

Here is an example monitoring the Windows Live Messenger:

As you have seen, we found the instantiation of IwebBrowser2. Since we don’t know what we want to see yet, we hooked every member except IDispatch (not necessary here). Then, the console printed calls for Navigate2 (among others), and we could see where the little browser at the bottom of messenger was getting its Adverts from.

The console is open source, so feel free to contribute on it. In this first release, it contains only one method to discover the creation of interfaces, but many others may be added. Go chase them ;) .

Download Deviare COM Spy Console

The truth about Google Chrome using Spy Studio

October 15th, 2008 | Posted by Pablo Yabo in Deviare | examples | opinion | products | SpyStudio - (11 Comments)

Everyone has a lot of questions about Chrome.  Some people say that it is spyware because each and every character you enter is sent to Google.  Hundreds of comments like this can be found on the web, like this one that says “Chrome spends nearly as much time phoning home to Google as it does talking to other Web servers.”  On the other hand, you can also find on the web the opposite opinion that claims “If you do not wish this data to be sent to your search provider, you have a number of options: Use incognito mode, turn off search suggestions permanently or change your search provider.”

Who is correct?  What kind of information is really traveling between Chrome and Google?  What data about you is being sent to the web?  Is it true that Google’s browser sends details about everything you do?  Is it an unsafe browser?  What happens behind Incognito mode?

The first thing we want to know is “What information does Chrome send about visited sites to Google”? Many different opinions can be found on the web, and some are really alarming.  One person says that toolbarqueries.google.com collects everything the browser sends to it.  This is indeed true, and you can see in metrics_service.cc [chromium.org], what information about visited websites is being sent.  Although this only happens if you selected it in Chromes ‘Under the Hood’ (Options -> “Help make Google Chrome better by automatically sending usage statistics and crash reports to Google”) this option is not selected by default, you have to specifically select it during the Chrome installation.  Using SpyStudio you can be 100% certain about this by checking and un-checking the option, and watching all the ‘send’ function calls.  So, does Google Chrome send information about every website you visit to toolbarqueries.google.com?  The answer is no, it does it only if you request it to.  This doesn’t mean that other information, like the one send to google-analytics, is not being sent anymore.

However it is interesting to notice that this behavior is exactly the same under Incognito mode.  This means that if the option of sending usage statistics is checked, it doesn’t matter what mode Chrome is running, the statistics are sent anyway.  We know that the only differences between normal and Incognito modes are the logging of websites visited, files downloaded, download histories and cookies.  So this feature is local to the machine, and nobody has said that statistics are not sent under this mode.  Although I think for many of us, we implicitly assume to be anonymous while running Chrome under Incognito mode.  So we better keep the limitations of this feature in mind!  Again, this only applies when sending statistics option is selected.

The other feature we want to inspect is the suggestion made by the address bar: “When you type URLs or queries in the address bar, the letters you type are sent to Google so the Suggest feature can automatically recommend terms or URLs you may be looking for.”  This is highly controversial, we want to know about this feature when using Incognito mode (in which the suggest feature seems to be automatically disabled). Again we can use SpyStudio to make sure.  You can see that Chrome does not send any information to Google about your key strokes when using Incognito mode.  You can also watch calls to GetAddrInfoW function, which provides protocol-independent translation from a Unicode host name to an address.
When you are not running on Incognito, you can turn this off by right clicking on the address bar and selecting “Edit search engines…” Then uncheck the check box at the bottom labeled “Use a suggestion service to help complete searches and URLs typed in the address bar”.

We can now safely stop all the paranoia about Chrome.  We can see the information that Google Chrome sends to Google using SpyStudio and we know that this depends on the options you choose.  So Chrome is not spyware that sends everything you do to Google.   I also believe it is important to understand what features the Incognito mode provides and not assume things about it.

Watch Google Chrome

See for yourself the information that Google Chrome sends to Google.  Use Nektra’s SpyStudio to monitor Chrome’s behavior.  It is very easy:

  1. Download SpyStudio from Nektra’s website free of charge and install it.
  2. Replace the database ‘deviare.fdb‘ with a new version.  You will find ‘deviare.fdb’ in the path you installed SpyStudio: SpyStudiobin
  3. Download the script chromewatcher and then add the path where you saved it to SpyStudio.  Edit -> Preferences -> Python
  4. Run SpyStudio and import the module chromeWatcher by typing “import chromeWatcher” in the Python console.  Then start monitoring by calling the Begin() function by typing “chromeWatcher.Begin()”.
  5. Now watch SpyStudio while using Google Chrome to find out what information is sent by Chrome.

What does the ChromeWatcher script do?

The ChromeWatcher module was specially made to capture calls to the Winsock functionssend‘ and ‘WSASend‘. To know where the information is going, a socket connections track must be kept.  So it is necessary to hook ‘connect’ and ‘select’ functions too.  The idea behind ChromeWatcher is to hook ‘send’ and ‘WSASend’ calls that are made to Google and show them to you.
To understand better this script you can see SpyStudio documentation on: SpyStudiodoc

How make a high quality video for YouTube

September 29th, 2008 | Posted by Pablo Yabo in videos - (3 Comments)

YouTube is very popular. It can also be very useful for companies to promote their products.

It provides free hosting of your video and allows you to embed it on your website,  this keeps your companies bandwidth costs down.  YouTube also provides a social network for its users allowing videos to be commented on and voted for and promoted within YouTube itself!

When creating the videos for OEAPI, CookiePie, Deviare and SpyStudio. I did some research on how to make a High Quality video for YouTube but found no complete source on how to make it from scratch using free software.

I used the following software for making my videos.

CamStudio 2.0 too record my desktop. (GPL)
Audacity 1.3.5 too record audio for the video. (GPL)
Virtualdub 1.8.5 for cutting and encoding. (GPL)
G.I.M.P. 2.4 for creating a company logo to put at the start and end of my video. (GPL)
JPGAvi 1.07 for converting the jpg into an avi frame. (Free/Donateware)
XviD Codec for encoding the video. (GPL)
LAME for use of MP3 in Audacity. (LGPL)

The main problem with using YouTube for your video is that the default videos are 320 x 240 resolution, using the H.263 codec that was developed in 1995.  This provides a low quality blurry picture that makes it almost impossible to see what is going on.

YouTube have recently added an option to view their videos at an increased resolution.  This is at 480 x 360 and also comes in 2 different Codec formats H.264/MPEG-4 AVC with stereo AAC sound and the standard H.263 but in the higher resolution.

To make the videos:

CamStudio Full Screen

CamStudio Full Screen

I used CamStudio to film the full desktop but i set the desktop size to a more viable 800×600 so it can be viewed easier on YouTube.

CamStudio Autopan

CamStudio Autopan

I also duplicated the recording by repeating the exact same things but this time using cam studios panning option i recorded an area of 320 x 240.

We then needed to convert these videos in something usable and manageable so we could edit them.  I did this by loading both videos into VirtualDub and changing them as follows.

For both recordings.

Video > Filter > Add > Resize

Then changed the Absolute (pixels) to 480 x 360 resolution.

VirtualDub Resize

VirtualDub Resize

The default frame rate from CamStudio is 200 fps which is unnecessary for what we need so i downgraded both videos to 30 fps.

Video > Frame Rate > Convert to fps

VirtualDub Framerate

VirtualDub Framerate

Raw video editing requires a large amount of harddrive space.  To get around this without losing much video quality i also re-encoded the video into Mpeg4 format using the XviD Codec.

Video > Compression > XviD MPEG-4 Codec.

Xvid MPEG-4 Codec

Xvid MPEG-4 Codec

Then to make the videos.

File > Save as AVI.

A start and end to the videos was needed.

I did this by placing the Nektra Logo on a 480 x 360 background and loading it into JPGAvi.

Nektra Logo

Nektra Logo

This outputs a small avi file that i then loaded into VirtualDub and changed the Resolution,  Framerate and encoding in the same way as above.

I then copy pasted the single frame until the start was 5 seconds long.

Now with all the videos ready for editing i started a new project in VirtualDub and appended the video i needed starting with the logo introduction.

File > Append AVI Segment

I went through both videos (closeup and full screen) selecting areas and exporting them to be imported into the final video.

Edit > Set selection start

Edit > Set selection end

This gave me the video i wanted which i could then use Audacity to record a voice over.  Exporting as a mp3 i can then use VirtualDub to place the audio track in the AVI.

Audio > Audio from other file

This video when uploaded to YouTube can then be embeded on your own website in both
Standard

and High Quality by adding &ap=%2526fmt%3D18 to both urls in the embed code.

Today we are releasing Trappola, our hook engine, under LPGL license. It has been a part of Deviare since its early beginning. And we think it reached a maturity level that any developer can appreciate.

There are several libraries that provide some of the functionality we give here. But most of them are theoretical examples, or very custom, that do not adjust well to every situation. In contrast, we designed it to suit to most situations and solve most common mistakes, as the ones seen on multithreading environments.

Inside the library, you’ll find a small yet powerful example. Let’s take a look at it:

The example’s goal is to deny access to a complete folder tree (My Documents) and hide any executable file from the dialog. Two kernel’s functions will be intercepted:

fnc_desc2

For our first task, we hook FindFirstFileW. From here we block any access attempt to our folder or any child in it.

fnc_ff

This hook is handled before the actual call is made. So, when we set the last error to access denied and ask our hook to skip the call, the kernel function is never reached, and the caller is prevented from enumerating it. Also, we are returning an invalid handle, as defined by the documentation.

To hide executable extensions from the user, we will hook FindNextFileW. A program call this function to navigate files in a folder. What we do here is intercept calls just before they return to the caller. There we see if the file found is of any interest to us.

fnc_fn

As shown, if we need to skip this call, we simply call the function again. This way, the result goes unknown from the caller. To cleanly return the next item, we make sure that the return value and last error get to the caller.

Please remember that this an open source project. Feel free to add any changes you see fit. We’ll keep on using it on our products, so don’t hesitate in sending us any bug report of feature request. We’ll try our best to add them.

Now go download the library and try it your self ;) . Or take a mayor step and get Deviare.

Using our API hooker SpyStudio I wrote a script to intercept http requests done using wininet.dll API coming from a specific module of a process. The script keeps request information (server and url) to display in next calls and let filter requests to a specific server. Its name is httpReport.py and can found in SpyStudio v1.0.1 distribution.

httpReport navigates the stack in each call to wininet.dll functions to see what module called the hooked function, filtering all modules except the specified. This feature and server name filtering, allow a fine interception.

To use the script keep only one instance of iexplore.exe (the script will only hook the first instance if there are more than one) and type these lines in SpyStudio python console:

import httpReport
httpReport.startIe(‘toolbarqueries’, ['googletoolbar2.dll'])

The script will display queries done to a server that contains the string ‘toolbarqueries’ coming from module ‘googletoolbar2.dll’.

For example, if TechCrunch page is inserted in the address bar we get a wininet.dll!InternetConnectA call to ‘toolbarqueries.google.co.uk’ server and then a GET request to this url:

/search?client=navclient-auto&googleip=O;64.233.169.147;266&iqrn=ZjbD&orig=0PnmJ&ie=UTF-8&oe=UTF-8&features=Rank:&q=info:http%3a%2f%2fwww%2etechcrunch%2ecom%2f&ch=751153802320

There are some parameters that need more research to be understood but there are some others we can tell something:

googleip: indicates Google server used for the query

ie: iexplore encoding?

oe: maybe Outlook Express encoding?, only a bad guess

features: what we are asking to the server (here ‘Rank’)

q: encoded url (http%3a%2f%2fwww%2etechcrunch%2ecom%2f = http://www.techcrunch.com/)

ch: it looks as a function to the url to prevent other client to do the same requests

Then, wininet.dll!InternetReadFile return the http response (to see it enable the option ‘Show Params on Return’ in Preferences):

‘Rank_1:1:8n’

that indicates that the page visiting has PageRank 8.

This process is repeated for every page you visit so Google can collect all the pages browsed by all the users using GoogleToolbar. That’s why it may be considered as a spyware.

Google Treasure Hunt puzzles are too easy?

May 23rd, 2008 | Posted by Pablo Yabo in Java | opinion | PHP | programming - (0 Comments)

Seems that the Google guys are getting softy. The last two questions of the Google Treasure Hunt 2008 were easily solved.

The Question #1 is about paths. We have a robot that can move down or right, in a n x m grid. So how many possible paths exists, from the top left to the top right?

It gets solved just searching in Google for “grid path right down” from there you will get the equation that you must run on any language that has Big Integer implementations, since involves the calculations factorial.

Example of our solution for the first puzzle in Java:

BigInteger dividend = factorial( (rows-1)+(columns-1) );
BigInteger divisor = factorial(rows-1).multiply(factorial(columns -1));
System.out.println(dividend.divide(divisor));

The Question #2 seems to be even easier. It involves to transverse a directory tree, filtering the files that verifies 2 conditions based on the path string and the extension string (like .txt or .xml). Then reading some specific line. All files are text files this simplifies then things even more. Nothing hard to any programmer.

Snippet of our solution for the second puzzle in PHP:

// Setting where's the Google Treasure Hunt Directory
$dirbase = 'GoogleTreasureHunt08_11336769377172459175';

// Creating and loading the directory Tree
$tree = new Mytree($dirbase);
$tree->load();

// Getting the leaf Files
$leafs = $tree->get_leafs();

// Filtering to files that satisfies the conditions
$cond1 = array_filter ($leafs, filter_bycond1);
$cond2 = array_filter ($leafs, filter_bycond2);

// Doing the sums at the right line number
$sum1 = array_reduce($cond1, create_function('$v, $node',
             '$v = ($v == null) ? 0 : $v;'.
             '$v += (int)read_line($node->data, 5);'.
            'return $v;'));
$sum2 = array_reduce($cond2, create_function('$v, $node',
            '$v = ($v == null) ? 0 : $v;'.
            '$v += (int)read_line($node->data, 5);'.
            'return $v;'));

echo $sum1, '<br>';
echo $sum2, '<br>';

// Obtaining result
echo $sum1 * $sum2;

So as you see, there’s no complication at all. I would expect some challenge when Google uses the “Puzzle” word. Maybe they aren’t what they were? I don’t know, but I will be expecting some real challenge to solve :) .

Robot solution:  GTH Q1 Java solution

File transeversing solutino: GTH Q2 PHP solution

It is hard to find on the internet a detailed and complete solution for modifying the contextual menu due to several reasons.

One of these reasons is that many of the implementations found use the System.Windows.Forms.ContextMenu; you can see one of them here:

Component-Based Development with Visual C#

In these kinds of examples the system menu is not invoked from the ShowContextMenu, instead a user customized menu is. This menu does not allow modifying it as we need.

Another reason is due to the programming language. In the MSDN website a C++ implementation of the ShowContextMenu can be found:

WebBrowser Customization (Part 2)

The problem is that when we want to implement it in C# difficulties such as not being able to call system functions, use the same data types, and many others arise.

Maybe the biggest difficulty can be found when trying to marshall the CComVariant class. A huge variety of solutions can be found on the internet, but they usually do not work (at least in the case mentioned above). Here are some examples of them:

VB Variant Equivalent in C#

Object To Variant

What is the equivalent of Variant data type in C#.NET?

Using the int[] type with size 3 or bigger is one of the ways of solving this.

   1:  int[] variantVar = new int[3];

The VARIANT type can be seen in this MSDN webpage:

VARIANT and VARIANTARG

Once we solved this problem, we can use the IOleCommandTarget function Exec:

   1:  [PreserveSig]
   2:  int Exec(
   3:      ref Guid pguidCmdGroup,
   4:      int nCmdID,
   5:      int nCmdExecOpt,
   6:      // we need to have this an array because callers 
   7:      // need to be able to specify NULL or VT_NULL
   8:      [In, MarshalAs(UnmanagedType.LPArray)] int[] pvaIn,
   9:      [Out, MarshalAs(UnmanagedType.LPArray)] int[] pvaOut
  10:      );

When calling Exec for the first time, we get the handle for the language submenu. We obtain it in variantVar variable:

   1:  int[] nullVariantVar = null;
   2:  int[] variantVar = new int[3];
   3:   
   4:  spCT.Exec(
   5:              ref CGID_ShellDocView,
   6:              SHDVID_GETMIMECSETMENU,
   7:              0,
   8:              nullVariantVar,
   9:              variantVar
  10:              );

Now we must parse variantVar in order to get the result (the handle for the language submenu). The first value that we get is a VARTYPE type, which indicates the kind of variable that we will find next. Then there is a reserved spot of three WORD long, followed by the value we are looking for. So the handle for the submenu is on the second place of the array:

   1:  IntPtr handleSubMenu = new IntPtr(variantVar[2]);

We can replace passing the CComVariant argument to the function by creating a new variable shown in the code below and then call again Exec:

   1:  variantVarIn[0] = VT_INT_PTR;
   2:  // Remember that variantVarIn[1] is reserved
   3:  variantVarIn[2] = handleMenu.ToInt32();
   4:   
   5:  variantVarOut[0] = VT_I4;
   6:  // Remember that variantVarOut[1] is reserved
   7:  variantVarOut[2] = dwID;
   8:   
   9:  // Insert Shortcut Menu Extensions from registry.
  10:  spCT.Exec(
  11:              ref CGID_ShellDocView,
  12:              SHDVID_ADDMENUEXTENSIONS,
  13:              0,
  14:              variantVarIn,
  15:              variantVarOut
  16:              );

We obtain the complete context menu as a result of the instructions shown above. This menu can be modified as much as we desire. Using this, you can add or remove menu items and also their functionality. For example you can call methods implemented in your project from the desired menu item.

Now you can build a customized browser using C# !

Custom Outlook Development

We have a team of experts developing plug-ins for Outlook. We can go beyond Outlook API and develop modifications to those functions that lacks of some features that your product may need. Our team leaders are experts running projects and our customers can feel confident that their product will be released in time. Our sales team can be contacted any time in our office in California  (310) 237-6506.
For more information visit Outlook plugin development

outlook express plugin windows live mail plugin windows live mail api application virtualization microsoft app-v shim outlook plugin development outlook development audio recorder capture sdk skype g-talk msn messenger IDirectSound / IAudioClient / MCI Wave API / Direct buffer writes capture recorder sdk apple mail plugin
windows system internals API Hook api intercept api hook api monitor api spy windows7 migration Track dll error Track COM error Ajax web scraping javascript web scraping Internet Explorer Knowledge Base