Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a "hook" and how can I write one in Java? And how to communicate with kernel to know the keys pressed by the user/registering with OS

Although I searched a lot, it is still unclear to me as to what exactly a "hook" is. For instance, I read this post on wiki answers :

A hook is a method of interposing a piece of code in front of another piece of code, so that the first piece of code executes before the second piece of code, giving the first piece of code an opportunity to monitor and/or filter the behavior of the second piece of code. An example might be a mouse hook, allowing the hook code to monitor the mouse while at the same time preserving the functionality of the original mouse event processing routine.

I also read this post, but I still don't understand what a "hook" exactly is. Can someone please explain, in layman terms, what is a "hook"? Why exactly do some write a "hook"? Also, is it possible to write a "hook" in Java?

Note:

I wanted to write a keylogger in java and one of my friend said that you will have to write a "hook" in C. Can't I write the whole keylogger in Java (to be operated on windows only)?

EDIT

please give an answer w.r.t keylogger. How can i ask kernel to give the information about the key pressed to my application using hooking ? Or how can i register my application with OS using JNI? I want my application to record keys pressed by the user.

like image 715
saplingPro Avatar asked Sep 02 '11 15:09

saplingPro


2 Answers

I would associate the word hook with at least two different concepts:

a) the Observer Pattern, where a Class lets you add a Listener that will be notified on certain events. You can find this all over Swing, the Servlet API and many 3rd party frameworks.

b) The Template Method pattern. An abstract class defines what methods are called in what order, and the implementing class may override these methods. Examples of this are not that common, but you see them every once in a while.

like image 126
Sean Patrick Floyd Avatar answered Sep 26 '22 22:09

Sean Patrick Floyd


From Hooking - Wikipedia,

In computer programming, the term hooking covers a range of techniques used to alter or augment the behavior of an operating system, of applications, or of other software components by intercepting function calls or messages or events passed between software components. Code that handles such intercepted function calls, events or messages is called a "hook".

A good example built into Java would be Runtime.addShutdownHook. A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently.

Runtime.addShutdownHook(new Thread(){
    @Override
    public void run(){
        // do something before application terminates
    }
});
like image 23
mre Avatar answered Sep 22 '22 22:09

mre