###########################################################################
###									###
###	Hagelslag							###
###	Design and implementation					###
###									###
###########################################################################


1 	Introduction

2 	Overview
2.1	Program Structure
2.2	Information Flow

3	Data Components
3.1	DataBase
3.2	DataBase Element
3.3	Buffer
3.4	Connection
3.5	Reference

4 	Program Components
4.1	Concepts
4.2	FileServer
4.3	Networker
4.4	GnutellaRouter
4.5	HostCatcher
4.6	SearchManager
4.7	Downloader
4.8	Monitor

5	Program Layers
5.1	Program Components
5.2	Backend
5.3	Commander
5.4	Hagelslag

Appendix A	F.A.M.E.

Appendix B	Word List

Appendix C	References



###########################################################################
###									###
###	Chapter 1							###
###	Introduction							###
###									###
###########################################################################


What's this ?
This document is a detailed describtion of all design and implementation
issues concerned with Hagelslag. This document applies to version 0.12
and 0.12.1.

Who should read it ?
Anyone who wants to, but of course it's intended for people wanting to
understand or change Hagelslag.

What's in here ?
Chapter 2, Design Overview, contains a description of the components and the 
way they are structured is the program, which forms the general design. It
also contains a description of the information flow through the program.
Chapter 3, Data Components, deals with various data types used in the
program that are used throughout the program. Not all data components are
described here, as most are rather straightforward.
Chapter 4, Program Components, contains a detailed description of each
component in the structure of the program. This descibtion includes design
decisions, used algoritms etc.
Chapter 5, Program Layers, describes what layers are in the program and what
they are doing.

What should you know before reading this ?
It'd probably help if you know how gnutella works, and it would probably
be easier to understand all about the internals of Hagelslag if you've
worked with the program a few times. It is also advisible to read the
User's Manual and the README file provided with Hagelslag.



###########################################################################
###									###
###	Chapter 2							###
###	Design Overview							###
###									###
###########################################################################


Whilst reading this Chapter, it may be useful to have a look at the two
images in the doc directory of Hagelslag, hagelslag-design.jpg and
hagelslag-classes.jpg.

#########################
# 2.1 Program structure #
#########################

Hagelslag uses different Program Components for different tasks. All 
functionality is offered by using different components to do certain tasks,
and then using another component to combine these tasks to provide the
desired services.

###
# 2.1.1 Program Components

The different Program Components are :
1) Networker
2) GnutellaRouter
3) FileServer
4) SearchManager
5) Downloader
6) HostCatcher
7) Monitor

All the Program Components have their own tasks :

The Networker deals with network connections and incoming connections. Data
is read from existing Gnutella network connection, data is send to them and
incoming connections of allmost all types are created here.

The GnutellaRouter makes routing decisions for incoming Gnutella Packets,
and offers the possibility to send a packet on a certain connection or to
broadcast it.

The FileServer, one of the most important parts of the system, does four
things. First, it maintains a database of locally shared files. Second, it
uploads shared files requested by other users. Third, and most important, it
composes answers to queries from other users. This is what determines the
performance of the program. Fourth, the Fileserver opens connections to
people that send push requests.

The SearchManager keeps track of the latest query started by the user and
all results that were found.

The Downloader downloads files and handles outstanding push-request to other
users.

The HostCatcher detects other people on the Gnutella Network and stores
hosts in the Hosts database.

The Monitor keeps track of queries from other people that pass through the
Gnutella Network.

A detailed description of the Program Components is given in Chapter 4.

###
# 2.1.2 Program Layers

There are several layers in Hagelslag. These layers offer an interface to
higher layers, thus hiding the complexity of the tasks in the layer itself.

The three layers are, from 'top' to 'bottom' :
- Hagelslag
- Commander
- Backend
- Program

The Program layer has all the Program Components in it.

The role of the Backend layer is to provide an interface to all tasks that
require the Program Components. In fact, the Backend offers a generic
interface to their functionality.

