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