The Code Cave

March 24, 2006

HELP!!! Retrieving the handle of the DLL’s owner -HOW?

Filed under: Tips, Techniques and Technologies — Brian @ 8:49 am

I have written a DLL, It needs to access a control in the instance of the application that loaded it. So, I want to get the handle of the application that is currently using that DLL. Or said a different way, the handle of the application that has loaded that instance of the dll. Anyone know how to do this? Solutions in any (major) programming language are acceptible. I should be able to readily translate them to Delphi…

I am building an Maxthon plug-in that adds the missing search buttons from the Google tool bar (search site, search news groups, search images). It is easy enough to search through all windows and get the handle of the maxthon window and then find the value you’ve put in the Maxthon search box. But I want to be certain that I get the right value. I could give myself a unique GUID, search all parent windows till I find that unique GUID and then know that that parent window is my host, however, that seems a pain….

Any thoughts?

March 23, 2006

The Best Pinger/Update Services List for WordPress 2.02

Filed under: WordPress — Brian @ 5:34 pm

After some fairly exaustive research and testing, I have come up with the following combined pinger list for WordPress. This took four or five other lists and eliminated duplicates and slow responders (from the US). Many lists contain entries that are already available through Ping-o-matic which goes out and pings the pingers. At the time of this post, this list will not produce any duplicates and will allow WordPress to complete its post before the standard browser will time out. This WILL increase the time it takes to post, however you do not need to wait for the browser to refresh itself. You can usually move on to do other things after the first second or two. At that point the post has been made to the DB and WordPress is off notifying the pingers and will continue that until it is done.

Here is the list of Update Services I use at my blogs:

http://rpc.pingomatic.com
http://1470.net/api/ping
http://bblog.com/ping.php
http://bulkfeeds.net/rpc
http://coreblog.org/ping/
http://xmlrpc.blogg.de

Put these in the “Update Services” field on the Options>Writing tab in your WordPress administrator control panel.

Loading/Unloading a registry hive programmatically in Delphi 5+

Filed under: Delphi — Brian @ 5:25 pm

Concepts demonstrated:
Registry Use (See procedure TfrmLoadHive.btnDisplayValueClick(Sender: TObject))
Hives & The Default User hive & .Default (See below)
Executing another program from within a Delphi program (See procedure TfrmLoadHive.btnExecRegEditClick)
Use of Process Token Privileges in Delphi (See below)

RE: Hives
The WinXP registry is divided into many different sections. Each major section is called a hive. Handling complete branches of the registry as separate hives allows Microsoft to perform several neat tricks. First of all, it allows hive to appear in several places in the registry with different names. The most obvious example of this is HKey_Current_User which of course points to the hive of the user that has logged in. A lesser known example is HKEY_CLASSES_ROOT which is simply a reloaded version of KEY_LOCAL_MACHINE\SOFTWARE\Classes. Those familiar with the DOS subst command and Linux symbolic links can draw comparisons there too.

An even lesser known use of windows hives is that Windows does not keep all of its hives active. It has separate hives to use as examples for creating local users, and other for creating user accounts when someone has logged into the machine remotely through a domain. I seem to remember there being a couple more examples but they elude me at the moment. Those hives are stored as DAT files on the hard drive. For instance, in the default XP install, the registry hive stored at ‘c:\\Documents and Settings\\Default User\\NTUSER.DAT’ will be used to set all the default registry entries whenever a new user logs into the machine. Set a value in that hive, and all future users will have that value.

NOTE: Do not confuse this with HKEY_USERS\.DEFAULT. The HKEY_USERS\.DEFAULT hive stores the values used when no one is logged in. “Huh? How could that be useful?” Well, if you think about it, controlling whether or not a computer puts itself to sleep if some one has booted it but not logged in can be very important. It might also be nice to set a screensaver that works when you log out of your computer but leave it turned on. An ultra secure person could set the color scheme to be entirely black on black, then only a person that really knows what they are doing could log into the computer - LOL. In any case, .DEFAULT and the Default User hives are NOT the same thing.