The Commander is the layer in which user input is parsed and appropriate
output is generated using information provided by the Backend.

Hagelslag is the top level layer, it communicates with the user (except
when compiled as ROUTER). It also polls the Backend which is nessicary to
let the program do its non-interactive business.

Further information about the program layers is in Chapter 5.

###
# 2.1.3 Data Components

Almost all Data Components are used in the Backend and the Program
Components. The only exception to the rule is the TransferStatus, which
hardly more than a copy of a Transfer.

It's not exactly true that Data Components do little more than holding 
information, by using inheritance and virtual functions several components
are actually interfaces implemented by other Data Components.

Further information in Chapter 3.

########################
# 2.2 Information flow #
########################

The discussion on flow of information through the program is limited to
information contained in Data Components in this section.
Most information is kept in its appropriate Program Component and travels
hardly anywhere out of it.

There are several cases where information is not kept in a single Program
Component.

###
# 2.2.1 Shared information

Two Database entities are so widely used throughout the program that they
could be considered as shared objects. These two are the Connections Database
and the Hosts Database. They are implemented as part of the Backend, but
used together or seperately in several Program Components.
The other shared object is the ControlCentre. All Program Components
requiring it have a pointer to the same ControlCentre.

###
# 2.2.2 Flow to higher layers

The only Data Component that is sent from the Backend to the Commander is
the TransferStatus. Nothing else comes higher than that.

###
# 2.2.3 Flow of Gnutella Packets

Gnutella Packets are read from the in-Buffer of the Gnutella Connections in
the Networker and passed to the Backend. The Backend processes them and, if
neccisary, passes them on to the Gnutella Router, which will add the
packet to the out-Buffer of the Gnutella Connections that it should be
sent to. The Networker also lets all Gnutella Connections send their
out-Buffer onto the network.

###
# 2.3.4 Simple flows

The Backend passed Gnutella Packets of the SEARCH type to the FileServer
and the Monitor.
The FileServer generates Gnutella Packets of the SEARCH-RESPONSE type and
passes them on to the Backend, which takes care of further processing.
The Backend passes Gnutella Packets of the SEARCH-RESPONSE type and the
INIT-RESPONSE type to the HostCatcher.



###########################################################################
###									###
###	Chapter 3							###
###	Data Components							###
###									###
###########################################################################


There are two kinds of Data Components in use : one to store information in,
and one which forms generalisations of the other. The latter are
superclasses and often contain virtual methods. The class 'tree' is in the
doc directory of Hagelslag, it is called hagelslag-classes.jpg.

Most of the Data Components also implement some functionality, but by far
not as much as the Program Components.


################
# 3.1 DataBase #
################

The Database Class is a special Data Component. It doesn't really store
information directly, it stores Data Components. All those Data Components
must be subclasses of DBElement, discussed further in this document.

The Database Component is implemented as Class DB.

###
# 3.1.1 Functionality

The Database Component is implemented in a certain way to offer certain
functionality. It's characteristics are :

1) Size is selected at allocation time.
2) Only a maximum number of elements can be contained in the Database.
3) When an element is added to a full Database, the oldest object in the
	Database is discarded.
4) No object that equals another object already in the Database can be stored
	in the Database.
5) An object can be marked as 'youngest' thus becoming the last to be trown
	out.
6) Objects are added in the lowest possible index.
7) Only subclasses of DBElement can be stored in the Database.

###
# 3.1.2 Data Organisation

Several constructions are used to organise data in the DataBase. These are :
- Array / Index
- Age list
- HashArray / Tree

First, Array / Index is, of course, simply an array which contains all the
elements. Each element is aware of its own index.

The age list is a linked list in which all elements are placed at the
'youngest' end when they are inserted. To identify older and younger elements,
indices are used in stead of pointers. A method 'touch' is provided to
place an element at the 'yougest' place. This makes it possible to use a
Database with LRU removal properties.

The HashArray is is one array of specified size. Objects are hashed to
compute an index. They are stored in a binary tree under this index in the
hash array.

