fe53eca9d4f9e9ea1eaf2c0e5521ff9b929f3c40
[oweals/gnunet.git] / doc / gnunet-c-tutorial.tex
1 \documentclass[10pt]{article}
2 \usepackage[ansinew]{inputenc}
3 \usepackage{makeidx,amsmath,amssymb,exscale,multicol,epsfig,graphics,verbatim,ulem}
4 \usepackage{epsfig,geometry,url,listings, subcaption}
5 \usepackage{boxedminipage}
6 \usepackage[T1]{fontenc}%required
7 \usepackage{textcomp}
8 \geometry{headsep=3ex,hscale=0.9}
9 \usepackage{hyperref}
10 \hypersetup{pdftitle={GNUnet C Tutorial},
11   pdfsubject={GNUnet},
12   pdfauthor={Christian Grothoff <christian@grothoff.org>},
13   pdfkeywords={p2p,search,gnunet,tutorial}
14   %,pdfpagemode={FullScreen}
15   }
16
17
18 \lstset{ 
19 language=bash,
20 basicstyle=\ttfamily,  
21 upquote=true,
22 columns=fullflexible,
23 literate={*}{{\char42}}1
24          {-}{{\char45}}1
25 }
26
27 \newcommand{\exercise}[1]{\noindent\begin{boxedminipage}{\textwidth}{\bf Exercise:} #1 \end{boxedminipage}}
28
29 \begin{document}
30
31 \begin{center}
32 \large {A Tutorial for GNUnet 0.9.x (C version)}
33
34 Christian Grothoff $\qquad$ Bart Polot $\qquad$ Matthias Wachs
35
36 \today
37 \end{center}
38 This tutorials explains how to install GNUnet on a GNU/Linux system ond gives an introduction how 
39 GNUnet can be used to develop a Peer-to-Peer application. Detailed installation instructions for 
40 various operating systems and a detailed list of all dependencies can found on our website at 
41 \url{https://gnunet.org/installation}. 
42
43 \textbf{Please read this tutorial carefully since every single step is important and do not hesitate to contact the GNUnet team if you have any questions or problems! Check here how to contact the GNUnet team:
44 \url{https://gnunet.org/contact_information}}
45
46
47 \section{Installing GNUnet}
48 First of all you have to install a current version of GNUnet. You can download a 
49 tarball of a stable version from GNU FTP mirrors or obtain the latest development 
50 version from our Subversion repository.
51
52 Most of the time you should prefer to download the stable version since with the 
53 latest development version things can be broken, functionality can be changed or tests 
54 can fail. You should only use the development version if you know that you require a 
55 certain feature or a certain issue has been fixed since the last release.
56
57 \subsection{Obtaining a stable version}
58 You can download the latest stable version of GNUnet from GNU FTP mirrors:
59 \begin{center}
60 \url{ftp://ftp.gnu.org/gnu/gnunet/gnunet-0.9.5a.tar.gz}
61 \end{center}
62 You should also download the signature file and verify the integrity of the tarball.
63 \begin{center}
64 \url{ftp://ftp.gnu.org/gnu/gnunet/gnunet-0.9.5a.tar.gz.sig}
65 \end{center}
66 To verify the signature you should first import the GPG key used to sign the tarball
67 \begin{lstlisting}
68 $ gpg --keyserver keys.gnupg.net --recv-keys 48426C7E
69 \end{lstlisting}
70 And use this key to verify the tarball's signature
71 \begin{lstlisting}
72 $ gpg --verify gnunet-0.9.5a.tar.gz.sig gnunet-0.9.5a.tar.gz
73 \end{lstlisting}
74 After successfully verifying the integrity you can extract the tarball using
75 \begin{lstlisting}
76 $ tar xvzf gnunet-0.9.5a.tar.gz
77 $ mv gnunet-0.9.5a gnunet # we will use the directory "gnunet" in the reminder of this document
78 $ cd gnunet
79 \end{lstlisting}
80
81 \subsection{Installing Build Tool Chain and Dependencies}
82 To successfully compile GNUnet you need the tools to build GNUnet and the required dependencies.
83 Please have a look at \url{https://gnunet.org/dependencies} for a list of required dependencies 
84 and \url{https://gnunet.org/generic_installation} for specific instructions for your operating system.
85
86 Please check the notes at the end of the configure process about required dependencies.
87
88 For GNUNet bootstrapping support and the http(s) plugin you should install \texttt{libcurl}.
89 For the filesharing service you should install at least one of the datastore backends \texttt{mysql}, 
90 \texttt{sqlite} or \texttt{postgresql}.
91
92 \subsection{Obtaining the latest version from Subversion}
93 The latest development version can obtained from our Subversion (\textit{svn}) repository. To obtain 
94 the code you need Subversion installed and checkout the repository using:
95 \lstset{language=bash}
96 \begin{lstlisting}
97 $ svn checkout https://gnunet.org/svn/gnunet
98 \end{lstlisting}
99 After cloning the repository you have to execute
100 \lstset{language=bash}
101 \begin{lstlisting}
102 $ cd gnunet
103 $ ./bootstrap
104 \end{lstlisting}
105
106 The remainder of this tutorial assumes that you have SVN HEAD checked out.
107
108 \subsection{Compiling and Installing GNUnet}
109
110 First, you need to install the latest {\tt
111   libgnupgerror}\footnote{\url{ftp://ftp.gnupg.org/gcrypt/libgpg-error/libgpg-error-1.11.tar.bz2}}
112 and {\tt libgcrypt} version from Git.  The current GNUnet code uses
113 ECC functions not available in any released version of libgcrypt.
114
115 \lstset{language=bash}
116 \begin{lstlisting}
117 $ git clone git://git.gnupg.org/libgcrypt.git
118 $ cd libgcrypt
119 $ ./autogen.sh
120 $ ./configure ; $ make install 
121 \end{lstlisting}
122
123 \label{sub:install}
124 Assuming all dependencies are installed, the following commands will compile and install GNUnet in your 
125 home directory. You can specify the directory where GNUnet will be installed by changing the \lstinline|--prefix| value when calling \lstinline|./configure|.  If you do not specifiy a prefix, GNUnet is installed in the directory \lstinline|/usr/local|. When developing new applications you may want to enable 
126 verbose logging by adding \lstinline|--enable-logging=verbose|:
127
128 \lstset{language=bash}
129 \begin{lstlisting}
130 $ ./configure --prefix=$HOME --enable-logging
131 $ make
132 $ make install 
133 \end{lstlisting}
134
135 After installing GNUnet you have to set the \lstinline|GNUNET_PREFIX| environmental variable used by GNUnet to detect it's installation directory and add your GNUnet installation to your path environmental variable.
136 This configuration is only valid for the current shell session, so you should add \lstinline|export GNUNET_PREFIX=$HOME| to your \lstinline|.bash_rc| or \lstinline|.profile| to be sure the environment variable is always set. In addition you have to create the \lstinline|.gnunet| directory in your home directory where GNUnet stores it's data and an empty GNUnet configuration file:
137
138 \lstset{language=bash}
139 \begin{lstlisting}
140 $ export GNUNET_PREFIX=$HOME 
141 $ export PATH=$PATH:$GNUNET_PREFIX/bin
142 $ echo export GNUNET_PREFIX=$HOME >> ~/.bashrc
143 $ echo export PATH=$GNUNET_PREFIX/bin:$PATH >> ~/.bashrc
144 $ mkdir ~/.gnunet/
145 $ touch ~/.gnunet/gnunet.conf
146 \end{lstlisting}
147 % $
148
149 \subsection{Common Issues - Check your GNUnet installation}
150 You should check your installation to ensure that installing GNUnet was successful up to this point. You should be able to access GNUnet's binaries and run GNUnet's self check.
151 \begin{lstlisting}
152 $ which gnunet-arm 
153 \end{lstlisting}
154 should return \lstinline|$GNUNET_PREFIX/bin/gnunet-arm|. It should be located in your GNUnet installation and the output should not be empty. If you see an output like:
155 \begin{lstlisting}
156 $ which gnunet-arm
157
158 \end{lstlisting}
159 check your {\tt PATH} variable to ensure GNUnet's {\tt bin} directory is included.
160
161 GNUnet provides tests for all of it's subcomponents. Run
162 \begin{lstlisting}
163 $ make check
164 \end{lstlisting}
165 to execute tests for all components. {\tt make check} traverses all subdirectories in {\tt src}. 
166 For every subdirectory you should get a message like this:
167
168 \begin{lstlisting}
169 make[2]: Entering directory `/home/mwachs/gnunet/contrib'
170 PASS: test_gnunet_prefix
171 =============
172 1 test passed
173 =============
174 \end{lstlisting}
175
176 If you see a message like this:
177
178 \begin{lstlisting}
179 Mar 12 16:57:56-642482 resolver-api-19449 ERROR Must specify `HOSTNAME' for `resolver' in configuration!
180 Mar 12 16:57:56-642573 test_program-19449 ERROR Assertion failed at resolver_api.c:204.
181 /bin/bash: line 5: 19449 Aborted                 (core dumped) ${dir}$tst
182 FAIL: test_program
183 \end{lstlisting}
184 double check your {\tt GNUNET\_PREFIX} environmental variable and double check the steps performed in ~\ref{sub:install}
185
186 \section{Background: GNUnet Architecture}
187 GNUnet is organized in layers and services. Each service is composed of a
188 main service implementation and a client library for other programs to use 
189 the service's functionality, described by an API. This approach is shown in 
190 figure~\ref{fig:service}. Some services provide an additional command line 
191 tool to enable the user to interact with the service.
192
193 Very often it is other GNUnet services that will use these APIs to build the
194 higher layers of GNUnet on top of the lower ones. Each layer expands or extends
195 the functionality of the service below (for instance, to build a mesh on top of
196 a DHT). See figure ~\ref{fig:interaction} for an illustration of this approach.
197
198 \begin{figure}[!h]
199   \begin{center}
200 %  \begin{subfigure}
201         \begin{subfigure}[b]{0.3\textwidth}
202                 \centering
203                 \includegraphics[width=\textwidth]{figs/Service.pdf}
204                 \caption{Service with API and network protocol}
205                 \label{fig:service}
206         \end{subfigure}    
207         ~~~~~~~~~~
208         \begin{subfigure}[b]{0.3\textwidth}
209                 \centering
210                 \includegraphics[width=\textwidth]{figs/System.pdf}
211                 \caption{Service interaction}
212                 \label{fig:interaction}
213         \end{subfigure}  
214   \end{center}
215   \caption{GNUnet's layered system architecture}
216 \end{figure}
217
218 The main service implementation runs as a standalone process in the operating
219 system and the client code runs as part of the client program, so crashes of a
220 client do not affect the service process or other clients. The service and the
221 clients communicate via a message protocol to be defined and implemented by
222 the programmer.
223
224 \section{First Steps with GNUnet}
225
226 \subsection{Configure your peer}
227 First of all we need to configure your peer. Each peer is started with a configuration containing settings for GNUnet itself and it's services. This configuration is based on the default configuration shipped with GNUnet and can be modified. The default configuration is located in the {\tt \$GNUNET\_PREFIX/share/gnunet/config.d} directory. When starting a peer, you can specify a customized configuration using the the {\tt$-c$} command line switch when starting the ARM service and all other services. When using a modified configuration the default values are loaded and only values specified in the configuration file will replace the default values.
228
229 Since we want to start additional peers later, we need 
230 some modifications from the default configuration. We need to create a separate service home and a file containing our modifications for this peer:
231 \begin{lstlisting}
232 $ mkdir ~/gnunet1/
233 $ touch peer1.conf
234 \end{lstlisting}
235
236 Now add the following lines to peer1.conf to use this directory. For simplified usage we want to prevent 
237 the peer to connect to the GNUnet network since this could lead to confusing output. This modifications will replace the default settings:
238 \begin{lstlisting}
239 $ [PATHS]
240 $ SERVICEHOME = ~/gnunet1/ # Use this directory to store GNUnet data
241 $ [hostlist]
242 $ SERVERS = # prevent bootstrapping
243 \end{lstlisting}
244
245 \subsection{Start a peer}
246 Each GNUnet instance (called peer) has an identity (\textit{peer ID}) based on a 
247 cryptographic public private key pair. The peer ID is the printable hash of the 
248 public key. So before starting the peer, you may want to just generate the peer's private 
249 key using the command
250 \lstset{language=bash}
251 \begin{lstlisting}
252 $ gnunet-peerinfo -c ~/peer1.conf -s
253 \end{lstlisting}
254 You should see an output containing the peer ID similar to:
255 \lstset{language=bash}
256 \begin{lstlisting}
257 I am peer `0PA02UVRKQTS2C .. JL5Q78F6H0B1ACPV1CJI59MEQUMQCC5G'.
258 \end{lstlisting}
259
260 GNUnet services are controlled by a master service the so called \textit{Automatic Restart Manager} (ARM).
261 ARM starts, stops and even restarts services automatically or on demand when a client connects.
262 You interact with the ARM service using the \lstinline|gnunet-arm| tool. 
263 GNUnet can then be started with \lstinline|gnunet-arm -s| and stopped with 
264 \lstinline|gnunet-arm -e|.  An additional service not automatically started 
265 can be started using \lstinline|gnunet-arm -i <service name>| and stopped 
266 using \lstinline|gnunet-arm -k <servicename>|. 
267
268 \subsection{Monitor a peer}
269 In this section, we will monitor the behaviour of our peer's DHT service with respect to a 
270 specific key. First we will start GNUnet and then start the DHT service and use the DHT monitor tool
271 to monitor the PUT and GET commands we issue ussing the \lstinline|gnunet-dht-put| and 
272 \lstinline|gnunet-dht-get| command. Using the ``monitor'' line given below, you can observe the behavior of
273 your own peer's DHT with respect to the specified KEY:
274
275 \lstset{language=bash}
276 \begin{lstlisting}
277 $ gnunet-arm -c ~/peer1.conf -s # start gnunet with all default services
278 $ gnunet-arm -c ~/peer1.conf -i dht # start DHT service
279 $ cd ~/gnunet/src/dht;
280 $ ./gnunet-dht-monitor -c ~/peer1.conf -k KEY
281 \end{lstlisting}
282 Now open a separate terminal and change again to the \lstinline|gnunet/src/dht| directory:
283 \begin{lstlisting}
284 $ cd ~/gnunet/src/dht
285 $ ./gnunet-dht-put -c ~/peer1.conf -k KEY -d VALUE # put VALUE under KEY in the DHT 
286 $ ./gnunet/src/dht/gnunet-dht-get ~/peer1.conf -k KEY # get key KEY from the DHT
287 $ gnunet-statistics -c ~/peer1.conf # print statistics about current GNUnet state
288 $ gnunet-statistics -c ~/peer1.conf -s dht # print statistics about DHT service
289 \end{lstlisting}
290 % $
291 \subsection{Starting Two Peers by Hand}
292 \subsubsection{Setup a second peer}
293 We will now start a second peer on your machine.
294 For the second peer, you will need to manually create a modified
295 configuration file to avoid conflicts with ports and directories.  
296 A peers configuration file is by default located in {\tt ~/.gnunet/gnunet.conf}.
297 This file is typically very short or even empty as only the differences to the
298 defaults need to be specified.  The defaults are located in 
299 many files in the {\tt \$GNUNET\_PREFIX/share/gnunet/config.d} directory.
300
301 To configure the second peer, use the files {\tt
302   \$GNUNET\_PREFIX/share/gnunet/config.d} as a template for your main
303 configuration file:
304 %
305 \lstset{language=bash}
306 \begin{lstlisting}
307 $ cat $GNUNET_PREFIX/share/gnunet/config.d/*.conf > peer2.conf
308 \end{lstlisting}
309 Now you have to edit {\tt peer2.conf} and change:
310 \begin{itemize}
311   \itemsep0em
312   \item{\texttt{SERVICEHOME} under \texttt{PATHS}}
313   \item{Every (uncommented) value for ``\texttt{PORT}'' (add 10000) in any
314         section (the option may be commented out if \texttt{PORT} is 
315         prefixed by "\#", in this case, UNIX domain sockets are used
316         and the PORT option does not need to be touched) }
317   \item{Every value for ``\texttt{UNIXPATH}'' in any section (e.g. by adding a "-p2" suffix)}
318 \end{itemize}
319 to a fresh, unique value.  Make sure that the \texttt{PORT} numbers stay
320 below 65536.  From now on, whenever you interact with the second
321 peer, you need to specify {\tt -c peer2.conf} as an additional
322 command line argument.
323
324 Now, generate the 2nd peer's private key:
325
326 \lstset{language=bash}
327 \begin{lstlisting}
328 $ gnunet-peerinfo -s -c peer2.conf
329 \end{lstlisting}
330 % $
331
332 This may take a while, generate entropy using your keyboard or mouse
333 as needed.  Also, make sure the output is different from the {\tt
334   gnunet-peerinfo} output for the first peer (otherwise you made an
335 error in the configuration).
336
337 \subsubsection{Start the second peer and connect the peers}
338 Then, you can start a second peer using:
339 \lstset{language=bash}
340 \begin{lstlisting}
341 $ gnunet-arm -c peer2.conf -s
342 $ gnunet-arm -c peer2.conf -i dht
343 $ ~/gnunet/src/dht/gnunet-dht-put -c peer2.conf -k KEY -d VALUE
344 $ ~/gnunet/src/dht/gnunet-dht-get -c peer2.conf -k KEY
345 \end{lstlisting}
346 If you want the two peers to connect, you have multiple options:
347 \begin{itemize}
348 \itemsep0em
349   \item UDP neighbour discovery (automatic)
350   \item Setup a bootstrap server
351   \item Connect manually
352 \end{itemize}
353 To setup peer 1 as bootstrapping server change the configuration of the first one to be a hostlist server by adding the following lines to \texttt{peer1.conf} to enable bootstrapping server:
354  \begin{lstlisting}
355 [hostlist]
356 OPTIONS = -p
357 \end{lstlisting}
358
359 Then change {\tt peer2.conf} and replace the ``\texttt{SERVERS}'' line in the ``\texttt{[hostlist]}'' section with
360 ``\texttt{http://localhost:8080/}''.  Restart both peers using:
361 \begin{lstlisting}
362 $ gnunet-arm -c peer1.conf -e # stop first peer
363 $ gnunet-arm -c peer1.conf -s # start first peer
364 $ gnunet-arm -c peer2.conf -s # start second peer
365 \end{lstlisting}
366
367 Note that if you start your peers without changing these settings, they
368 will use the ``global'' hostlist servers of the GNUnet P2P network and
369 likely connect to those peers.  At that point, debugging might become
370 tricky as you're going to be connected to many more peers and would 
371 likely observe traffic and behaviors that are not explicitly controlled
372 by you.
373
374 \subsubsection{How to connect manually}
375 If you want to use the \texttt{peerinfo} tool to connect your peers, you should:
376 \begin{itemize}
377 \itemsep0em
378  \item{Remove {\tt hostlist} from {\tt DEFAULTSERVICES} (to not connect to the global GNUnet)}
379  \item{Start both peers running {\tt gnunet-arm -c peer1.conf -s} and {\tt gnunet-arm -c peer2.conf -s}}
380  \item{Get \texttt{HELLO} message of the first peer running {\tt gnunet-peerinfo -c peer1.conf -g}}
381  \item{Give the output to the second peer by running {\tt gnunet-peerinfo -c peer2.conf -p '<output>'}}
382 \end{itemize}
383
384 Check that they are connected using {\tt gnunet-core -c peer1.conf}, which should give you the other peer's 
385 peer identity:
386 \begin{lstlisting}
387 $ gnunet-core -c peer1.conf
388 Peer `9TVUCS8P5A7ILLBGO6JSTSSN2B44H3D2MUIFJMLKAITC0I22UVFBFP1H8NRK2IA35VKAK16LLO0MFS7TAQ9M1KNBJ4NGCHP3JPVULDG'
389 \end{lstlisting}
390
391 \subsection{Starting Peers Using the Testbed Service}
392
393 GNUnet's testbed service is used for testing scenarios where a number of peers
394 are to be started.  The testbed can manage peers on a single host or on multiple
395 hosts in a distributed fashion.  On a single affordable computer, it should be
396 possible to run around tens of peers without drastically increasing the load on the
397 system.
398
399 The testbed service can be access through its API
400 \texttt{include/gnunet\_testbed\_service.h}.  The API provides many routines for
401 managing a group of peers.  It also provides a helper function
402 \texttt{GNUNET\_TESTBED\_test\_run()} to quickly setup a minimalistic testing
403 environment on a single host.
404
405 This function takes a configuration file which will be used as a template
406 configuration for the peers.  The testbed takes care of modifying relevant
407 options in the peers' configuration such as SERVICEHOME, PORT, UNIXPATH to
408 unique values so that peers run without running into conflicts.  It also checks
409 and assigns the ports in configurations only if they are free.  
410
411 Additionally, the testbed service also reads its options from the same
412 configuration file.  Various available options and details about them can be
413 found in the testbed default configuration file \texttt{src/testbed/testbed.conf}.
414
415 With the testbed API, a sample test case can be structured as follows:
416 \lstinputlisting[language=C]{testbed_test.c}
417 The source code for the above listing can be found at
418 \url{https://gnunet.org/svn/gnunet/doc/testbed_test.c}.  After installing GNUnet, the above source code can be compiled as:
419 \lstset{language=bash}
420 \begin{lstlisting}
421 $ export CPPFLAGS="-I/path/to/gnunet/headers"
422 $ export LDFLAGS="-L/path/to/gnunet/libraries"
423 $ gcc -o testbed-test testbed_test.c  -lgnunettestbed -lgnunetdht -lgnunetutil
424 \end{lstlisting}
425 The \texttt{CPPFLAGS} and \texttt{LDFLAGS} are necessary if GNUnet is installed
426 into a different directory other than \texttt{/usr/local}.
427
428 All of testbed API's peer management functions treat management actions as
429 operations and return operation handles.  It is expected that the operations
430 begin immediately, but they may get delayed (to balance out load on the system).
431 The program using the API then has to take care of marking the operation as
432 ``done'' so that its associated resources can be freed immediately and other
433 waiting operations can be executed.  Operations will be canceled if they are
434 marked as ``done'' before their completion.
435
436 An operation is treated as completed when it succeeds or fails.  Completion of
437 an operation is either conveyed as events through \textit{controller event
438   callback} or through respective operation completion callbacks.  In functions
439 which support completion notification through both controller event callback and
440 operation completion callback, first the controller event callback will be
441 called.  If the operation is not marked as done in that callback or if the
442 callback is given as NULL when creating the operation, the operation completion
443 callback will be called.  The API documentation shows which event are to be
444 expected in the controller event notifications.  It also documents any
445 exceptional behaviour.
446
447 Once the peers are started, test cases often need to connect some of the peers'
448 services.  Normally, opening a connect to a peer's service requires the peer's
449 configuration.  While using testbed, the testbed automatically generates
450 per-peer configuration.  Accessing those configurations directly through file
451 system is discouraged as their locations are dynamically created and will be
452 different among various runs of testbed.  To make access to these configurations
453 easy, testbed API provides the function
454 \texttt{GNUNET\_TESTBED\_service\_connect()}.  This function fetches the
455 configuration of a given peer and calls the \textit{Connect Adapter}.
456 In the example code, it is the \texttt{dht\_ca}.  A connect adapter is expected
457 to open the connection to the needed service by using the provided configuration
458 and return the created service connection handle.  Successful connection to the
459 needed service is signaled through \texttt{service\_connect\_comp\_cb}.
460
461 A dual to connect adapter is the \textit{Disconnect Adapter}.  This callback is
462 called after the connect adapter has been called when the operation from
463 \texttt{GNUNET\_TESTBED\_service\_connect()} is marked as ``done''.  It has to
464 disconnect from the service with the provided service handle (\texttt{op\_result}).
465
466 \exercise{Find out how many peers you can run on your system.}
467
468 \exercise{Find out how to create a 2D torus topology by changing the
469   options in the configuration file.\footnote{FIXME: Sree Harsha: need to 
470   document configuration file options on gnunet.org and add link here!}
471   Then use the DHT API to store and retrieve values in the
472   network.}
473
474 \section{Developing Applications}
475 \subsection{gnunet-ext}
476 To develop a new peer-to-peer application or to extend GNUnet we provide
477 a template build system for writing GNUnet extensions in C. It can be
478 obtained as follows:
479
480 \lstset{language=bash}
481 \begin{lstlisting}
482 $ svn checkout https://gnunet.org/svn/gnunet-ext/
483 $ cd gnunet-ext/
484 $ ./bootstrap
485 $ ./configure --prefix=$HOME --with-gnunet=$GNUNET_PREFIX
486 $ make
487 $ make install
488 $ make check
489 \end{lstlisting}
490 % $
491
492 The GNUnet ext template includes examples and a working buildsystem for a new GNUnet service.
493 A common GNUnet service consists of the following parts which will be discussed in detail in the
494 remainder of this document. The functionality of a GNUnet service is implemented in:
495
496 \begin{itemize}
497 \itemsep0em
498   \item the GNUnet service (\lstinline|gnunet-ext/src/ext/gnunet-service-ext.c|)
499   \item the client API (\lstinline|gnunet-ext/src/ext/ext_api.c|)
500   \item the client application using the service API (\lstinline|gnunet-ext/src/ext/gnunet-ext.c|) 
501
502
503 \end{itemize}
504
505 The interfaces for these entities are defined in:
506 \begin{itemize}
507 \itemsep0em
508   \item client API interface (\lstinline|gnunet-ext/src/ext/ext.h|) 
509   \item the service interface (\lstinline|gnunet-ext/src/include/gnunet_service_SERVICE.h|)
510   \item the P2P protocol (\lstinline|gnunet-ext/src/include/gnunet_protocols_ext.h|)
511 \end{itemize}
512
513
514 In addition the \texttt{ext} systems provides:
515 \begin{itemize}
516 \itemsep0em
517   \item a test testing the API (\lstinline|gnunet-ext/src/ext/test_ext_api.c|)
518   \item a configuration template for the service (\lstinline|gnunet-ext/src/ext/ext.conf.in|)
519 \end{itemize}
520
521
522 \subsection{Adapting the Template}
523
524 The first step for writing any extension with a new service is to
525 ensure that the {\tt ext.conf.in} file contains entries for the
526 \texttt{UNIXPATH}, \texttt{PORT} and \texttt{BINARY} for the service in a section named after
527 the service. 
528
529 If you want to adapt the template rename the {\tt ext.conf.in} to match your 
530 services name, you have to modify the \texttt{AC\_OUTPUT} section in {\tt configure.ac} 
531 in the \texttt{gnunet-ext} root.
532
533 \section{Writing a Client Application}
534
535 When writing any client application (for example, a command-line
536 tool), the basic structure is to start with the {\tt
537   GNUNET\_PROGRAM\_run} function.  This function will parse
538 command-line options, setup the scheduler and then invoke the {\tt
539   run} function (with the remaining non-option arguments) and a handle
540 to the parsed configuration (and the configuration file name that was
541 used, which is typically not needed):
542
543 \lstset{language=c}
544 \begin{lstlisting}
545 #include <gnunet/platform.h>
546 #include <gnunet/gnunet_util_lib.h>
547
548 static int ret;
549
550 static void
551 run (void *cls,
552      char *const *args,
553      const char *cfgfile,
554      const struct GNUNET_CONFIGURATION_Handle *cfg)
555 {
556   /* main code here */
557   ret = 0;
558 }
559
560 int
561 main (int argc, char *const *argv)
562 {
563   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
564     GNUNET_GETOPT_OPTION_END
565   };
566   return (GNUNET_OK ==
567           GNUNET_PROGRAM_run (argc,
568                               argv,
569                               "binary-name",
570                               gettext_noop ("binary description text"),
571                               options, &run, NULL)) ? ret : 1;
572 }
573 \end{lstlisting}
574
575 \subsection{Handling command-line options}
576
577 Options can then be added easily by adding global variables and
578 expanding the {\tt options} array.  For example, the following would
579 add a string-option and a binary flag (defaulting to {\tt NULL} and
580 {\tt GNUNET\_NO} respectively):
581
582 \begin{lstlisting}
583 static char *string_option;
584 static int a_flag;
585
586 // ...
587   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
588   {'s', "name", "SOMESTRING",
589      gettext_noop ("text describing the string_option NAME"), 1,
590      &GNUNET_GETOPT_set_string, &string_option},
591     {'f', "flag", NULL,
592      gettext_noop ("text describing the flag option"), 0,
593      &GNUNET_GETOPT_set_one, &a_flag},
594     GNUNET_GETOPT_OPTION_END
595   };
596 // ...
597 \end{lstlisting}
598
599 Issues such as displaying some helpful text describing options using
600 the {\tt --help} argument and error handling are taken care of when
601 using this approach.  Other {\tt GNUNET\_GETOPT\_}-functions can be used
602 to obtain integer value options, increment counters, etc.  You can
603 even write custom option parsers for special circumstances not covered
604 by the available handlers.
605
606 Inside the {\tt run} method, the program would perform the
607 application-specific logic, which typically involves initializing and
608 using some client library to interact with the service.  The client
609 library is supposed to implement the IPC whereas the service provides
610 more persistent P2P functions.
611
612 \exercise{Add a few command-line options and print them inside
613 of {\tt run}.  What happens if the user gives invalid arguments?}
614
615 \subsection{Writing a Client Library}
616
617 The first and most important step in writing a client library is to
618 decide on an API for the library.  Typical API calls include 
619 connecting to the service, performing application-specific requests
620 and cleaning up.  Many examples for such service APIs can be found
621 in the {\tt gnunet/src/include/gnunet\_*\_service.h} files.
622
623 Then, a client-service protocol needs to be designed.  This typically
624 involves defining various message formats in a header that will be
625 included by both the service and the client library (but is otherwise
626 not shared and hence located within the service's directory and not
627 installed by {\tt make install}).  Each message must start with a {\tt
628   struct GNUNET\_MessageHeader} and must be shorter than 64k.  By
629 convention, all fields in IPC (and P2P) messages must be in big-endian
630 format (and thus should be read using {\tt ntohl} and similar
631 functions and written using {\tt htonl} and similar functions).
632 Unique message types must be defined for each message struct in the
633 {\tt gnunet\_protocols.h} header (or an extension-specific include
634 file).
635
636 \subsubsection{Connecting to the Service}
637
638 Before a client library can implement the application-specific protocol
639 with the service, a connection must be created:
640
641 \lstset{language=c}
642 \begin{lstlisting}
643   struct GNUNET_CLIENT_Connection *client;
644   client = GNUNET_CLIENT_connect ("service-name", cfg);
645 \end{lstlisting}
646
647 As a result a {\tt GNUNET\_CLIENT\_Connection} handle is returned 
648 which has to used in later API calls related to this service.
649 The complete client API can be found in {\tt gnunet\_client\_lib.h}
650
651 \subsubsection{GNUnet Messages}
652
653 In GNUnet, messages are always sent beginning with a {\tt struct GNUNET\_MessageHeader}
654 in big endian format. This header defines the size and the type of the 
655 message, the payload follows after this header.
656
657 \lstset{language=c}
658 \begin{lstlisting}
659 struct GNUNET_MessageHeader
660 {
661
662   /**
663    * The length of the struct (in bytes, including the length field itself),
664    * in big-endian format.
665    */
666   uint16_t size GNUNET_PACKED;
667
668   /**
669    * The type of the message (GNUNET_MESSAGE_TYPE_XXXX), in big-endian format.
670    */
671   uint16_t type GNUNET_PACKED;
672
673 };
674 \end{lstlisting}
675
676 Existing message types are defined in {\tt gnunet\_protocols.h}\\
677 A common way to create a message is:
678
679 \lstset{language=c}
680 \begin{lstlisting}
681 struct GNUNET_MessageHeader *msg = 
682   GNUNET_malloc(payload_size + sizeof(struct GNUNET_MessageHeader));
683 msg->size = htons(payload_size + sizeof(struct GNUNET_MessageHeader));
684 msg->type = htons(GNUNET_MY_MESSAGE_TYPE);
685 memcpy(&msg[1], &payload, payload_size);
686 // use 'msg'
687 \end{lstlisting}
688
689 \exercise{Define a message struct that includes a 32-bit
690 unsigned integer in addition to the standard GNUnet MessageHeader.
691 Add a C struct and define a fresh protocol number for your message.}
692
693
694 \subsubsection{Sending Requests to the Service}
695
696 Any client-service protocol must start with the client sending the
697 first message to the service, since services are only notified about
698 (new) clients upon receiving a the first message.
699
700 Clients can transmit messages to the service using the
701 {\tt GNUNET\_CLIENT\_notify\_transmit\_ready} API:
702 \lstset{language=c}
703 \begin{lstlisting}
704 static size_t
705 transmit_cb (void *cls, size_t size, void *buf)
706 {
707   // ...
708   if (NULL == buf) { handle_error(); return 0; }
709   GNUNET_assert (size >= msg_size);
710   memcpy (buf, my_msg, msg_size);
711   // ...
712   return msg_size;
713 }
714
715 // ...  
716 th = GNUNET_CLIENT_notify_transmit_ready (client,
717                                           msg_size,
718                                     timeout,
719                                           GNUNET_YES,
720                                           &transmit_cb, cls);
721 // ...
722 \end{lstlisting}
723
724 The client-service protocoll calls {\tt GNUNET\_CLIENT\_notify\_transmit\_ready}
725 to be notified when the client is ready to send data to the service. 
726 Besides other arguments, you have to pass the client returned 
727 from the {\tt connect} call, the message size and the callback function to 
728 call when the client is ready to send. 
729
730 Only a single transmission request can be queued per client at the
731 same time using this API.  The handle {\tt th} can be used to cancel
732 the request if necessary (for example, during shutdown).  
733
734 When {\tt transmit\_cb} is called the message is copied in the buffer provided and 
735 the number of bytes copied into the buffer is returned. {\tt transmit\_cb} 
736 could also return 0 if for some reason no message
737 could be constructed; this is not an error and the connection to the
738 service will persist in this case.
739
740 \exercise{Define a helper function to transmit a 32-bit
741 unsigned integer (as payload) to a service using some given client
742 handle.}
743
744
745 \subsubsection{Receiving Replies from the Service}
746
747 Clients can receive messages from the service using the
748 {\tt GNUNET\_CLIENT\_receive} API:
749
750 \lstset{language=c}
751 \begin{lstlisting}
752 /**
753  * Function called with messages from stats service.
754  *
755  * @param cls closure
756  * @param msg message received, NULL on timeout or fatal error
757  */
758 static void
759 receive_message (void *cls, const struct GNUNET_MessageHeader *msg)
760 {
761   struct MyArg *arg = cls;
762
763   // process 'msg'
764 }
765
766 // ... 
767   GNUNET_CLIENT_receive (client,
768                          &receive_message,
769                          arg,
770                          timeout);
771 // ...
772 \end{lstlisting}
773
774 It should be noted that this receive call only receives a single
775 message.  To receive additional messages, {\tt
776   GNUNET\_CLIENT\_receive} must be called again.
777
778 \exercise{Expand your helper function to receive a
779 response message (for example, containing just the GNUnet MessageHeader
780 without any payload).  Upon receiving the service's response, you should
781 call a callback provided to your helper function's API.  You'll need to 
782 define a new 'struct' to hold your local context (``closure'').}
783
784
785 \subsection{Writing a user interface}
786
787 Given a client library, all it takes to access a service now is to
788 combine calls to the client library with parsing command-line
789 options.
790
791 \exercise{Call your client API from your {\tt run} method
792 in your client application to send a request to the service.
793 For example, send a 32-bit integer value based on a number given
794 at the command-line to the service.}
795
796
797   
798 \section{Writing a Service}
799
800 Before you can test the client you've written so far, you'll need to also
801 implement the corresponding service.
802
803
804 \subsection{Code Placement}
805
806 New services are placed in their own subdirectory under {\tt gnunet/src}.
807 This subdirectory should contain the API implementation file {\tt SERVICE\_api.c},
808 the description of the client-service protocol {\tt SERVICE.h} and P2P protocol
809 {\tt SERVICE\_protocol.h}, the implementation of the service itself
810 {\tt gnunet-service-SERVICE.h} and several files for tests, including test code
811 and configuration files.
812
813 \subsection{Starting a Service}
814
815 The key API definitions for starting services are:
816 \lstset{language=C}
817 \begin{lstlisting}
818 typedef void (*GNUNET_SERVICE_Main) (void *cls,
819                                      struct GNUNET_SERVER_Handle *server,
820                                      const struct GNUNET_CONFIGURATION_Handle *cfg);
821 int GNUNET_SERVICE_run (int argc,
822                         char *const *argv,
823                         const char *serviceName,
824                         enum GNUNET_SERVICE_Options opt,
825                         GNUNET_SERVICE_Main task,
826                         void *task_cls);
827 \end{lstlisting}
828
829 Here is a starting point for your main function for your service:
830
831 \lstset{language=c}
832 \begin{lstlisting}
833 static void my_main (void *cls,
834                      struct GNUNET_SERVER_Handle *server,
835                      const struct GNUNET_CONFIGURATION_Handle *cfg)
836
837    /* do work */  
838 }
839
840 int main (int argc, char *const*argv) 
841 {
842   if (GNUNET_OK != 
843       GNUNET_SERVICE_run (argc, argv, "my", 
844                           GNUNET_SERVICE_OPTION_NONE, 
845                           &my_main, NULL);
846     return 1;
847   return 0;    
848 }
849 \end{lstlisting}
850
851 \exercise{Write a stub service that processes no messages at all
852 in your code.  Create a default configuration for it, integrate it
853 with the build system and start the service from {\tt
854   gnunet-service-arm} using {\tt gnunet-arm -i NAME}.}
855
856
857 \subsection{Receiving Requests from Clients}
858
859 Inside of the {\tt my\_main} method, a service typically registers for
860 the various message types from clients that it supports by providing
861 a handler function, the message type itself and possibly a fixed
862 message size (or 0 for variable-size messages):
863
864 \lstset{language=c}
865 \begin{lstlisting}
866 static void
867 handle_set (void *cls,
868             struct GNUNET_SERVER_Client *client,
869             const struct GNUNET_MessageHeader *message)
870 {
871   GNUNET_SERVER_receive_done (client, GNUNET_OK); 
872 }
873 static void
874 handle_get (void *cls,
875             struct GNUNET_SERVER_Client *client,
876             const struct GNUNET_MessageHeader *message)
877 {
878   GNUNET_SERVER_receive_done (client, GNUNET_OK); 
879 }
880
881 static void my_main (void *cls,
882                      struct GNUNET_SERVER_Handle *server,
883                      const struct GNUNET_CONFIGURATION_Handle *cfg)
884
885   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
886     {&handle_set, NULL, GNUNET_MESSAGE_TYPE_MYNAME_SET, 0},
887     {&handle_get, NULL, GNUNET_MESSAGE_TYPE_MYNAME_GET, 0},
888     {NULL, NULL, 0, 0}
889   };
890   GNUNET_SERVER_add_handlers (server, handlers);
891    /* do more setup work */  
892
893 \end{lstlisting}
894
895 Each handler function {\bf must} eventually (possibly in some
896 asynchronous continuation) call {\tt GNUNET\_SERVER\_receive\_done}.
897 Only after this call additional messages from the same client may
898 be processed. This way, the service can throttle processing messages
899 from the same client.  By passing {\tt GNUNET\_SYSERR}, the service
900 can close the connection to the client, indicating an error.
901
902 Services must check that client requests are well-formed and must not
903 crash on protocol violations by the clients.  Similarly, client
904 libraries must check replies from servers and should gracefully report
905 errors via their API.
906
907
908 \exercise{Change the service to ``handle'' the message from your
909 client (for now, by printing a message).  What happens if you
910 forget to call {\tt GNUNET\_SERVER\_receive\_done}?}
911
912
913 \subsection{Responding to Clients}
914
915 Servers can send messages to clients using the
916 {\tt GNUNET\_SERVER\_notify\_transmit\_ready} API:
917
918 \lstset{language=c}
919 \begin{lstlisting}
920 static size_t
921 transmit_cb (void *cls, size_t size, void *buf)
922 {
923   // ...
924   if (NULL == buf) { handle_error(); return 0; }
925   GNUNET_assert (size >= msg_size);
926   memcpy (buf, my_msg, msg_size);
927   // ...
928   return msg_size;
929 }
930
931 // ...  
932 struct GNUNET_SERVER_TransmitHandle *th;
933 th = GNUNET_SERVER_notify_transmit_ready (client,
934                                           msg_size,
935                                           timeout,
936                                           &transmit_cb, cls);
937 // ...
938 \end{lstlisting}
939
940 Only a single transmission request can be queued per client
941 at the same time using this API.
942 Additional APIs for sending messages to clients can be found
943 in the {\tt gnunet\_server\_lib.h} header.  
944
945
946 \exercise{Change the service respond to the request from your
947 client.  Make sure you handle malformed messages in both directions.}
948
949
950 \section{Interacting directly with other Peers using the CORE Service}
951
952 One of the most important services in GNUnet is the \texttt{CORE} service 
953 managing connections between peers and handling encryption between peers.
954
955 One of the first things any service that extends the P2P protocol typically does
956 is connect to the \texttt{CORE} service using:
957
958 \lstset{language=C}
959 \begin{lstlisting}
960 #include <gnunet/gnunet_core_service.h>
961
962 struct GNUNET_CORE_Handle *
963 GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
964                      void *cls,
965                      GNUNET_CORE_StartupCallback init,
966                      GNUNET_CORE_ConnectEventHandler connects,
967                      GNUNET_CORE_DisconnectEventHandler disconnects,
968                      GNUNET_CORE_MessageCallback inbound_notify,
969                      int inbound_hdr_only,
970                      GNUNET_CORE_MessageCallback outbound_notify,
971                      int outbound_hdr_only,
972                      const struct GNUNET_CORE_MessageHandler *handlers);
973 \end{lstlisting}
974
975 \subsection{New P2P connections}
976
977 Before any traffic with a different peer can be exchanged, the peer must be
978 known to the service. This is notified by the \texttt{CORE} {\tt connects} callback,
979 which communicates the identity of the new peer to the service:
980
981 \lstset{language=C}
982 \begin{lstlisting}
983 void
984 connects (void *cls,
985           const struct GNUNET_PeerIdentity * peer)
986 {
987     /* Save identity for later use */
988     /* Optional: start sending messages to peer */
989 }
990 \end{lstlisting}
991
992 \exercise{Create a service that connects to the \texttt{CORE}.  Then
993 start (and connect) two peers and print a message once your connect
994 callback is invoked.}
995
996 \subsection{Receiving P2P Messages}
997
998 To receive messages from \texttt{CORE}, services register a set of handlers
999 (parameter {\tt *handlers} in the \lstinline|GNUNET_CORE_connect| call that are called by \texttt{CORE}
1000 when a suitable message arrives.
1001
1002 \lstset{language=c}
1003 \begin{lstlisting}
1004 static int
1005 callback_function_for_type_one(void *cls,
1006                                const struct GNUNET_PeerIdentity *peer,
1007                                const struct GNUNET_MessageHeader *message)
1008 {
1009     /* Do stuff */
1010     return GNUNET_OK; /* or GNUNET_SYSERR to close the connection */
1011 }
1012
1013 /**
1014  * Functions to handle messages from core
1015  */
1016 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
1017   {&callback_function_for_type_one, GNUNET_MESSAGE_TYPE_MYSERVICE_TYPE_ONE, 0},
1018   /* more handlers*/
1019   {NULL, 0, 0}
1020 };
1021 \end{lstlisting}
1022
1023 \exercise{Start one peer with a new service that has a message
1024 handler and start a second peer that only has your ``old'' service
1025 without message handlers.  Which ``connect'' handlers are invoked when
1026 the two peers are connected?  Why?}
1027
1028
1029 \subsection{Sending P2P Messages}
1030
1031 In response to events (connect, disconnect, inbound messages, 
1032 timing, etc.) services can then use this API to transmit messages:
1033
1034 \lstset{language=C}
1035 \begin{lstlisting}
1036 typedef size_t 
1037 (*GNUNET_CONNECTION_TransmitReadyNotify) (void *cls,
1038                                           size_t size, 
1039                                           void *buf)
1040 {
1041     /* Fill "*buf" with up to "size" bytes, must start with GNUNET_MessageHeader */
1042     return n; /* Total size of the message put in "*buf" */
1043 }
1044
1045 struct GNUNET_CORE_TransmitHandle *
1046 GNUNET_CORE_notify_transmit_ready (struct GNUNET_CORE_Handle *handle,
1047                                    int cork, uint32_t priority,
1048                                    struct GNUNET_TIME_Relative maxdelay,
1049                                    const struct GNUNET_PeerIdentity *target,
1050                                    size_t notify_size,
1051                                    GNUNET_CONNECTION_TransmitReadyNotify notify,
1052                                    void *notify_cls);
1053 \end{lstlisting}
1054
1055 \exercise{Write a service that upon connect sends messages as
1056 fast as possible to the other peer (the other peer should run a
1057 service that ``processes'' those messages).  How fast is the
1058 transmission?  Count using the STATISTICS service on both ends.  Are
1059 messages lost? How can you transmit messages faster?  What happens if
1060 you stop the peer that is receiving your messages?}
1061
1062
1063 \subsection{End of P2P connections}
1064
1065 If a message handler returns {\tt GNUNET\_SYSERR}, the remote peer shuts down or
1066 there is an unrecoverable network disconnection, CORE notifies the service that
1067 the peer disconnected. After this notification no more messages will be received
1068 from the peer and the service is no longer allowed to send messages to the peer.
1069 The disconnect callback looks like the following:
1070
1071 \lstset{language=C}
1072 \begin{lstlisting}
1073 void
1074 disconnects (void *cls,
1075              const struct GNUNET_PeerIdentity * peer)
1076 {
1077     /* Remove peer's identity from known peers */
1078     /* Make sure no messages are sent to peer from now on */
1079 }
1080 \end{lstlisting}
1081
1082 \exercise{Fix your service to handle peer disconnects.}
1083
1084 \section{Using the DHT}
1085 The DHT allows to store data so other peers in the P2P network can
1086 access it and retrieve data stored by any peers in the network.
1087 This section will explain how to use the DHT. Of course, the first
1088 thing to do is to connect to the DHT service:
1089 \lstset{language=C}
1090 \begin{lstlisting}
1091 dht_handle = GNUNET_DHT_connect (cfg, parallel_requests);
1092 \end{lstlisting}
1093 The second parameter indicates how many requests in parallel to expect.
1094 It is not a hard limit, but a good approximation will make the DHT more
1095 efficiently.
1096
1097 \subsection{Storing data in the DHT}
1098 Since the DHT is a dynamic environment (peers join a leave frequently)
1099 the data that we put in the DHT does not stay there indefinitely. It is
1100 important to ``refresh'' the data periodically by simply storing it again,
1101 in order to make sure other peers can access it.
1102
1103 The put API call offers a callback to signal that the PUT request has been
1104 sent. This does not guarantee that the data is accessible to others peers,
1105 or even that is has been stored, only that the service has requested to
1106 a neighboring peer the retransmission of the PUT request towards its final
1107 destination. Currently there is no feedback about whether or not the data
1108 has been sucessfully stored or where it has been stored. In order to improve
1109 the availablilty of the data and to compensate for possible errors, peers leaving
1110 and other unfavorable events, just make several PUT requests!
1111
1112 \lstset{language=C}
1113 \begin{lstlisting}
1114 void
1115 message_sent_cont (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1116 {
1117     /* Request has left local node */
1118 }
1119
1120 struct GNUNET_DHT_PutHandle *
1121 GNUNET_DHT_put (struct GNUNET_DHT_Handle *handle, 
1122                 const struct GNUNET_HashCode * key,
1123                 uint32_t desired_replication_level,
1124                 enum GNUNET_DHT_RouteOption options, /* Route options, see next call */
1125                 enum GNUNET_BLOCK_Type type, size_t size, const void *data,
1126                 struct GNUNET_TIME_Absolute exp, /* When does the data expire? */
1127                 struct GNUNET_TIME_Relative timeout,  /* How long to try to send the request */
1128                 GNUNET_DHT_PutContinuation cont,
1129                 void *cont_cls)
1130 \end{lstlisting}
1131
1132 \exercise{Store a value in the DHT periodically to make sure it is available
1133 over time. You might consider using the function GNUNET\_SCHEDULER\_add\_delayed and
1134 call GNUNET\_DHT\_put from inside a helper function.}
1135
1136
1137 \subsection{Obtaining data from the DHT}
1138 As we saw in the previous example, the DHT works in an asynchronous mode.
1139 Each request to the DHT is executed ``in the background'' and the API
1140 calls return immediately. In order to receive results from the DHT, the
1141 API provides a callback. Once started, the request runs in the service,
1142 the service will try to get as many results as possible (filtering out
1143 duplicates) until the timeout expires or we explicitly stop the request.
1144 It is possible to give a ``forever'' timeout with
1145 {\tt GNUNET\_TIME\_UNIT\_FOREVER\_REL}.
1146
1147 If we give a route option {\tt GNUNET\_DHT\_RO\_RECORD\_ROUTE} the callback
1148 will get a list of all the peers the data has travelled, both on the PUT
1149 path and on the GET path.
1150 \lstset{language=C}
1151 \begin{lstlisting}
1152 static void
1153 get_result_iterator (void *cls, struct GNUNET_TIME_Absolute expiration,
1154                      const struct GNUNET_HashCode * key,
1155                      const struct GNUNET_PeerIdentity *get_path,
1156                      unsigned int get_path_length,
1157                      const struct GNUNET_PeerIdentity *put_path,
1158                      unsigned int put_path_length,
1159                      enum GNUNET_BLOCK_Type type, size_t size, const void *data)
1160 {
1161     /* Do stuff with the data and/or route */
1162     /* Optionally: */
1163     GNUNET_DHT_get_stop (get_handle);
1164 }
1165
1166 get_handle =
1167       GNUNET_DHT_get_start (dht_handle,
1168                             block_type,
1169                             &key,
1170                             replication,
1171                             GNUNET_DHT_RO_NONE, /* Route options */
1172                             NULL, /* xquery: not used here */
1173                             0, /* xquery size */
1174                             &get_result_iterator,
1175                             cls)
1176 \end{lstlisting}
1177
1178 \exercise{Store a value in the DHT and after a while retrieve it. Show the IDs of all 
1179 the peers the requests have gone through. In order to convert a peer ID to a string, use
1180 the function GNUNET\_i2s. Pay attention to the route option parameters in both calls!}
1181
1182 \subsection{Implementing a block plugin}
1183
1184 In order to store data in the DHT, it is necessary to provide a block
1185 plugin.  The DHT uses the block plugin to ensure that only well-formed
1186 requests and replies are transmitted over the network.
1187
1188 The block plugin should be put in a file {\tt
1189   plugin\_block\_SERVICE.c} in the service's respective directory. The
1190 mandatory functions that need to be implemented for a block plugin are
1191 described in the following sections.
1192
1193 \subsubsection{Validating requests and replies}
1194
1195 The evaluate function should validate a reply or a request. It returns
1196 a {\tt GNUNET\_BLOCK\_EvaluationResult}, which is an enumeration. All
1197 possible answers are in {\tt gnunet\_block\_lib.h}.  The function will
1198 be called with a {\tt reply\_block} argument of {\tt NULL} for
1199 requests.  Note that depending on how {\tt evaluate} is called, only
1200 some of the possible return values are valid.  The specific meaning of
1201 the {\tt xquery} argument is application-specific.  Applications that
1202 do not use an extended query should check that the {\tt xquery\_size}
1203 is zero.  The Bloom filter is typically used to filter duplicate
1204 replies.
1205
1206 \lstset{language=C}
1207 \begin{lstlisting}
1208 static enum GNUNET_BLOCK_EvaluationResult
1209 block_plugin_SERVICE_evaluate (void *cls,
1210                                enum GNUNET_BLOCK_Type type,
1211                                const GNUNET_HashCode * query,
1212                                struct GNUNET_CONTAINER_BloomFilter **bf,
1213                                int32_t bf_mutator,
1214                                const void *xquery,
1215                                size_t xquery_size,
1216                                const void *reply_block,
1217                                size_t reply_block_size)
1218 {
1219   /* Verify type, block and bloomfilter */
1220 }
1221 \end{lstlisting}
1222
1223 Note that it is mandatory to detect duplicate replies in this 
1224 function and return the respective status code.  Duplicate 
1225 detection should be done by setting the respective bits in
1226 the Bloom filter {\tt bf}.  Failure to do so may cause replies
1227 to circle in the network.
1228
1229 \subsubsection{Deriving a key from a reply}
1230
1231 The DHT can operate more efficiently if it is possible to derive a key
1232 from the value of the corresponding block.  The {\tt get\_key}
1233 function is used to obtain the key of a block --- for example, by
1234 means of hashing.  If deriving the key is not possible, the function
1235 should simply return {\tt GNUNET\_SYSERR} (the DHT will still work
1236 just fine with such blocks).
1237
1238 \lstset{language=C}
1239 \begin{lstlisting}
1240 static int
1241 block_plugin_SERVICE_get_key (void *cls, enum GNUNET_BLOCK_Type type,
1242                               const void *block, size_t block_size,
1243                               GNUNET_HashCode * key)
1244 {
1245     /* Store the key in the key argument, return GNUNET_OK on success. */
1246 }
1247 \end{lstlisting}
1248
1249 \subsubsection{Initialization of the plugin}
1250
1251 The plugin is realized as a shared C library.  The library must export
1252 an initialization function which should initialize the plugin.  The
1253 initialization function specifies what block types the plugin cares
1254 about and returns a struct with the functions that are to be used for
1255 validation and obtaining keys (the ones just defined above).
1256
1257 \lstset{language=C}
1258 \begin{lstlisting}
1259 void *
1260 libgnunet_plugin_block_SERVICE_init (void *cls)
1261 {
1262   static enum GNUNET_BLOCK_Type types[] =
1263   {
1264     GNUNET_BLOCK_TYPE_SERVICE_BLOCKYPE, /* list of blocks we care about, from gnunet_block_lib.h */
1265     GNUNET_BLOCK_TYPE_ANY       /* end of list */
1266   };
1267   struct GNUNET_BLOCK_PluginFunctions *api;
1268
1269   api = GNUNET_malloc (sizeof (struct GNUNET_BLOCK_PluginFunctions));
1270   api->evaluate = &block_plugin_SERICE_evaluate;
1271   api->get_key = &block_plugin_SERVICE_get_key;
1272   api->types = types;
1273   return api;
1274 }
1275 \end{lstlisting}
1276
1277 \subsubsection{Shutdown of the plugin}
1278
1279 Following GNUnet's general plugin API concept, the plugin must 
1280 export a second function for cleaning up.  It usually does very
1281 little.
1282
1283 \lstset{language=C}
1284 \begin{lstlisting}
1285 void *
1286 libgnunet_plugin_block_SERVICE_done (void *cls)
1287 {
1288   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1289
1290   GNUNET_free (api);
1291   return NULL;
1292 }
1293 \end{lstlisting}
1294
1295
1296 \subsubsection{Integration of the plugin with the build system}
1297
1298 In order to compile the plugin, the {\tt Makefile.am} file for the
1299 service should contain a rule similar to this:
1300
1301 \lstset{language=make}
1302 \begin{lstlisting}
1303 plugin_LTLIBRARIES = \
1304   libgnunet_plugin_block_SERVICE.la
1305 libgnunet_plugin_block_SERVICE_la_SOURCES = \
1306   plugin_block_SERVICE.c
1307 libgnunet_plugin_block_SERVICE_la_LIBADD = \
1308   $(top_builddir)/src/hello/libgnunethello.la \
1309   $(top_builddir)/src/block/libgnunetblock.la \
1310   $(top_builddir)/src/util/libgnunetutil.la
1311 libgnunet_plugin_block_SERVICE_la_LDFLAGS = \
1312  $(GN_PLUGIN_LDFLAGS)
1313 libgnunet_plugin_block_SERVICE_la_DEPENDENCIES = \
1314   $(top_builddir)/src/block/libgnunetblock.la
1315 \end{lstlisting}
1316 % $
1317
1318
1319 \exercise{Write a block plugin that accepts all queries
1320 and all replies but prints information about queries and replies
1321 when the respective validation hooks are called.}
1322
1323
1324
1325 \subsection{Monitoring the DHT}
1326 It is possible to monitor the functioning of the local DHT service. When monitoring
1327 the DHT, the service will alert the monitoring program of any events,
1328 both started locally or received for routing from another peer. The are three different
1329 types of events possible: a GET request, a PUT request or a response (a reply to
1330 a GET).
1331
1332 Since the different events have different associated data, the API gets 3
1333 different callbacks (one for each message type) and optional type and key parameters,
1334 to allow for filtering of messages. When an event happens, the appropiate callback
1335 is called with all the information about the event.
1336 \lstset{language=C}
1337 \begin{lstlisting}
1338 void
1339 get_callback (void *cls,
1340               enum GNUNET_DHT_RouteOption options,
1341               enum GNUNET_BLOCK_Type type,
1342               uint32_t hop_count,
1343               uint32_t desired_replication_level,
1344               unsigned int path_length,
1345               const struct GNUNET_PeerIdentity *path,
1346               const struct GNUNET_HashCode * key)
1347 {
1348 }
1349
1350 void
1351 get_resp_callback (void *cls,
1352                    enum GNUNET_BLOCK_Type type,
1353                    const struct GNUNET_PeerIdentity *get_path,
1354                    unsigned int get_path_length,
1355                    const struct GNUNET_PeerIdentity *put_path,
1356                    unsigned int put_path_length,
1357                    struct GNUNET_TIME_Absolute exp,
1358                    const struct GNUNET_HashCode * key,
1359                    const void *data,
1360                    size_t size)
1361 {
1362 }
1363
1364 void
1365 put_callback (void *cls,
1366               enum GNUNET_DHT_RouteOption options,
1367               enum GNUNET_BLOCK_Type type,
1368               uint32_t hop_count,
1369               uint32_t desired_replication_level,
1370               unsigned int path_length,
1371               const struct GNUNET_PeerIdentity *path,
1372               struct GNUNET_TIME_Absolute exp,
1373               const struct GNUNET_HashCode * key,
1374               const void *data,
1375               size_t size)
1376 {
1377 }
1378
1379 monitor_handle = GNUNET_DHT_monitor_start (dht_handle,
1380                                            block_type, /* GNUNET_BLOCK_TYPE_ANY for all */
1381                                            key, /* NULL for all */
1382                                            &get_callback,
1383                                            &get_resp_callback,
1384                                            &put_callback,
1385                                            cls);
1386 \end{lstlisting}
1387
1388
1389 \section{Debugging with {\tt gnunet-arm}}
1390
1391 Even if services are managed by {\tt gnunet-arm}, you can start them with 
1392 {\tt gdb} or {\tt valgrind}.  For example, you could add the following lines
1393 to your configuration file to start the DHT service in a {\tt gdb} session in a
1394 fresh {\tt xterm}:
1395
1396 \begin{verbatim}
1397 [dht]
1398 PREFIX=xterm -e gdb --args
1399 \end{verbatim}
1400
1401 Alternatively, you can stop a service that was started via ARM and run it manually:
1402
1403 \lstset{language=bash}
1404 \begin{lstlisting}
1405 $ gnunet-arm -k dht
1406 $ gdb --args gnunet-service-dht -L DEBUG 
1407 $ valgrind gnunet-service-dht -L DEBUG 
1408 \end{lstlisting}
1409 % $
1410
1411 Assuming other services are well-written, they will automatically re-integrate the
1412 restarted service with the peer.
1413
1414 GNUnet provides a powerful logging mechanism providing log levels \texttt{ERROR}, 
1415 \texttt{WARNING}, \texttt{INFO} and \texttt{DEBUG}. The current log level is 
1416 configured using the \lstinline|$GNUNET_FORCE_LOG| environmental variable.
1417 The \texttt{DEBUG} level is only available if \lstinline|--enable-logging=verbose| was used when 
1418 running \texttt{configure}. More details about logging can be found under 
1419 \url{https://gnunet.org/logging}.
1420
1421 You should also probably enable the creation of core files, by setting
1422 {\tt ulimit}, and echo'ing 1 into {\tt /proc/sys/kernel/core\_uses\_pid}.
1423 Then you can investigate the core dumps with {\tt gdb}, which is often
1424 the fastest method to find simple errors.
1425
1426 \exercise{Add a memory leak to your service and obtain a trace
1427 pointing to the leak using {\tt valgrind} while running the service
1428 from {\tt gnunet-service-arm}.}
1429
1430
1431 \end{document}