RE: Token Privileges:
Windows XP/NT/2000 and newer operating systems have advanced security methods to restrict what programs can and cannot do. These restrictions also allow the logging of some restricted access functions. So, for example, while it is possible for programs to set the system time, just any old program can’t do it.

The program has to ask for and get permission to update the time, before it can be accomplished. It is a bit like what a bell hop must do to get into someone’s hotel room. If a bell hop needs to get into room 5321 (let’s pretend this hotel uses keys and not plastic cards), the bell hop will tell his manager he’s gonna need to get into a room, look up which key that room needs, ask the manager for that key, unlock the room and do his thing. Then of course he will lock the door as soon as he is done. Note that if the bell hop does a bunch of other things before locking the door, the room could be burglarized. And when a good bell hop has to access the room several times, the room will be locked between times he is accessing it.

The process for Windows is the same:
Tell Windows you will be adjusting privileges by calling: OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, TTokenHd);
Find the local name of the privilege you will be adjusting by calling LookupPrivilegeValue
Grant yourself access by setting TTokenPvg.Privileges[0].Attributes to SE_PRIVILEGE_ENABLED
Lock the door again by setting TTokenPvg.Privileges[0].Attributes to SE_PRIVILEGE_DISABLED

In my program, I have created three helper routines for working with the tokens: SetTokenPrivilege, GrantPrivilege and RevokePrivilege. The latter two only serve to make my calling code clear. Readability is essential for any professional grade program. At some point you will forget the details of every single program you’ve write. So, even if you are only writing a routine for your own use, you should do what you can to make it easier to read. Tasks like this may seem wasted on throw away programs, but the more you do it, the faster you will be and the more likely it will be that your habit of writing good code will pay off in the end.

Here are my Delphi privilege routines:

DELPHI:
  1. {******************************************************************************
  2.   SetTokenPrivilege
  3.   A helper function that enables or disables specific privileges on the
  4.   specified computer.  A NIL in SystemName means the privilege will be granted
  5.   for the current computer.  Any other value must match the name of a computer
  6.   on your network.
  7. ******************************************************************************}
  8. procedure SetTokenPrivilege(aSystemName: PChar; aPrivilegeName: PChar; aEnabled: Boolean);
  9. var
  10.   TTokenHd: THandle;
  11.   TTokenPvg: TTokenPrivileges;
  12.   cbtpPrevious: DWORD;
  13.   rTTokenPvg: TTokenPrivileges;
  14.   pcbtpPreviousRequired: DWORD;
  15.   TokenOpened, ValueFound: Boolean;
  16. begin // SetPrivilege
  17.   // The privilege system is only available on NT and beyond
  18.   if (Win32Platform = VER_PLATFORM_WIN32_NT)
  19.   then begin
  20.     // Retrieve the Token that represents this current application session
  21.     TokenOpened := OpenProcessToken(GetCurrentProcess(),
  22.                                     TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY,
  23.                                     TTokenHd);
  24.  
  25.     // Check for failure
  26.     if (not TokenOpened)
  27.     then raise Exception.Create(‘The current user does not have the access required to run this program.’)
  28.     else begin
  29.       // Get the name of the privilege (since Windows is multi-lingual, this must be done)
  30.       ValueFound := LookupPrivilegeValue(aSystemName, aPrivilegeName, TTokenPvg.Privileges[0].Luid) ;
  31.       TTokenPvg.PrivilegeCount := 1;
  32.  
  33.       // Enable or disable the flag according to the bool passed
  34.       if (aEnabled)
  35.       then TTokenPvg.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED
  36.       else TTokenPvg.Privileges[0].Attributes := SE_PRIVILEGE_DISABLED; // See note on local constant declaration
  37.       cbtpPrevious := SizeOf(rTTokenPvg) ;
  38.       pcbtpPreviousRequired := 0;
  39.       if (not ValueFound)
  40.       then raise Exception.Create(‘This program is incompatible with the operating system installed on this computer.’)
  41.       else begin
  42.         try
  43.           // Adjust the permissions as required.
  44.           Windows.AdjustTokenPrivileges(TTokenHd, False, TTokenPvg, cbtpPrevious,
  45.                                         rTTokenPvg, pcbtpPreviousRequired);
  46.         except
  47.           raise Exception.Create(‘The current user does not have the required access to load a registry hive.’)
  48.         end;
  49.       end;
  50.     end
  51.   end;
  52. end// SetPrivilege
  53. {******************************************************************************
  54.   GrantPrivilege
  55.   This routine grants the privilege(s) needed to access the hidden system hive
  56.   and load it into memory.
  57. ******************************************************************************}
  58. procedure TfrmLoadHive.GrantPrivilege(aPrivilegeName: String);
  59. begin // GrantPrivilege
  60.   SetTokenPrivilege(NIL, PChar(aPrivilegeName), TRUE);
  61. end// GrantPrivilege
  62.  
  63. {******************************************************************************
  64.   RevokePrivilege
  65.   This routine revokes privilege(s) given in GrantPrivilege
  66. ******************************************************************************}
  67. procedure TfrmLoadHive.RevokePrivilege(aPrivilegeName: String);
  68. begin // RevokePrivilege
  69.   SetTokenPrivilege(NIL, PChar(aPrivilegeName), FALSE);
  70. end// RevokePrivilege