Structure (younger / older couplings left out for simplification):
The numbers indicate indices in the arrays.
The lines are pointers.
The letters symbolize DBElements (or subclasses thereof)

hash Array	| 0| 1| 2| 3| 4| 5| 6| 7| 8| 9|10|11|12|
			|	       |
		       (A)	      (B)
Tree		      / | \	     / \
		     /  |  \	    /  	\
		   (C)  |  (D)     (E)	 \
		   /	\  /	    |	  \
		  |	 \/	    \	   \
		 /	 /\	     |	    \
		|	 | \	     |	     \
Array	| 0| 1| 2| 3| 4| 5| 6| 7| 8| 9|10|11|12|13|14|15|16|17|18|



###
# 3.1.3 Performance of operations

I've had some comment from Joris that using a combination of hashing and
biinary trees is overly complex and bad for performance. The reasons I used
them anyway are :
- A tree is a way of handling overflow at a entry in the hash array.
- Using this construction one can vastly overload the hash space and still
  have acceptable perfomance when looking up elements
- Delete operations may be expensive but optimize the tree because it has to
  be rebuilt anyway.

This construction performs best when most operations are lookups and every now
and then a delete operation that balances the tree.



########################
# 3.2 Database Element #
########################

The Database Element class is a superclass of all thing that can be stored
in a Database and it implemented in DBElement. It contains all nessicary
methods and data.

The data contained are it's own index in the array, the index of it's parent
in the tree, it's left and right subtree, and the indices of the elements
older and younger than itself.

The method 'hashValue' is used to compute its hashvalue. The methods
'lessThan', 'greaterThan' and 'equals' are used in the binary tree of the
Database.


##############
# 3.3 Buffer #
##############

A Buffer is nothing more than a piece of memory of a specified size that can
be used as, surprise, a buffer. Methods are provided to read input from file
desciptors, sockets and files, as wel as to send or write to files, sockets or
file descriptors. This integration reduces overhead as it prevents the
program from having to copy data out of the Buffer and send/writing the
copy.


##################
# 3.4 Connection #
##################

The Connection is a sub class of DBElement, it serves as superclass of all
types of connections in Hagelslag.

###
# 3.4.1 Subclasses

The subclasses of Connection are Transfer and GnutellaConnection. Both
Upload and Download are subclasses of Transfer.

###
# 3.4.2 Type and Status

Each Connection has a type with which it can be identified. More important,
each Connection has a status field. This allows Program Components to use a
scheme in which they have a method which handles all known Connections
based on their status.

###
# 3.4.3 Buffering

Every Connection has an in- and an outBuffer. These are used to send data
reliably. Connections will change status if a Buffer operation return -1.

###
# 3.4.4 Connection scheme

Connections contain a 'tryToConnect' method which will attempt to
establish a connection. This scheme has a timeout construction.


#################
# 3.5 Reference #
#################

Here follows a list of all Data Components, for reference :

DB:
The DataBase structure. Used to store data.

DBElement:
Base class of everything that is stored in a DB.

GnutellaPacket:
One packet in a Gnutella Network.

Packet:
A subclass of GnutellaPacket which contains useful functions to
buildt GnutelaPackets.

File:
Data of one file shared by Hagelslag.

Host:
One Host on the Gnutella Network.

PushRequest:
Contains information on what file we should push to whom.

Mesg:
The signature of a GnutellaPacket. Used to make routing decisions.

SearchResult:
One result to a search request from us. One SearchResult holds data on only
one file, so one response takes possibly several SearchResults.

Connection:
The base class of types of connections. Contains two 'Buffer's, one ingoing,
one outgoing.

GnutellaConnection:
One GnutellaNetwork connection.

Transfer:
Base class of Upload and Download.

Download:
One download.

Upload:
One upload.

ControlCentre:
There is just one ControlCentre in Hagelslag, lot's of things have a
pointer to it. It contains all global variables which are used to do thing
flexible.

Path:
One shared path.

