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