In my case, I am using the SeRestorePrivilege token. This is actually one of the most powerful and lethal tokens. With it you are telling Windows that you are a Hard Drive backup program and you want to have access to all sorts of files that most programs are not allowed access to. Presumably you are doing this for good and not evil. Other tokens are:
SeCreateTokenPrivilege, SeAssignPrimaryTokenPrivilege, SeLockMemoryPrivilege, SeIncreaseQuotaPrivilege, SeUnsolicitedInputPrivilege, SeMachineAccountPrivilege, SeTcbPrivilege, SeSecurityPrivilege, SeTakeOwnershipPrivilege, SeLoadDriverPrivilege, SeSystemProfilePrivilege, SeSystemtimePrivilege, SeProfileSingleProcessPrivilege, SeIncreaseBasePriorityPrivilege, SeCreatePagefilePrivilege, SeCreatePermanentPrivilege, SeBackupPrivilege, SeRestorePrivilege, SeShutdownPrivilege, SeDebugPrivilege, SeAuditPrivilege, SeSystemEnvironmentPrivilege, SeChangeNotifyPrivilege, SeRemoteShutdownPrivilege, SeUndockPrivilege, SeSyncAgentPrivilege, SeEnableDelegationPrivilege, SeManageVolumePrivilege
So, that’s the basics. Take a look a the comments in the rest of the source code and you’ll soon see what happens and why.

Also try some different things. Run RegEdit and load the hive manually through File>Load Hive. Did you notice that you HAVE to be at a point within one of the preloaded hives before that option is enabled? What happens when you press the load hive button but you haven’t granted yourself privileges? What happens when you grant your self privileges and don’t revoke them b4 closing the program. Can you then load the hive when you rerun the program? What happens if you Grant 4 time but only unload once?

Experiment. But remember, you are playing with the registry and thar be monsters there. This app works fine on my system, I’ve used similar routine regularly for a couple years now, but I haven’t tested it with all versions of Windows and I have no idea how it will handle out-of-the-ordinary circumstances, like bad sectors in a dat file on your HD. Additionally, a Windows Service pack could totally change what this program does. So, in short, don’t come to me when you need to reinstall Windows. I’ll simply say it was a bad coincidence and anyway your system is beyond my control, you never should have run this program on it. I’m not responsible for your financial and emotional loss. You are responsible for making sure that source code you run on your computer does not have deliberate or accidental malicious behaviors.

http://www.TheCodeCave.com/downloads/delphi/LoadHiveDemo.exe
http://www.TheCodeCave.com/downloads/delphi/LoadHiveDemo.dpr
http://www.TheCodeCave.com/downloads/delphi/U_LoadHive.dfm
http://www.TheCodeCave.com/downloads/delphi/U_LoadHive.pas

Cool stuff to look at on Google Satelite view

Filed under: Things that catch my eye — Brian @ 1:41 pm

Have you ever explored the artic regions?