Buffer:
A buffer structure used in Connection to provide robust data transfer.

Query:
One thing that someone requested for.

TransferStatus:
Almost similar to Transfer, contains data from a Transfer object ready to be
transformed into data for the user by Commander.

LocalResult:
Something the FServer uses when processing an external search request.

Socket:
A network socket. This is a separate class to allow the interface to be
implemented under different systems.


###########################################################################
###									###
###	Chapter 4							###
###	Program Components						###
###									###
###########################################################################



################
# 4.1 Concepts #
################

There are some generic concepts that are used in various parts of
hagelslag. Since they don't really belong with any of the Program
Components, they are discussed here.

###
# 4.1.1 Handle by State

This scheme is used for management of Connections. It is used in the
Backend for GnutellaConnections, Uploads in FileServer and Downloads in
Downloader.

Each Connection is requested from the DataBase, one by one. Each Connection
is handles according their state.

in pseudo-code :

	int		i;
	Connection	*c;

	for (i = 0; i < database->getSize(); ++i)
		if ((c = (subclass-type *)database->findElement(i)))
			switch(c->getState())
			{
				case this	:	doSomething();
							setState(next);
							break;
				case that	:	doNextState();
							setState(last);
							break;
				default		:	doOops();
							break;

			}

###
# 4.1.2 Polling

Program Components that need to do things on a regular basis, have a
method to 'poll' the Program Component. These polling methods return 0 if
nothing was done, and 1 otherwise. The idea behind this is that if nothing
was done, hagelslag should sleep for a while to reduce CPU load.


##################
# 4.2 FileServer #
##################

The most interesting part of the program is the FileServer. The reason that
this part is so interesting is that it's performance is of critical
importance to the performance of the system. It is the FileServers tasks to
handle the queries of other people. Besides that, it is also concerned with
managing outgoing Uploads (push requests) and Uploads them selves. These
latter tasks are not too complex. The true challenge lies in handling
several thousend queries per second, with a large collection of shared
files. This is the most advanced part of Hagelslag. People with love of
beautiful algoritms won't find anything better in this document.

###
# 4.1.1 Outgoing pushes

Every now and then, people issue a push request that must be dealt
with. the FileServer attempts to open a connection to such a host, then
adds the opened Connection to the Uploads Database.

###
# 4.1.2 Uploads

Uploads are dealt with in a scheme that is also used in the Downloader and
the Backend, the Handle / State scheme. The FileServer has a superclass
HTTPServer. This is an abstraction layer that allows one to use any
implementation for this task.

###
# 4.1.3 Search Algoritm

The search algoritm is discussed in various stages. First, the basic idea
will be discussed. Next, the implementation will be discussed. At last,
some enhancements will be discussed. At last, an overview of the entire
system is presented.

###
# 4.1.3.1 Query Analyses

Our first step is standardizing queries. In this case, only letters and
numbers may be used. Queries are case-insensitive. Therefore, all
letters are converted to uppercase. The members of this set are from now
on calles validChars. They are listed here below.

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9

People tend to use combinations of patterns (such as "britney +mp3"), and
characters that we do not allow. A standard form for queries is used to
deal with this.

Syntaxis :
Queries may only consist of one or more substrings, separated by one space
character (' '). The substrings of a Query must be ordered (with
strcmp). No spaces may occur as a first or last character, Queries may not
be empty.

Semantics:
A Query is a list of substrings, of which it is given that all responses
must contain ALL the substrings (logical AND).

Correct examples :

"BRITNEY MP3"
"IRON"

###
# 4.1.3.2 Searching

Let's have a look at the general principle behind searching. This
algorithm has been developed by Edward Akerboom (See Appendix C).

###
# 4.1.3.2.1 Preparation

First, all shared files are numbered. We will call these numbers fileNr
from now on.
Second, an array is constructed with combinations of validChars. It starts
with combinations of one validChar, then two and finally three. This array
is called the searchArray.

