gnunet-c-tutorial.tex 61 KB

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