There’s some incredible stuff to see up there in satellite view, like icebergs the size of SW PA breaking off and flowing down stream…
http://maps.google.com/?ll=80.319658,-86.594238&spn=0.282656,2.287903&t=k

I had been looking at Greenland then I became fascinated with this huge river up in Russia

http://maps.google.com/?ll=80.319658,-86.594238&spn=0.282656,2.287903&t=k

This thing is absolute HUGE and look at the pockmarked land structure around that bay… it is just wild
http://maps.google.com/?t=k&ll=70.768146,78.308487&spn=0.13842,0.571976&t=k

And that river flows all the way back to/from this huge lake thousands of miles away - which has a really weird streak across it. http://maps.google.com/?t=k&ll=53.13359,108.676758&spn=2.017007,4.575806&t=k

It must be something on the satellite’s lens… You can see it’s fabric….
http://maps.google.com/?t=k&ll=53.91814,108.683195&spn=0.02674,0.043516

Even so, I am considering submitting a story to Weekly World News about how the Russians have a massive program to create a band-aid to patch the hole in the ozone… I think it would fly don’t you?

March 22, 2006

A batch file to find the first matching file in the search path…

Filed under: Batch — Brian @ 12:49 am

This is another small app I wrote for someone to use at the ZTree forum.

This one is a DOS batch file that finds files in your search path that match the criteria you pass to it.
For instance you could type “SearchPath WPFile.Doc” and it would return the location of that file in your search path. If you type in simply “SearchPath MyApp” it will do a search for all executible files as defined by the PATHEXT environmental variable.

I found this program extremely useful since when clicking Start>Run and entering NO (it was supposed to autocomplete to notepad) ran a program that I could not find anywhere. SearchPath found it in a network directory.

Concepts Demonstrated:
Batch file subroutines - Use a CALL to execute a jump location in the same batch file as if it was a seperate batch
GOTO :EOF - Used to return out of a batch file OR batch Subroutine.
For Loops & Accessing to Environment variables
Child Recursion - A parent calls the child and the child in turn calls the parent which could in turn
child again.

DOS:
  1. :: *************************************************************************
  2. ::  SearchPath.Bat                                                                                            10/31/2005
  3. ::  Written by Brian Layman (AKA Capt. Queeg)
  4. ::  Visit him at http://www.TheCodeCave.com
  5. :
  6. ::  A batch written to display the program that would be run when
  7. ::  a filename is typed at the command prompt.  Just a demo for
  8. ::  Hartmut at http://www.ztw3.com/forum/forum.cgi
  9. :
  10. ::  Usage: SearchPath ProgramName[.EXT]
  11. :
  12. ::  History:
  13. ::     10/31/2005 - BL - Created
  14. ::     11/01/2005 - BL - Removed Temp File Usage
  15. :
  16. :: *************************************************************************
  17. @echo Off
  18. :: All this is boiled down to one subroutine that sets a variable of the
  19. :: same name.
  20. call :SearchedFilePath %1
  21.  
  22. :: If no program is found, say so.
  23. if "%SearchedFilePath%"=="" echo There is no matching program in the search path
  24.  
  25. :: If a program was found, echo its name.
  26. if NOT "%SearchedFilePath%"=="" echo %SearchedFilePath%
  27.  
  28. :: Clear out our temp variable
  29. set SearchedFilePath=
  30.  
  31. :: Quit
  32. GOTO :EOF
  33. :: *************************************************************************
  34.  
  35.  
  36. :: *************************************************************************
  37. ::  Support procedures
  38. ::
  39. ::  These routines are called with a CALL directive and the GOTO :EOF
  40. ::  terminates that CALL but does not terminate the entire running of the
  41. ::  batch file.
  42. :: *************************************************************************
  43.  
  44. :: *************************************************************************
  45. :SearchedFilePath
  46. ::  Returns the full path to a passed file in the searchpath
  47. ::
  48. ::  Returns blank if not found.
  49. ::
  50. :: *************************************************************************
  51. : set SearchedFilePath
  52.   :: Set the default value to blank.
  53.   set SearchedFilePath=
  54.  
  55.   :: If there is no extension handle it
  56.   if "%~x1"=="" Call :SearchWithExtensions %1&GOTO :EOF
  57.  
  58.   :: There is no extension, is it blank?
  59.   if "%1"=="" GOTO :EOF
  60.  
  61.   :: So, we have an extension.  That means we can do a simple search.
  62.   :: %~dp$PATH:1 automatically searches the path for us.  It is a
  63.   :: variable set by the Call command.
  64.   set  SearchedFilePath=%~dp$PATH:1%1
  65.   if "%SearchedFilePath%"=="%1" set SearchedFilePath=&GOTO :EOF
  66.   GOTO :EOF
  67. :: *************************************************************************
  68.  
  69. :: *************************************************************************
  70. :SearchWithExtensions
  71. ::  Iterates the extensions gathered from the PATHEXT environment
  72. ::  and searches until the file is found.
  73. ::
  74. ::  Returns blank if not found.
  75. ::
  76. :: *************************************************************************
  77.     :: Initialize a counter for looking at multiple search results in one line
  78.     set cnt=0
  79.  
  80.     :SearchLoop
  81.       :: Break out after 20  checks.
  82.       :: If you might have more than 20 extensions, increase this value.
  83.       :: If you could find out how many periods there are in the temp file,
  84.       :: you could optimize this.
  85.       if "%cnt%"=="20" GOTO :SearchLoopCleanup
  86.       set /A cnt=%cnt%+1
  87.       :: Continually search the single line file returning each sequential
  88.       :: search result and recursively pass it to the SearchedFilePath routine. 
  89.       :: When we ask for a token # that doesn’t exist and blank is returned,
  90.       :: abort out.
  91.       for /F "tokens=%cnt% delims=.;" %%C in ("%PATHEXT%") do call :SearchedFilePath %1.%%C
  92.       if "%SearchedFilePath%"== "" GOTO :SearchLoop
  93.    
  94.     :SearchLoopCleanup
  95.       :: Clear our Temp variable
  96.       set cnt=
  97.   GOTO :EOF
  98. :: *************************************************************************