the searchArray (corresponding patterns above):

  A   B   ......   AA   AB   AC   ......    AAA    AAB   ......    ZZZ
| 0 | 1 | ...... | 37 | 38 | 39 | ...... | 1369 | 1370 | ...... | 50653 |

Each file is proccesed now. This means that all possible combinations of
validChars in the filename are found. The fileNr of the file is added to a
list at the apropriate index of the searchArray.

Thus, given a file with fileNr 10 and name AAC, the searchArray looks like
this :

  A   B   C   ...  AA   AB   AC   ...    AAA    AAB    AAC    ...    999
| 0 | 1 | 2 | ... | 37 | 38 | 39 | ... | 1369 | 1370 | 1371 | ... | 50653 |
  |	  |	    |	      |				|
+----+	+----+    +----+   +----+		     +----+
| 10 |	| 10 |    | 10 |   | 10 |		     | 10 |
+----+	+----+    +----+   +----+		     +----+

###
# 4.1.3.2.1 One Search

First, the query string is created. Then, all combinations of 3
validChars in the query are generated. We start with assuming that we have
a list which contains the fileNr's of the files we're looking for. This is
our result list. For each combination of validChars in the query, the
appropriate list of fileNrs is fetched. The first list fetched is our
initial result list. Each time a new list is fetched, it is AND-ed with the
results list. The process is repeated with all combinations of
2 and 1 validChars. When that is done, we have our final result list.

Example :

Suppose we have the searchArray in the state as mentioned above.
A possible Query might be : "A C". This consists of two substrings, each
having only 1 combination of 1 validChar.

First, the list under 'A' is fetched. This is our initial result 
list. Then, the list under 'C' is fetched. It is AND-ed with the result
list. fileNr 10 is in both lists, so it will be in the final result
list. Conclusion : the file with fileNr 10 has both 'A' and 'C' in its
name.

Example 2 :

Suppose we have the searchArray in the state as mentioned above.
A possible Query might be : "A B". This consists of two substrings, each
having only 1 combination of 1 validChar.

First, the list under 'A' is fetched. This is our initial result
list. Then, the list under 'B' is fetched, which is an empty list. It is
AND-ed with the result list, thus the result list is empty. Conclusion :
there is no file with an 'A' and a 'B' in its name.

Each of the files that are found with this algorithm have to be checked,
to test whether all complete substrings are completely present in the file
name. The generation of the list can be done MUCH faster than comparing each
file to each substring, thus leading to a significant performance
improvement.


###
# 4.1.3.3 Implementation

In the implementation, the searchArray holds pointers to unsigned ints. A
NULL pointer indicates an empty list. Otherwise, the pointers points to an
array of unsigned ints. This array is one big bitmask. That is, if fileNr 6
is in the list, that means that bit nr 6 is set to 1. All others are, of
course, set to zero.

This approach makes it possible to AND the lists extremely fast. Using
binary AND's, 32 bits can be ANDed in only one CPU cyle.

in pseudo-code :

	int	i;

	for (i = 0; i < intsInList; ++i)
		result[i] 	&= currentList[i];

	return result;


###
# 4.1.3.4 Improvements

Some improvements have been done to the original algorithm. Besides the use
of bitmasks in the implementation, three other improvements have been 
considered. Two of these are actually used in Hagelslag.

###
# 4.1.3.4.1 Hashing Substrings

In the searchArray, only combinations of 1, 2 and 3 validChars are used. Using
combinations of 4 and more validChars would have resulted in faster
operation, because a combination of 4 validChars is more rare than
combinations of 3 validChars.

This is easy to understand when a query "ABC" is sought. It is faster to
process the "ABC" entry in the searchArray than to find the "A", the "B",
binary 'AND' the lists, fetch the "C" entry, and binary 'AND' the list
again. This latter process would even have found files containing "BAC", 
"CAB" etc. Therefore, searching is faster is longer patterns are used.

The problem is, that combination of 1 validChar require 37 entries in the
searchArray. Combinations of 1 and 2 validChars require 37 + 37^2 = 1406
entries. Combinations of 3 validChars require 37 + 37^2 + 37^3 = 52059
entries. This is still acceptable, but using combinations of more
validchars would require 37^4 more entries, which is not feasable.

To still try to benefit from the speedup that would be gained from using
combinations of more than 3 validChars, an array is created that is
similar to the searchArray. It is called the hashArray. 

In the searchArray, combinations of validChars are mapped directly to an
index. In the hashArray each substring with a length of at least 4
validChars is hashed to produce an index in the hashArray.

Example:
The file "AAABB CCCD" has fileNr 11.

When we add this file to the hashArray, we compute 'index =
hash(AAABB);' and add fileNr 11 to the list at 'index'. Next, we compute
'index = hash(CCCD);' and add fileNr 11 to the list at 'index'.

Whenever a query asks for all file containing "CCCD", this combination is
hashed to produce 'index = hash(CCCD);'. The list under this index will
contain fileNr 11.

This addition to the search algorithm is used in Hagelslag, this step is
taken before searching using the searchArray.

###
# 4.1.3.4.2 Cache

A cache is a common construction for performance improvements, and it is
used here as well.

The cache is a Database object containing CacheEntries. A CacheEntry is a
class containing a tuple of a query and a pointer to Packet.

The reason that the substrings of a query must be ordered is that
otherwise the cache would not see that "BRITNEY MP3" and 
"MP3 BRITNEY" are really identical when it comes to finding
results. Comparison of queries is now easy.

When a query returns an empty result list, the pointer to Packet in the
corresponding CacheEntry will be NULL.

Each time a query is found in the cache, the corresponding CacheEntry is
'touched' in the cache. This means that it is placed at the 'youngest'
position in the Database. Since the oldest element is discarded when the
cache is full and a new element is added, this cache is a LRU cache.

When a query is not found in the cache, the normal search algorithm
starts, first processing the hashArray and then th searchArray. The query
and its result form a new CacheEntry that is stored in the cache.

###
# 4.1.3.4.3 Prime Products

In theory, it is possible to map a different prime number to each index in
the searchArray. After adding all fileNrs in lists at the appropiate
indices, we would have some list this :


Primes:		   2    3    5    7   11   13   
Combinations:	   A    B    C    D    E    F
Index in Array:	|  0 |  1 |  2 |  3 |  4 |  5 | 
		   |	     |	  |    |
Lists:		 +---+	   +---+  |   +---+
		 | 0 |	   | 0 |  |   | 0 |
		 +---+	   +---+  |   +---+
		   |	  	  |
		 +---+		+---+
		 | 2 |  	| 2 |
		 +---+  	+---+

Now, we create a new array, called the primeArray. In this array, we use 
the fileNr of a file as index. We place the product of all prime numbers
where the fileNr is listed and store that in the primeArray. In the
example above here, we would do the following :

For fileNr 0 :
Compute the product of all prime numbers that have '0' in the list of
fileNrs under them. That would be 2 * 5 * 11 = 110. Thus we store 110 at
index 0 of the primeArray.

For fileNr 1 :
Compute the product of all prime numbers that have '1' in the list of
fileNrs under them. That would be 2 * 7 = 14. Thus we store 14 at
index 1 of the primeArray.

That would result in the following picture :

Primes:		   2    3    5    7   11   13   
Combinations:	   A    B    C    D    E    F
Index in Array:	|  0 |  1 |  2 |  3 |  4 |  5 | 	Prime Array
		   |	     |	  |    |		 Value	Index
Lists:		 +---+	   +---+  |   +---+		+-----+
		 | 0 |	   | 0 |  |   | 0 |		| 110 |   0
		 +---+	   +---+  |   +---+		|     |
		   |	  	  |			+-----+
		 +---+		+---+			|     |
		 | 1 |  	| 1 |			|  14 |	  1
		 +---+  	+---+			+-----+

For those with some mathematical insight : each product in the primeArray
can be factored in only one product of prime numbers. It is therefore,
only divisible by products of one or more of its diffent factors (no
repetition allowed).