A small app to gather specific lines from files

Filed under: Tips, Techniques and Technologies — Brian @ 12:24 am

Here’s a small app that I wrote to help out Pat Gilbert over on the ZTree support forums.

And I quote: http://www.ztw3.com/archive/020/archive.cgi?read=72807

> What I need to do is to “gather” the 3rd & 4th lines of text
> from a set of files and write them to a temporary file for further
> processing. Ideally I would like them appended to the temp file without
> additional LFCR at the end of each gather.

I sometimes give myself a 15 minute project to write on Monday mornings to clear my brain and get my mind into the right mode. I REALLY needed that this morning, so I threw this together. With testing, I exeeded my 15 minute time limit by 5 minutes, so you’ll need to figure out how to use it yourself, but here:
http://the-wildwest.com/Queeg/Batches/GatherLines.exe

Click the ChangeDirectory button to populate that edit box with the currend path.

Save to file will save a file called Gathered.txt to the current directory (which is probably where you are gathering lines from.).

It could be MUCH more efficient and if you are working with Largish files, it will be slow (for convenience I load the whole file), but like I said, I had 15 minutes.

Maybe it will help…

March 21, 2006

My Dear Friend…

Filed under: My Journal — Brian @ 2:42 pm


This is my friend Tom Moyer.

AKA Preacher

This is my friend Tom on Steel…










Any Questions?

Goodbye Google Image Search as we know it

Filed under: Google — Brian @ 10:55 am

The actual court injunction against Google

Well, there you have it… a preliminary injunction by a California judge against Google Inc., Amazon et. al. See the whole thing here.

You see there’s this soft porn company called Perfect 10. They even publish a magazine with the most perfect “natural” women in the world (no additives but plenty of preservatives). This magazine is, from what I hear, like getting the Sports Illustrated Swimsuit Edition, 12 months out of the year.

Well, really, it is just a tie-in to Perfect 10’s big business - their Pay-for-Porn services at Perfect10.com. They want you to goto their website for the full nude shots of their models. Plus they want to put naked girls on your cell phone. And that’s where the problem lies. While there are many more famous body parts, for Perfect 10 the most important it all comes down to the girl’s thumbs.