We will use this to try if we can find all files containing the pattern
"A".

Step 1 : Compute QueryProduct for the query.
	"A" correspondse to 2. Thus the QueryProduct is 2.

Step 2 : Check the primeArray.
	The product at primeArray index 0 (= 110) is divisible by 2.
	Thus, the file with fileNr 0 contains an "A"

	The product at primeArray index 1 (= 14) is divisible by 2.
	Thus, the file with fileNr 0 contains an "A"

What about pattern "AC" ?

Step 1 : Compute QueryProduct for the query.
	"A" correspondse to 2, "C" to 5. Thus the QueryProduct is 10.

Step 2 : Check the primeArray.
	The product at primeArray index 0 (= 110) is divisible by 10.
	Thus, the file with fileNr 0 contains "AC"

	The product at primeArray index 1 (= 14) is not divisible by 10.
	Thus, the file with fileNr 0 does not contain "AC"


This scheme requires only very simple steps. For each query, a product has
to be computed. Then, for each entry in the primeArray, we must test
whether the entry is divisile by the product of the query. If that is the
case, the pattern is in the file, otherwise it is not.

The problem with this algorithm is that computing products of prime number
yields VERY large numbers. Suppose every pattern is in a filename. Then
the product would be the product of all prime numbers. The product of even
the smallest 50000+ prime numbers is HUGE. Therefore, this algorithm is
not used in Hagelslag.


###
# 4.1.3.5 Overview


#################
# 4.2 Networker #
#################

The Networker accepts new connections, reads from existing connections and
lets all Connections send their out-Buffers onto the Gnutella Network. Please
note that outgoing Connections are made using a HConnect method in Host, called
from the Backend.

###
# 4.2.1 Accepting new connections

The Networker listens on a port. Whenever a new connection is attempted,
it tries to determine the type of connection. If insufficient data is
received, a Connection object is instanciated and stored in the
pendingConnections Database. When sufficient data is received, the
Connection is returned for further processing, a time construction deals
with silent connections.

###
# 4.2.2 Reading data

First, all Connections are requested to read data from the net. Then, the
Networker attempts to create GnutellaPackets from the Connections
in-Buffer. Packets that are incomplete are stored in a pendingPackets
Database. Some sanity checking is done, the source code contains a lot of
comment to describe the various steps.

###
# 4.2.3 Sending data

A simple method causes all Connections to send their out-Buffers over the
net.

######################
# 4.3 GnutellaRouter #
######################

The GnutellaRouter makes routing decisions for Gnutella Packets. It offers
additional method for sending packets on a particular Connection and for
broadcasting packets to all Connections.

The Routing decisions made are compliant with the specifications of the
Gnutella protocol.

The GnutellaRouters makes its routing decisions for a given GnutellaPacket 
based  on a Database of Mesg objects. It then adds the GnutellaPacket to
the out-buffer of all Connections in the shared Connections DataBase that
need to receive this GntellaPacket.


###################
# 4.4 HostCatcher #
###################

The HostCatcher attempt to detect hosts on the gnutella network. It does so
by attempting to parse INIT_RESPONSE and QUERY_RESPONSE packets. Certain hosts
should be refused, particularly those on originating from local networks.

These include, but are not limited too, the following list :

10.0.0.0 	- 10.255.255.255
172.16.0.0	- 172.32.255.255
192.168.0.0	- 192.168.255.255


#####################
# 4.5 SearchManager #
#####################

The SearchManager parses GnutellaPackets of the QUERY_RESPONSE type and
creates SearchResult object from these packets. All results are stored in a
DataBase.

##################
# 4.6 Downloader #
##################

The Downloader does 2 things

PushRequest Management
Download Management.

PushRequest Management follows the following basic pattern :
	- PushRequests can be added.
	- incoming push connections can be matched with PushRequests.
	  if succesfull, they are then added to the downloads
	- aged PushRequests are removed.

Download Management is done in a seperate function. Several states are
defined. Downloads are expected to move slowly through the proces and are removed
when an error has occured (= their state has changes to an nasty value) of they
are done (= their state has changed to CON_STATE_DONE).

The Downloaded has been split into two parts really, it has a superclass
HTTPClient, to allow different implementations to download using HTTP.


###############
# 4.7 Monitor #
###############

This thing is very boring. It keeps a linked list of Query Data Components
of a specified length, so nosy people can see what other people are
looking for.




###########################################################################
###									###
###	Chapter 5							###
###	Program Layers							###
###									###
###########################################################################


##########################
# 5.1 Program Components #
##########################

The Program Components form the lowest layer. One could see this as the
layer which forms the actual program, as these are the parts that perform
specific tasks where others merely translate between abstraction levels.

###############
# 5.2 Backend #
###############

The Backend forms an interface of all actions that Hagelslag can take.
These can be divided in several area's :
1) a poll function that must be calles frequently (= as often as possible)
2) Informational commands to extract information from the Program Components
3) Methods to take actions, to influence the Program Component Layer
4) Automated tasks
5) Methods to couple the Program Components


#################
# 5.3 Commander #
#################

The Commander parses user input and formats output. It's only function is to
act as abstaction level between Hagelslag, which only knows that input and
output must be processed and the Backend, which only offers an interface full
of program calls.

#################
# 5.4 Hagelslag #
#################

Hagelslag is the top level layer. Except when running as a ROUTER, this layer
reads user input, passes it on to the commander and sends output back to the
user.

It's second task is that is contains the main loop that keeps the entire
program running.

###########################################################################
###									###
###	Appendix A							###
###	F.A.M.E.							###
###									###
###########################################################################

F.A.M.E. is an acronym which stands for :
Fast Access Method Extention

Is this really something besides a confusing acronym to imply a good idea
behind bad programming ? NO!

F.A.M.E. was something I came up with to improve performance. In order to
retrieve a string from an object, one usualy requires the following
construction :

void Class::getString(char *dest)
{
	strcpy(dest, objectMember);
}

It is faster and more memory efficient to use the follwing construction :

char *Class:getString()
{
	return (char *)objectMember;
}

This pointer allows modification of the object outside the object class
methods, which is a clear violation of data protection. It saves a copy
operation, which is not very interesting, except when you have to do it very
often.

So, F.A.M.E. actually is the following set of rules :
1) F.A.M.E. methods return pointer to data inside objects to allow fast
access to this data.
2) These pointers may ONLY be used for READ access.
3) To warn the programmer of the risk, it should be noted in comment
when a method is a F.A.M.E. method.


###########################################################################
###									###
###	Appendix B							###
###	Word List							###
###									###
###########################################################################

Data Component
	# A Class which is primarily intended to hold information or to
	serve as base Class to other Data Components.

F.A.M.E.
	# See appendix A

Gnutella Connection
	# A network connection between to Hosts on the Gnutella Network.

Gnutella Network
	# The virtual network that is made of all Host with their Gnutella
	Connections to each other.

Gnutella Packet
	# A packet of information that is sent over the Gnutella Network.

Gnutella Protocol
	# The protocol for communication between Hosts on the Gnutella Network

Host
	# A node running a Gnutella clone.

Program Component
	# A Class which is intended to function as an 'acting' part of the
	program.


###########################################################################
###									###
###	Appendix C							###
###	References							###
###									###
###########################################################################

Most cool thing have been ripped from elsewhere and have been optimized by
myself and finaly applied in the program.

There are a few people that I should mention :

Joris van Rantwijk, who frequently discusses alghorithms with me (and
gives free lectures which are better than some of the professors'...)

Edward Akerboom, who invented the heart of the search algorithm of the
FileServer. This algorithm was developed from use in a real-time speech-
recognition application.

Other people have done their share of testing, packaging etc, but this is
a document on design and theory and therefore their names are not listed
here. If you feel left out, please contact the author.