Google’s image search goes out and grabs pictures from all over the Internet UNLESS a website tells them not to. And some guys like to share pornographic pictures of “hot women” on their websites. When Google displays those pictures, they are displayed as small thumbnail size images - the perfect size for a cell phone screen. You can see where this is going… So, Perfect 10 is saying that Google is distributing copyrighted material in a form that will directly affect their market. And the judge agrees. I’m sorry to say that I agree too.

The facts in the case are not disputed.

  • Google does display copyrighted images - this is strictly speaking illegal.
  • Google does display versions of them modified to a thumbnail size - this is strictly speaking illegal.
  • This one is almost as important - Google is aiding in theft of services by discovering and propogating passwordz to porn sites.  So this is not JUST about images but Perfect 10 is also saying that google cannot display text results that might contain information that allows people into their site without paying for it. 

How do you fix that? How do you restrict text searches?  How do you tell if an image was once associated with a copyrighted site.  It’s a bit of a sticky wicket. Google indexes what’s on the web. That’s all it does. The funny thing is that the Judge didn’t know what to do about. He asked Google to come up with a solution to get him out of this hairy mess.

Eliminating all possible copyrighted material this goes fundamentally against the very nature of the search engine. Google was already pressing the boundary by indexing all copyrighted works in public libraries. This particular case strikes not at that blatent infringement, but at the core search that no one (few) had a problem with.

So, in the ever more dicey battle over intellectual property, where do search engines fall? Could this be the end of an all inclusive Google? I think the answer is: yes. Google - as we know it - is gone. There will be restrictions enforced on copyrighted material. Personally, I think Google will propose a standard involving placing copyright notices in the page, the .htaccess or more specifically the media itself. The latter is the only solution that works for images copied off site. Then any media that contains that copyright notice (which will become a standard addition to images produced on professional grade cameras) will not be indexed on Google. However, I think Perfect 10 will fight against that since it is more work for them and it is easily bypassed.

We’ll have to see. Will Girls, Girls, Girls be the downfall of that brief 21st century fluke: “The Search Engine”.

Free Microsoft Visual Studio 2005 Standard Edition

Filed under: Microsoft, Tips, Techniques and Technologies — Brian @ 9:34 am

or “How to get into the game development business cheaply” pt. 1.”

Microsoft does these promotions periodically. Microsoft isn’t REALLY into the individual developer compiler business anymore - that’s not where the cash is. They want to sell multiple enterprise copies to businesses and the more developers at those big companies that are already familiar with their products, the more easily the company will make a capital investment. Standard editions have become MS’s marketing & educational tools. So, they just give away them away after a little indoctrinization.

This site one way to get your own copy: www.learn2asp.net. Just listen to three presentations and they’ll mail you a copy of MS VS 2005 SE. You can sign in using a hot mail account and give them a “separate” mailing address.

Microsoft® Visual Studio® 2005 Standard Edition Includes:

  • Microsoft Visual Basic®,
  • Microsoft Visual C#®,
  • Visual C++®,
  • Microsoft Visual J#®
  • Tools for building Windows® and Web solutions
  • SmartPhone and Pocket PC development tools
  • Tools for visually designing databases, queries, and stored procedures

This is what the demos look like:
http://www.thecodecave.com/PHPvsASP.wmv

New Links

Filed under: Music, This Blog — Brian @ 12:01 am

I’ve finally had some time to add a few of the links I’ve been planning for my Links roll.

One of the neat things (well I think it’s neat) I wanted to do was add a group of music links.

I’ve found that you can browse the MSN music site and get Top Playlists for your favorite bands. Then you can grab the asx file from your cache and put it on your own website.

It’s all legit since it goes through MSN’s site for the music and displays all appropriate ads in the media player.

I think it’s kinda cool. I admit I kept on going further and further back into my eccentric music tastes to see if I could stump it. I could not find any “Mad at the World”, but I did find some other goodies like Barren Cross. And of course Steve Taylor. These are just some of the things I listen to on a daily basis. I need to throw in The Bobs too, since they are a regular.

« Older PostsNewer Posts »

Powered by WordPress