doc/documentation: developer,philosophy,user: suggestions by
[oweals/gnunet.git] / doc / documentation / chapters / developer.texi
1 @c ***********************************************************************
2 @node GNUnet Developer Handbook
3 @chapter GNUnet Developer Handbook
4
5 This book is intended to be an introduction for programmers that want to
6 extend the GNUnet framework. GNUnet is more than a simple peer-to-peer
7 application.
8
9 For developers, GNUnet is:
10
11 @itemize @bullet
12 @item developed by a community that believes in the GNU philosophy
13 @item Free Software (Free as in Freedom), licensed under the
14 GNU General Public License
15 @item A set of standards, including coding conventions and
16 architectural rules
17 @item A set of layered protocols, both specifying the communication
18 between peers as well as the communication between components
19 of a single peer
20 @item A set of libraries with well-defined APIs suitable for
21 writing extensions
22 @end itemize
23
24 In particular, the architecture specifies that a peer consists of many
25 processes communicating via protocols. Processes can be written in almost
26 any language.
27 C and Java @footnote{As well as Guile} APIs exist for accessing existing
28 services and for writing extensions.
29 It is possible to write extensions in other languages by
30 implementing the necessary IPC protocols.
31
32 GNUnet can be extended and improved along many possible dimensions, and
33 anyone interested in Free Software and Freedom-enhancing Networking is
34 welcome to join the effort. This Developer Handbook attempts to provide
35 an initial introduction to some of the key design choices and central
36 components of the system.
37 This part of the GNUNet documentation is far from complete,
38 and we welcome informed contributions, be it in the form of
39 new chapters, sections or insightful comments.
40
41 @menu
42 * Developer Introduction::
43 * Code overview::
44 * System Architecture::
45 * Subsystem stability::
46 * Naming conventions and coding style guide::
47 * Build-system::
48 * Developing extensions for GNUnet using the gnunet-ext template::
49 * Writing testcases::
50 * TESTING library::
51 * Performance regression analysis with Gauger::
52 * TESTBED Subsystem::
53 * libgnunetutil::
54 * Automatic Restart Manager (ARM)::
55 * TRANSPORT Subsystem::
56 * NAT library::
57 * Distance-Vector plugin::
58 * SMTP plugin::
59 * Bluetooth plugin::
60 * WLAN plugin::
61 * ATS Subsystem::
62 * CORE Subsystem::
63 * CADET Subsystem::
64 * NSE Subsystem::
65 * HOSTLIST Subsystem::
66 * IDENTITY Subsystem::
67 * NAMESTORE Subsystem::
68 * PEERINFO Subsystem::
69 * PEERSTORE Subsystem::
70 * SET Subsystem::
71 * STATISTICS Subsystem::
72 * Distributed Hash Table (DHT)::
73 * GNU Name System (GNS)::
74 * GNS Namecache::
75 * REVOCATION Subsystem::
76 * File-sharing (FS) Subsystem::
77 * REGEX Subsystem::
78 @end menu
79
80 @node Developer Introduction
81 @section Developer Introduction
82
83 This Developer Handbook is intended as first introduction to GNUnet for
84 new developers that want to extend the GNUnet framework. After the
85 introduction, each of the GNUnet subsystems (directories in the
86 @file{src/} tree) is (supposed to be) covered in its own chapter. In
87 addition to this documentation, GNUnet developers should be aware of the
88 services available on the GNUnet server to them.
89
90 New developers can have a look a the GNUnet tutorials for C and java
91 available in the @file{src/} directory of the repository or under the
92 following links:
93
94 @c ** FIXME: Link to files in source, not online.
95 @c ** FIXME: Where is the Java tutorial?
96 @itemize @bullet
97 @c broken link
98 @item @uref{https://gnunet.org/git/gnunet.git/plain/doc/gnunet-c-tutorial.pdf, GNUnet C tutorial}
99 @item GNUnet Java tutorial
100 @end itemize
101
102 In addition to the GNUnet Reference Documentation you are reading,
103 the GNUnet server at @uref{https://gnunet.org} contains
104 various resources for GNUnet developers and those
105 who aspire to become regular contributors.
106 They are all conveniently reachable via the "Developer"
107 entry in the navigation menu. Some additional tools (such as static
108 analysis reports) require a special developer access to perform certain
109 operations. If you want (or require) access, you should contact
110 @uref{http://grothoff.org/christian/, Christian Grothoff},
111 GNUnet's maintainer.
112
113 The public subsystems on the GNUnet server that help developers are:
114
115 @itemize @bullet
116
117 @item The version control system (git) keeps our code and enables
118 distributed development.
119 It is pubclicly accessible at @uref{https://gnunet.org/git/}.
120 Only developers with write access can commit code, everyone else is
121 encouraged to submit patches to the
122 @uref{https://lists.gnu.org/mailman/listinfo/gnunet-developers, GNUnet-developers mailinglist}.
123
124 @item The bugtracking system (Mantis).
125 We use it to track feature requests, open bug reports and their
126 resolutions.
127 It can be accessed at @uref{https://gnunet.org/bugs/}.
128 Anyone can report bugs, but only developers can claim to have fixed them.
129
130 @item Our site installation of the
131 CI@footnote{Continuous Integration} system @code{Buildbot} is used
132 to check GNUnet builds automatically on a range of platforms.
133 The web interface of this CI is exposed at
134 @uref{https://gnunet.org/buildbot/}.
135 Builds are triggered automatically 30 minutes after the last commit to
136 our repository was made.
137
138 @item The current quality of our automated test suite is assessed using
139 Code coverage analysis. This analysis is run daily; however the webpage
140 is only updated if all automated tests pass at that time. Testcases that
141 improve our code coverage are always welcome.
142
143 @item We try to automatically find bugs using a static analysis scan.
144 This scan is run daily; however the webpage is only updated if all
145 automated tests pass at the time. Note that not everything that is
146 flagged by the analysis is a bug, sometimes even good code can be marked
147 as possibly problematic. Nevertheless, developers are encouraged to at
148 least be aware of all issues in their code that are listed.
149
150 @item We use Gauger for automatic performance regression visualization.
151 Details on how to use Gauger are here.
152
153 @item We use @uref{http://junit.org/, junit} to automatically test
154 @command{gnunet-java}.
155 Automatically generated, current reports on the test suite are here.
156
157 @item We use Cobertura to generate test coverage reports for gnunet-java.
158 Current reports on test coverage are here.
159
160 @end itemize
161
162
163
164 @c ***********************************************************************
165 @menu
166 * Project overview::
167 @end menu
168
169 @node Project overview
170 @subsection Project overview
171
172 The GNUnet project consists at this point of several sub-projects. This
173 section is supposed to give an initial overview about the various
174 sub-projects. Note that this description also lists projects that are far
175 from complete, including even those that have literally not a single line
176 of code in them yet.
177
178 GNUnet sub-projects in order of likely relevance are currently:
179
180 @table @asis
181
182 @item @command{gnunet}
183 Core of the P2P framework, including file-sharing, VPN and
184 chat applications; this is what the Developer Handbook covers mostly
185 @item @command{gnunet-gtk}
186 Gtk+-based user interfaces, including:
187
188 @itemize @bullet
189 @item @command{gnunet-fs-gtk} (file-sharing),
190 @item @command{gnunet-statistics-gtk} (statistics over time),
191 @item @command{gnunet-peerinfo-gtk}
192 (information about current connections and known peers),
193 @item @command{gnunet-chat-gtk} (chat GUI) and
194 @item @command{gnunet-setup} (setup tool for "everything")
195 @end itemize
196
197 @item @command{gnunet-fuse}
198 Mounting directories shared via GNUnet's file-sharing
199 on GNU/Linux distributions
200 @item @command{gnunet-update}
201 Installation and update tool
202 @item @command{gnunet-ext}
203 Template for starting 'external' GNUnet projects
204 @item @command{gnunet-java}
205 Java APIs for writing GNUnet services and applications
206 @c ** FIXME: Point to new website repository once we have it:
207 @c ** @item svn/gnunet-www/ Code and media helping drive the GNUnet
208 @c website
209 @item @command{eclectic}
210 Code to run GNUnet nodes on testbeds for research, development,
211 testing and evaluation
212 @c ** FIXME: Solve the status and location of gnunet-qt
213 @item @command{gnunet-qt}
214 Qt-based GNUnet GUI (is it depreacated?)
215 @item @command{gnunet-cocoa}
216 cocoa-based GNUnet GUI (is it depreacated?)
217 @item @command{gnunet-guile}
218
219 @end table
220
221 We are also working on various supporting libraries and tools:
222 @c ** FIXME: What about gauger, and what about libmwmodem?
223
224 @table @asis
225 @item @command{libextractor}
226 GNU libextractor (meta data extraction)
227 @item @command{libmicrohttpd}
228 GNU libmicrohttpd (embedded HTTP(S) server library)
229 @item @command{gauger}
230 Tool for performance regression analysis
231 @item @command{monkey}
232 Tool for automated debugging of distributed systems
233 @item @command{libmwmodem}
234 Library for accessing satellite connection quality
235 reports
236 @item @command{libgnurl}
237 gnURL (feature-restricted variant of cURL/libcurl)
238 @end table
239
240 Finally, there are various external projects (see links for a list of
241 those that have a public website) which build on top of the GNUnet
242 framework.
243
244 @c ***********************************************************************
245 @node Code overview
246 @section Code overview
247
248 This section gives a brief overview of the GNUnet source code.
249 Specifically, we sketch the function of each of the subdirectories in
250 the @file{gnunet/src/} directory. The order given is roughly bottom-up
251 (in terms of the layers of the system).
252
253 @table @asis
254 @item @file{util/} --- libgnunetutil
255 Library with general utility functions, all
256 GNUnet binaries link against this library. Anything from memory
257 allocation and data structures to cryptography and inter-process
258 communication. The goal is to provide an OS-independent interface and
259 more 'secure' or convenient implementations of commonly used primitives.
260 The API is spread over more than a dozen headers, developers should study
261 those closely to avoid duplicating existing functions.
262 @pxref{libgnunetutil}.
263 @item @file{hello/} --- libgnunethello
264 HELLO messages are used to
265 describe under which addresses a peer can be reached (for example,
266 protocol, IP, port). This library manages parsing and generating of HELLO
267 messages.
268 @item @file{block/} --- libgnunetblock
269 The DHT and other components of GNUnet
270 store information in units called 'blocks'. Each block has a type and the
271 type defines a particular format and how that binary format is to be
272 linked to a hash code (the key for the DHT and for databases). The block
273 library is a wapper around block plugins which provide the necessary
274 functions for each block type.
275 @item @file{statistics/} --- statistics service
276 The statistics service enables associating
277 values (of type uint64_t) with a component name and a string. The main
278 uses is debugging (counting events), performance tracking and user
279 entertainment (what did my peer do today?).
280 @item @file{arm/} --- Automatic Restart Manager (ARM)
281 The automatic-restart-manager (ARM) service
282 is the GNUnet master service. Its role is to start gnunet-services, to
283 re-start them when they crashed and finally to shut down the system when
284 requested.
285 @item @file{peerinfo/} --- peerinfo service
286 The peerinfo service keeps track of which peers are known
287 to the local peer and also tracks the validated addresses for each peer
288 (in the form of a HELLO message) for each of those peers. The peer is not
289 necessarily connected to all peers known to the peerinfo service.
290 Peerinfo provides persistent storage for peer identities --- peers are
291 not forgotten just because of a system restart.
292 @item @file{datacache/} --- libgnunetdatacache
293 The datacache library provides (temporary) block storage for the DHT.
294 Existing plugins can store blocks in Sqlite, Postgres or MySQL databases.
295 All data stored in the cache is lost when the peer is stopped or
296 restarted (datacache uses temporary tables).
297 @item @file{datastore/} --- datastore service
298 The datastore service stores file-sharing blocks in
299 databases for extended periods of time. In contrast to the datacache, data
300 is not lost when peers restart. However, quota restrictions may still
301 cause old, expired or low-priority data to be eventually discarded.
302 Existing plugins can store blocks in Sqlite, Postgres or MySQL databases.
303 @item @file{template/} --- service template
304 Template for writing a new service. Does nothing.
305 @item @file{ats/} --- Automatic Transport Selection
306 The automatic transport selection (ATS) service
307 is responsible for deciding which address (i.e.
308 which transport plugin) should be used for communication with other peers,
309 and at what bandwidth.
310 @item @file{nat/} --- libgnunetnat
311 Library that provides basic functions for NAT traversal.
312 The library supports NAT traversal with
313 manual hole-punching by the user, UPnP and ICMP-based autonomous NAT
314 traversal. The library also includes an API for testing if the current
315 configuration works and the @code{gnunet-nat-server} which provides an
316 external service to test the local configuration.
317 @item @file{fragmentation/} --- libgnunetfragmentation
318 Some transports (UDP and WLAN, mostly) have restrictions on the maximum
319 transfer unit (MTU) for packets. The fragmentation library can be used to
320 break larger packets into chunks of at most 1k and transmit the resulting
321 fragments reliabily (with acknowledgement, retransmission, timeouts,
322 etc.).
323 @item @file{transport/} --- transport service
324 The transport service is responsible for managing the
325 basic P2P communication. It uses plugins to support P2P communication
326 over TCP, UDP, HTTP, HTTPS and other protocols.The transport service
327 validates peer addresses, enforces bandwidth restrictions, limits the
328 total number of connections and enforces connectivity restrictions (i.e.
329 friends-only).
330 @item @file{peerinfo-tool/} --- gnunet-peerinfo
331 This directory contains the gnunet-peerinfo binary which can be used to
332 inspect the peers and HELLOs known to the peerinfo service.
333 @item @file{core/}
334 The core service is responsible for establishing encrypted, authenticated
335 connections with other peers, encrypting and decrypting messages and
336 forwarding messages to higher-level services that are interested in them.
337 @item @file{testing/} --- libgnunettesting
338 The testing library allows starting (and stopping) peers
339 for writing testcases.
340 It also supports automatic generation of configurations for peers
341 ensuring that the ports and paths are disjoint. libgnunettesting is also
342 the foundation for the testbed service
343 @item @file{testbed/} --- testbed service
344 The testbed service is used for creating small or large scale deployments
345 of GNUnet peers for evaluation of protocols.
346 It facilitates peer depolyments on multiple
347 hosts (for example, in a cluster) and establishing varous network
348 topologies (both underlay and overlay).
349 @item @file{nse/} --- Network Size Estimation
350 The network size estimation (NSE) service
351 implements a protocol for (securely) estimating the current size of the
352 P2P network.
353 @item @file{dht/} --- distributed hash table
354 The distributed hash table (DHT) service provides a
355 distributed implementation of a hash table to store blocks under hash
356 keys in the P2P network.
357 @item @file{hostlist/} --- hostlist service
358 The hostlist service allows learning about
359 other peers in the network by downloading HELLO messages from an HTTP
360 server, can be configured to run such an HTTP server and also implements
361 a P2P protocol to advertise and automatically learn about other peers
362 that offer a public hostlist server.
363 @item @file{topology/} --- topology service
364 The topology service is responsible for
365 maintaining the mesh topology. It tries to maintain connections to friends
366 (depending on the configuration) and also tries to ensure that the peer
367 has a decent number of active connections at all times. If necessary, new
368 connections are added. All peers should run the topology service,
369 otherwise they may end up not being connected to any other peer (unless
370 some other service ensures that core establishes the required
371 connections). The topology service also tells the transport service which
372 connections are permitted (for friend-to-friend networking)
373 @item @file{fs/} --- file-sharing
374 The file-sharing (FS) service implements GNUnet's
375 file-sharing application. Both anonymous file-sharing (using gap) and
376 non-anonymous file-sharing (using dht) are supported.
377 @item @file{cadet/} --- cadet service
378 The CADET service provides a general-purpose routing abstraction to create
379 end-to-end encrypted tunnels in mesh networks. We wrote a paper
380 documenting key aspects of the design.
381 @item @file{tun/} --- libgnunettun
382 Library for building IPv4, IPv6 packets and creating
383 checksums for UDP, TCP and ICMP packets. The header
384 defines C structs for common Internet packet formats and in particular
385 structs for interacting with TUN (virtual network) interfaces.
386 @item @file{mysql/} --- libgnunetmysql
387 Library for creating and executing prepared MySQL
388 statements and to manage the connection to the MySQL database.
389 Essentially a lightweight wrapper for the interaction between GNUnet
390 components and libmysqlclient.
391 @item @file{dns/}
392 Service that allows intercepting and modifying DNS requests of
393 the local machine. Currently used for IPv4-IPv6 protocol translation
394 (DNS-ALG) as implemented by "pt/" and for the GNUnet naming system. The
395 service can also be configured to offer an exit service for DNS traffic.
396 @item @file{vpn/} --- VPN service
397 The virtual public network (VPN) service provides a virtual
398 tunnel interface (VTUN) for IP routing over GNUnet.
399 Needs some other peers to run an "exit" service to work.
400 Can be activated using the "gnunet-vpn" tool or integrated with DNS using
401 the "pt" daemon.
402 @item @file{exit/}
403 Daemon to allow traffic from the VPN to exit this
404 peer to the Internet or to specific IP-based services of the local peer.
405 Currently, an exit service can only be restricted to IPv4 or IPv6, not to
406 specific ports and or IP address ranges. If this is not acceptable,
407 additional firewall rules must be added manually. exit currently only
408 works for normal UDP, TCP and ICMP traffic; DNS queries need to leave the
409 system via a DNS service.
410 @item @file{pt/}
411 protocol translation daemon. This daemon enables 4-to-6,
412 6-to-4, 4-over-6 or 6-over-4 transitions for the local system. It
413 essentially uses "DNS" to intercept DNS replies and then maps results to
414 those offered by the VPN, which then sends them using mesh to some daemon
415 offering an appropriate exit service.
416 @item @file{identity/}
417 Management of egos (alter egos) of a user; identities are
418 essentially named ECC private keys and used for zones in the GNU name
419 system and for namespaces in file-sharing, but might find other uses later
420 @item @file{revocation/}
421 Key revocation service, can be used to revoke the
422 private key of an identity if it has been compromised
423 @item @file{namecache/}
424 Cache for resolution results for the GNU name system;
425 data is encrypted and can be shared among users,
426 loss of the data should ideally only result in a
427 performance degradation (persistence not required)
428 @item @file{namestore/}
429 Database for the GNU name system with per-user private information,
430 persistence required
431 @item @file{gns/}
432 GNU name system, a GNU approach to DNS and PKI.
433 @item @file{dv/}
434 A plugin for distance-vector (DV)-based routing.
435 DV consists of a service and a transport plugin to provide peers
436 with the illusion of a direct P2P connection for connections
437 that use multiple (typically up to 3) hops in the actual underlay network.
438 @item @file{regex/}
439 Service for the (distributed) evaluation of regular expressions.
440 @item @file{scalarproduct/}
441 The scalar product service offers an API to perform a secure multiparty
442 computation which calculates a scalar product between two peers
443 without exposing the private input vectors of the peers to each other.
444 @item @file{consensus/}
445 The consensus service will allow a set of peers to agree
446 on a set of values via a distributed set union computation.
447 @item @file{rest/}
448 The rest API allows access to GNUnet services using RESTful interaction.
449 The services provide plugins that can exposed by the rest server.
450 @item @file{experimentation/}
451 The experimentation daemon coordinates distributed
452 experimentation to evaluate transport and ATS properties.
453 @end table
454
455 @c ***********************************************************************
456 @node System Architecture
457 @section System Architecture
458
459 GNUnet developers like LEGOs. The blocks are indestructible, can be
460 stacked together to construct complex buildings and it is generally easy
461 to swap one block for a different one that has the same shape. GNUnet's
462 architecture is based on LEGOs:
463
464 @c @image{images/service_lego_block,5in,,picture of a LEGO block stack - 3 APIs as connectors upon Network Protocol on top of a Service}
465
466 This chapter documents the GNUnet LEGO system, also known as GNUnet's
467 system architecture.
468
469 The most common GNUnet component is a service. Services offer an API (or
470 several, depending on what you count as "an API") which is implemented as
471 a library. The library communicates with the main process of the service
472 using a service-specific network protocol. The main process of the service
473 typically doesn't fully provide everything that is needed --- it has holes
474 to be filled by APIs to other services.
475
476 A special kind of component in GNUnet are user interfaces and daemons.
477 Like services, they have holes to be filled by APIs of other services.
478 Unlike services, daemons do not implement their own network protocol and
479 they have no API:
480
481 The GNUnet system provides a range of services, daemons and user
482 interfaces, which are then combined into a layered GNUnet instance (also
483 known as a peer).
484
485 Note that while it is generally possible to swap one service for another
486 compatible service, there is often only one implementation. However,
487 during development we often have a "new" version of a service in parallel
488 with an "old" version. While the "new" version is not working, developers
489 working on other parts of the service can continue their development by
490 simply using the "old" service. Alternative design ideas can also be
491 easily investigated by swapping out individual components. This is
492 typically achieved by simply changing the name of the "BINARY" in the
493 respective configuration section.
494
495 Key properties of GNUnet services are that they must be separate
496 processes and that they must protect themselves by applying tight error
497 checking against the network protocol they implement (thereby achieving a
498 certain degree of robustness).
499
500 On the other hand, the APIs are implemented to tolerate failures of the
501 service, isolating their host process from errors by the service. If the
502 service process crashes, other services and daemons around it should not
503 also fail, but instead wait for the service process to be restarted by
504 ARM.
505
506
507 @c ***********************************************************************
508 @node Subsystem stability
509 @section Subsystem stability
510
511 This section documents the current stability of the various GNUnet
512 subsystems. Stability here describes the expected degree of compatibility
513 with future versions of GNUnet. For each subsystem we distinguish between
514 compatibility on the P2P network level (communication protocol between
515 peers), the IPC level (communication between the service and the service
516 library) and the API level (stability of the API). P2P compatibility is
517 relevant in terms of which applications are likely going to be able to
518 communicate with future versions of the network. IPC communication is
519 relevant for the implementation of language bindings that re-implement the
520 IPC messages. Finally, API compatibility is relevant to developers that
521 hope to be able to avoid changes to applications build on top of the APIs
522 of the framework.
523
524 The following table summarizes our current view of the stability of the
525 respective protocols or APIs:
526
527 @multitable @columnfractions .20 .20 .20 .20
528 @headitem Subsystem @tab P2P @tab IPC @tab C API
529 @item util @tab n/a @tab n/a @tab stable
530 @item arm @tab n/a @tab stable @tab stable
531 @item ats @tab n/a @tab unstable @tab testing
532 @item block @tab n/a @tab n/a @tab stable
533 @item cadet @tab testing @tab testing @tab testing
534 @item consensus @tab experimental @tab experimental @tab experimental
535 @item core @tab stable @tab stable @tab stable
536 @item datacache @tab n/a @tab n/a @tab stable
537 @item datastore @tab n/a @tab stable @tab stable
538 @item dht @tab stable @tab stable @tab stable
539 @item dns @tab stable @tab stable @tab stable
540 @item dv @tab testing @tab testing @tab n/a
541 @item exit @tab testing @tab n/a @tab n/a
542 @item fragmentation @tab stable @tab n/a @tab stable
543 @item fs @tab stable @tab stable @tab stable
544 @item gns @tab stable @tab stable @tab stable
545 @item hello @tab n/a @tab n/a @tab testing
546 @item hostlist @tab stable @tab stable @tab n/a
547 @item identity @tab stable @tab stable @tab n/a
548 @item multicast @tab experimental @tab experimental @tab experimental
549 @item mysql @tab stable @tab n/a @tab stable
550 @item namestore @tab n/a @tab stable @tab stable
551 @item nat @tab n/a @tab n/a @tab stable
552 @item nse @tab stable @tab stable @tab stable
553 @item peerinfo @tab n/a @tab stable @tab stable
554 @item psyc @tab experimental @tab experimental @tab experimental
555 @item pt @tab n/a @tab n/a @tab n/a
556 @item regex @tab stable @tab stable @tab stable
557 @item revocation @tab stable @tab stable @tab stable
558 @item social @tab experimental @tab experimental @tab experimental
559 @item statistics @tab n/a @tab stable @tab stable
560 @item testbed @tab n/a @tab testing @tab testing
561 @item testing @tab n/a @tab n/a @tab testing
562 @item topology @tab n/a @tab n/a @tab n/a
563 @item transport @tab stable @tab stable @tab stable
564 @item tun @tab n/a @tab n/a @tab stable
565 @item vpn @tab testing @tab n/a @tab n/a
566 @end multitable
567
568 Here is a rough explanation of the values:
569
570 @table @samp
571 @item stable
572 No incompatible changes are planned at this time; for IPC/APIs, if
573 there are incompatible changes, they will be minor and might only require
574 minimal changes to existing code; for P2P, changes will be avoided if at
575 all possible for the 0.10.x-series
576
577 @item testing
578 No incompatible changes are
579 planned at this time, but the code is still known to be in flux; so while
580 we have no concrete plans, our expectation is that there will still be
581 minor modifications; for P2P, changes will likely be extensions that
582 should not break existing code
583
584 @item unstable
585 Changes are planned and will happen; however, they
586 will not be totally radical and the result should still resemble what is
587 there now; nevertheless, anticipated changes will break protocol/API
588 compatibility
589
590 @item experimental
591 Changes are planned and the result may look nothing like
592 what the API/protocol looks like today
593
594 @item unknown
595 Someone should think about where this subsystem headed
596
597 @item n/a
598 This subsystem does not have an API/IPC-protocol/P2P-protocol
599 @end table
600
601 @c ***********************************************************************
602 @node Naming conventions and coding style guide
603 @section Naming conventions and coding style guide
604
605 Here you can find some rules to help you write code for GNUnet.
606
607 @c ***********************************************************************
608 @menu
609 * Naming conventions::
610 * Coding style::
611 @end menu
612
613 @node Naming conventions
614 @subsection Naming conventions
615
616
617 @c ***********************************************************************
618 @menu
619 * include files::
620 * binaries::
621 * logging::
622 * configuration::
623 * exported symbols::
624 * private (library-internal) symbols (including structs and macros)::
625 * testcases::
626 * performance tests::
627 * src/ directories::
628 @end menu
629
630 @node include files
631 @subsubsection include files
632
633 @itemize @bullet
634 @item _lib: library without need for a process
635 @item _service: library that needs a service process
636 @item _plugin: plugin definition
637 @item _protocol: structs used in network protocol
638 @item exceptions:
639 @itemize @bullet
640 @item gnunet_config.h --- generated
641 @item platform.h --- first included
642 @item plibc.h --- external library
643 @item gnunet_common.h --- fundamental routines
644 @item gnunet_directories.h --- generated
645 @item gettext.h --- external library
646 @end itemize
647 @end itemize
648
649 @c ***********************************************************************
650 @node binaries
651 @subsubsection binaries
652
653 @itemize @bullet
654 @item gnunet-service-xxx: service process (has listen socket)
655 @item gnunet-daemon-xxx: daemon process (no listen socket)
656 @item gnunet-helper-xxx[-yyy]: SUID helper for module xxx
657 @item gnunet-yyy: command-line tool for end-users
658 @item libgnunet_plugin_xxx_yyy.so: plugin for API xxx
659 @item libgnunetxxx.so: library for API xxx
660 @end itemize
661
662 @c ***********************************************************************
663 @node logging
664 @subsubsection logging
665
666 @itemize @bullet
667 @item services and daemons use their directory name in
668 @code{GNUNET_log_setup} (i.e. 'core') and log using
669 plain 'GNUNET_log'.
670 @item command-line tools use their full name in
671 @code{GNUNET_log_setup} (i.e. 'gnunet-publish') and log using
672 plain 'GNUNET_log'.
673 @item service access libraries log using
674 '@code{GNUNET_log_from}' and use '@code{DIRNAME-api}' for the
675 component (i.e. 'core-api')
676 @item pure libraries (without associated service) use
677 '@code{GNUNET_log_from}' with the component set to their
678 library name (without lib or '@file{.so}'),
679 which should also be their directory name (i.e. '@file{nat}')
680 @item plugins should use '@code{GNUNET_log_from}'
681 with the directory name and the plugin name combined to produce
682 the component name (i.e. 'transport-tcp').
683 @item logging should be unified per-file by defining a
684 @code{LOG} macro with the appropriate arguments,
685 along these lines:
686
687 @example
688 #define LOG(kind,...)
689 GNUNET_log_from (kind, "example-api",__VA_ARGS__)
690 @end example
691
692 @end itemize
693
694 @c ***********************************************************************
695 @node configuration
696 @subsubsection configuration
697
698 @itemize @bullet
699 @item paths (that are substituted in all filenames) are in PATHS
700 (have as few as possible)
701 @item all options for a particular module (@file{src/MODULE})
702 are under @code{[MODULE]}
703 @item options for a plugin of a module
704 are under @code{[MODULE-PLUGINNAME]}
705 @end itemize
706
707 @c ***********************************************************************
708 @node exported symbols
709 @subsubsection exported symbols
710
711 @itemize @bullet
712 @item must start with @code{GNUNET_modulename_} and be defined in
713 @file{modulename.c}
714 @item exceptions: those defined in @file{gnunet_common.h}
715 @end itemize
716
717 @c ***********************************************************************
718 @node private (library-internal) symbols (including structs and macros)
719 @subsubsection private (library-internal) symbols (including structs and macros)
720
721 @itemize @bullet
722 @item must NOT start with any prefix
723 @item must not be exported in a way that linkers could use them or@ other
724 libraries might see them via headers; they must be either
725 declared/defined in C source files or in headers that are in the
726 respective directory under @file{src/modulename/} and NEVER be declared
727 in @file{src/include/}.
728 @end itemize
729
730 @node testcases
731 @subsubsection testcases
732
733 @itemize @bullet
734 @item must be called @file{test_module-under-test_case-description.c}
735 @item "case-description" maybe omitted if there is only one test
736 @end itemize
737
738 @c ***********************************************************************
739 @node performance tests
740 @subsubsection performance tests
741
742 @itemize @bullet
743 @item must be called @file{perf_module-under-test_case-description.c}
744 @item "case-description" maybe omitted if there is only one performance
745 test
746 @item Must only be run if @code{HAVE_BENCHMARKS} is satisfied
747 @end itemize
748
749 @c ***********************************************************************
750 @node src/ directories
751 @subsubsection src/ directories
752
753 @itemize @bullet
754 @item gnunet-NAME: end-user applications (i.e., gnunet-search, gnunet-arm)
755 @item gnunet-service-NAME: service processes with accessor library (i.e.,
756 gnunet-service-arm)
757 @item libgnunetNAME: accessor library (_service.h-header) or standalone
758 library (_lib.h-header)
759 @item gnunet-daemon-NAME: daemon process without accessor library (i.e.,
760 gnunet-daemon-hostlist) and no GNUnet management port
761 @item libgnunet_plugin_DIR_NAME: loadable plugins (i.e.,
762 libgnunet_plugin_transport_tcp)
763 @end itemize
764
765 @cindex Coding style
766 @node Coding style
767 @subsection Coding style
768
769 @c XXX: Adjust examples to GNU Standards!
770 @itemize @bullet
771 @item We follow the GNU Coding Standards (@pxref{Top, The GNU Coding Standards,, standards, The GNU Coding Standards});
772 @item Indentation is done with spaces, two per level, no tabs;
773 @item C99 struct initialization is fine;
774 @item declare only one variable per line, for example:
775
776 @noindent
777 instead of
778
779 @example
780 int i,j;
781 @end example
782
783 @noindent
784 write:
785
786 @example
787 int i;
788 int j;
789 @end example
790
791 @c TODO: include actual example from a file in source
792
793 @noindent
794 This helps keep diffs small and forces developers to think precisely about
795 the type of every variable.
796 Note that @code{char *} is different from @code{const char*} and
797 @code{int} is different from @code{unsigned int} or @code{uint32_t}.
798 Each variable type should be chosen with care.
799
800 @item While @code{goto} should generally be avoided, having a
801 @code{goto} to the end of a function to a block of clean up
802 statements (free, close, etc.) can be acceptable.
803
804 @item Conditions should be written with constants on the left (to avoid
805 accidental assignment) and with the 'true' target being either the
806 'error' case or the significantly simpler continuation. For example:
807
808 @example
809 if (0 != stat ("filename," &sbuf)) @{
810   error();
811  @}
812  else @{
813    /* handle normal case here */
814  @}
815 @end example
816
817 @noindent
818 instead of
819
820 @example
821 if (stat ("filename," &sbuf) == 0) @{
822   /* handle normal case here */
823  @} else @{
824   error();
825  @}
826 @end example
827
828 @noindent
829 If possible, the error clause should be terminated with a 'return' (or
830 'goto' to some cleanup routine) and in this case, the 'else' clause
831 should be omitted:
832
833 @example
834 if (0 != stat ("filename," &sbuf)) @{
835   error();
836   return;
837  @}
838 /* handle normal case here */
839 @end example
840
841 This serves to avoid deep nesting. The 'constants on the left' rule
842 applies to all constants (including. @code{GNUNET_SCHEDULER_NO_TASK}),
843 NULL, and enums). With the two above rules (constants on left, errors in
844 'true' branch), there is only one way to write most branches correctly.
845
846 @item Combined assignments and tests are allowed if they do not hinder
847 code clarity. For example, one can write:
848
849 @example
850 if (NULL == (value = lookup_function())) @{
851   error();
852   return;
853  @}
854 @end example
855
856 @item Use @code{break} and @code{continue} wherever possible to avoid
857 deep(er) nesting. Thus, we would write:
858
859 @example
860 next = head;
861 while (NULL != (pos = next)) @{
862   next = pos->next;
863   if (! should_free (pos))
864     continue;
865   GNUNET_CONTAINER_DLL_remove (head, tail, pos);
866   GNUNET_free (pos);
867  @}
868 @end example
869
870 instead of
871
872 @example
873 next = head; while (NULL != (pos = next)) @{
874   next = pos->next;
875   if (should_free (pos)) @{
876     /* unnecessary nesting! */
877     GNUNET_CONTAINER_DLL_remove (head, tail, pos);
878     GNUNET_free (pos);
879    @}
880   @}
881 @end example
882
883 @item We primarily use @code{for} and @code{while} loops.
884 A @code{while} loop is used if the method for advancing in the loop is
885 not a straightforward increment operation. In particular, we use:
886
887 @example
888 next = head;
889 while (NULL != (pos = next))
890 @{
891   next = pos->next;
892   if (! should_free (pos))
893     continue;
894   GNUNET_CONTAINER_DLL_remove (head, tail, pos);
895   GNUNET_free (pos);
896 @}
897 @end example
898
899 to free entries in a list (as the iteration changes the structure of the
900 list due to the free; the equivalent @code{for} loop does no longer
901 follow the simple @code{for} paradigm of @code{for(INIT;TEST;INC)}).
902 However, for loops that do follow the simple @code{for} paradigm we do
903 use @code{for}, even if it involves linked lists:
904
905 @example
906 /* simple iteration over a linked list */
907 for (pos = head;
908      NULL != pos;
909      pos = pos->next)
910 @{
911    use (pos);
912 @}
913 @end example
914
915
916 @item The first argument to all higher-order functions in GNUnet must be
917 declared to be of type @code{void *} and is reserved for a closure. We do
918 not use inner functions, as trampolines would conflict with setups that
919 use non-executable stacks.
920 The first statement in a higher-order function, which unusually should
921 be part of the variable declarations, should assign the
922 @code{cls} argument to the precise expected type. For example:
923
924 @example
925 int callback (void *cls, char *args) @{
926   struct Foo *foo = cls;
927   int other_variables;
928
929    /* rest of function */
930 @}
931 @end example
932
933
934 @item It is good practice to write complex @code{if} expressions instead
935 of using deeply nested @code{if} statements. However, except for addition
936 and multiplication, all operators should use parens. This is fine:
937
938 @example
939 if ( (1 == foo) || ((0 == bar) && (x != y)) )
940   return x;
941 @end example
942
943
944 However, this is not:
945
946 @example
947 if (1 == foo)
948   return x;
949 if (0 == bar && x != y)
950   return x;
951 @end example
952
953 @noindent
954 Note that splitting the @code{if} statement above is debateable as the
955 @code{return x} is a very trivial statement. However, once the logic after
956 the branch becomes more complicated (and is still identical), the "or"
957 formulation should be used for sure.
958
959 @item There should be two empty lines between the end of the function and
960 the comments describing the following function. There should be a single
961 empty line after the initial variable declarations of a function. If a
962 function has no local variables, there should be no initial empty line. If
963 a long function consists of several complex steps, those steps might be
964 separated by an empty line (possibly followed by a comment describing the
965 following step). The code should not contain empty lines in arbitrary
966 places; if in doubt, it is likely better to NOT have an empty line (this
967 way, more code will fit on the screen).
968 @end itemize
969
970 @c ***********************************************************************
971 @node Build-system
972 @section Build-system
973
974 If you have code that is likely not to compile or build rules you might
975 want to not trigger for most developers, use @code{if HAVE_EXPERIMENTAL}
976 in your @file{Makefile.am}.
977 Then it is OK to (temporarily) add non-compiling (or known-to-not-port)
978 code.
979
980 If you want to compile all testcases but NOT run them, run configure with
981 the @code{--enable-test-suppression} option.
982
983 If you want to run all testcases, including those that take a while, run
984 configure with the @code{--enable-expensive-testcases} option.
985
986 If you want to compile and run benchmarks, run configure with the
987 @code{--enable-benchmarks} option.
988
989 If you want to obtain code coverage results, run configure with the
990 @code{--enable-coverage} option and run the @file{coverage.sh} script in
991 the @file{contrib/} directory.
992
993 @cindex gnunet-ext
994 @node Developing extensions for GNUnet using the gnunet-ext template
995 @section Developing extensions for GNUnet using the gnunet-ext template
996
997 For developers who want to write extensions for GNUnet we provide the
998 gnunet-ext template to provide an easy to use skeleton.
999
1000 gnunet-ext contains the build environment and template files for the
1001 development of GNUnet services, command line tools, APIs and tests.
1002
1003 First of all you have to obtain gnunet-ext from git:
1004
1005 @example
1006 git clone https://gnunet.org/git/gnunet-ext.git
1007 @end example
1008
1009 The next step is to bootstrap and configure it. For configure you have to
1010 provide the path containing GNUnet with
1011 @code{--with-gnunet=/path/to/gnunet} and the prefix where you want the
1012 install the extension using @code{--prefix=/path/to/install}:
1013
1014 @example
1015 ./bootstrap
1016 ./configure --prefix=/path/to/install --with-gnunet=/path/to/gnunet
1017 @end example
1018
1019 When your GNUnet installation is not included in the default linker search
1020 path, you have to add @code{/path/to/gnunet} to the file
1021 @file{/etc/ld.so.conf} and run @code{ldconfig} or your add it to the
1022 environmental variable @code{LD_LIBRARY_PATH} by using
1023
1024 @example
1025 export LD_LIBRARY_PATH=/path/to/gnunet/lib
1026 @end example
1027
1028 @cindex writing testcases
1029 @node Writing testcases
1030 @section Writing testcases
1031
1032 Ideally, any non-trivial GNUnet code should be covered by automated
1033 testcases. Testcases should reside in the same place as the code that is
1034 being tested. The name of source files implementing tests should begin
1035 with @code{test_} followed by the name of the file that contains
1036 the code that is being tested.
1037
1038 Testcases in GNUnet should be integrated with the autotools build system.
1039 This way, developers and anyone building binary packages will be able to
1040 run all testcases simply by running @code{make check}. The final
1041 testcases shipped with the distribution should output at most some brief
1042 progress information and not display debug messages by default. The
1043 success or failure of a testcase must be indicated by returning zero
1044 (success) or non-zero (failure) from the main method of the testcase.
1045 The integration with the autotools is relatively straightforward and only
1046 requires modifications to the @file{Makefile.am} in the directory
1047 containing the testcase. For a testcase testing the code in @file{foo.c}
1048 the @file{Makefile.am} would contain the following lines:
1049
1050 @example
1051 check_PROGRAMS = test_foo
1052 TESTS = $(check_PROGRAMS)
1053 test_foo_SOURCES = test_foo.c
1054 test_foo_LDADD = $(top_builddir)/src/util/libgnunetutil.la
1055 @end example
1056
1057 Naturally, other libraries used by the testcase may be specified in the
1058 @code{LDADD} directive as necessary.
1059
1060 Often testcases depend on additional input files, such as a configuration
1061 file. These support files have to be listed using the @code{EXTRA_DIST}
1062 directive in order to ensure that they are included in the distribution.
1063
1064 Example:
1065
1066 @example
1067 EXTRA_DIST = test_foo_data.conf
1068 @end example
1069
1070 Executing @code{make check} will run all testcases in the current
1071 directory and all subdirectories. Testcases can be compiled individually
1072 by running @code{make test_foo} and then invoked directly using
1073 @code{./test_foo}. Note that due to the use of plugins in GNUnet, it is
1074 typically necessary to run @code{make install} before running any
1075 testcases. Thus the canonical command @code{make check install} has to be
1076 changed to @code{make install check} for GNUnet.
1077
1078 @cindex TESTING library
1079 @node TESTING library
1080 @section TESTING library
1081
1082 The TESTING library is used for writing testcases which involve starting a
1083 single or multiple peers. While peers can also be started by testcases
1084 using the ARM subsystem, using TESTING library provides an elegant way to
1085 do this. The configurations of the peers are auto-generated from a given
1086 template to have non-conflicting port numbers ensuring that peers'
1087 services do not run into bind errors. This is achieved by testing ports'
1088 availability by binding a listening socket to them before allocating them
1089 to services in the generated configurations.
1090
1091 An another advantage while using TESTING is that it shortens the testcase
1092 startup time as the hostkeys for peers are copied from a pre-computed set
1093 of hostkeys instead of generating them at peer startup which may take a
1094 considerable amount of time when starting multiple peers or on an embedded
1095 processor.
1096
1097 TESTING also allows for certain services to be shared among peers. This
1098 feature is invaluable when testing with multiple peers as it helps to
1099 reduce the number of services run per each peer and hence the total
1100 number of processes run per testcase.
1101
1102 TESTING library only handles creating, starting and stopping peers.
1103 Features useful for testcases such as connecting peers in a topology are
1104 not available in TESTING but are available in the TESTBED subsystem.
1105 Furthermore, TESTING only creates peers on the localhost, however by
1106 using TESTBED testcases can benefit from creating peers across multiple
1107 hosts.
1108
1109 @menu
1110 * API::
1111 * Finer control over peer stop::
1112 * Helper functions::
1113 * Testing with multiple processes::
1114 @end menu
1115
1116 @cindex TESTING API
1117 @node API
1118 @subsection API
1119
1120 TESTING abstracts a group of peers as a TESTING system. All peers in a
1121 system have common hostname and no two services of these peers have a
1122 same port or a UNIX domain socket path.
1123
1124 TESTING system can be created with the function
1125 @code{GNUNET_TESTING_system_create()} which returns a handle to the
1126 system. This function takes a directory path which is used for generating
1127 the configurations of peers, an IP address from which connections to the
1128 peers' services should be allowed, the hostname to be used in peers'
1129 configuration, and an array of shared service specifications of type
1130 @code{struct GNUNET_TESTING_SharedService}.
1131
1132 The shared service specification must specify the name of the service to
1133 share, the configuration pertaining to that shared service and the
1134 maximum number of peers that are allowed to share a single instance of
1135 the shared service.
1136
1137 TESTING system created with @code{GNUNET_TESTING_system_create()} chooses
1138 ports from the default range @code{12000} - @code{56000} while
1139 auto-generating configurations for peers.
1140 This range can be customised with the function
1141 @code{GNUNET_TESTING_system_create_with_portrange()}. This function is
1142 similar to @code{GNUNET_TESTING_system_create()} except that it take 2
1143 additional parameters --- the start and end of the port range to use.
1144
1145 A TESTING system is destroyed with the funciton
1146 @code{GNUNET_TESTING_system_destory()}. This function takes the handle of
1147 the system and a flag to remove the files created in the directory used
1148 to generate configurations.
1149
1150 A peer is created with the function
1151 @code{GNUNET_TESTING_peer_configure()}. This functions takes the system
1152 handle, a configuration template from which the configuration for the peer
1153 is auto-generated and the index from where the hostkey for the peer has to
1154 be copied from. When successfull, this function returs a handle to the
1155 peer which can be used to start and stop it and to obtain the identity of
1156 the peer. If unsuccessful, a NULL pointer is returned with an error
1157 message. This function handles the generated configuration to have
1158 non-conflicting ports and paths.
1159
1160 Peers can be started and stopped by calling the functions
1161 @code{GNUNET_TESTING_peer_start()} and @code{GNUNET_TESTING_peer_stop()}
1162 respectively. A peer can be destroyed by calling the function
1163 @code{GNUNET_TESTING_peer_destroy}. When a peer is destroyed, the ports
1164 and paths in allocated in its configuration are reclaimed for usage in new
1165 peers.
1166
1167 @c ***********************************************************************
1168 @node Finer control over peer stop
1169 @subsection Finer control over peer stop
1170
1171 Using @code{GNUNET_TESTING_peer_stop()} is normally fine for testcases.
1172 However, calling this function for each peer is inefficient when trying to
1173 shutdown multiple peers as this function sends the termination signal to
1174 the given peer process and waits for it to terminate. It would be faster
1175 in this case to send the termination signals to the peers first and then
1176 wait on them. This is accomplished by the functions
1177 @code{GNUNET_TESTING_peer_kill()} which sends a termination signal to the
1178 peer, and the function @code{GNUNET_TESTING_peer_wait()} which waits on
1179 the peer.
1180
1181 Further finer control can be achieved by choosing to stop a peer
1182 asynchronously with the function @code{GNUNET_TESTING_peer_stop_async()}.
1183 This function takes a callback parameter and a closure for it in addition
1184 to the handle to the peer to stop. The callback function is called with
1185 the given closure when the peer is stopped. Using this function
1186 eliminates blocking while waiting for the peer to terminate.
1187
1188 An asynchronous peer stop can be cancelled by calling the function
1189 @code{GNUNET_TESTING_peer_stop_async_cancel()}. Note that calling this
1190 function does not prevent the peer from terminating if the termination
1191 signal has already been sent to it. It does, however, cancels the
1192 callback to be called when the peer is stopped.
1193
1194 @c ***********************************************************************
1195 @node Helper functions
1196 @subsection Helper functions
1197
1198 Most of the testcases can benefit from an abstraction which configures a
1199 peer and starts it. This is provided by the function
1200 @code{GNUNET_TESTING_peer_run()}. This function takes the testing
1201 directory pathname, a configuration template, a callback and its closure.
1202 This function creates a peer in the given testing directory by using the
1203 configuration template, starts the peer and calls the given callback with
1204 the given closure.
1205
1206 The function @code{GNUNET_TESTING_peer_run()} starts the ARM service of
1207 the peer which starts the rest of the configured services. A similar
1208 function @code{GNUNET_TESTING_service_run} can be used to just start a
1209 single service of a peer. In this case, the peer's ARM service is not
1210 started; instead, only the given service is run.
1211
1212 @c ***********************************************************************
1213 @node Testing with multiple processes
1214 @subsection Testing with multiple processes
1215
1216 When testing GNUnet, the splitting of the code into a services and clients
1217 often complicates testing. The solution to this is to have the testcase
1218 fork @code{gnunet-service-arm}, ask it to start the required server and
1219 daemon processes and then execute appropriate client actions (to test the
1220 client APIs or the core module or both). If necessary, multiple ARM
1221 services can be forked using different ports (!) to simulate a network.
1222 However, most of the time only one ARM process is needed. Note that on
1223 exit, the testcase should shutdown ARM with a @code{TERM} signal (to give
1224 it the chance to cleanly stop its child processes).
1225
1226 The following code illustrates spawning and killing an ARM process from a
1227 testcase:
1228
1229 @example
1230 static void run (void *cls,
1231                  char *const *args,
1232                  const char *cfgfile,
1233                  const struct GNUNET_CONFIGURATION_Handle *cfg) @{
1234   struct GNUNET_OS_Process *arm_pid;
1235   arm_pid = GNUNET_OS_start_process (NULL,
1236                                      NULL,
1237                                      "gnunet-service-arm",
1238                                      "gnunet-service-arm",
1239                                      "-c",
1240                                      cfgname,
1241                                      NULL);
1242   /* do real test work here */
1243   if (0 != GNUNET_OS_process_kill (arm_pid, SIGTERM))
1244     GNUNET_log_strerror
1245       (GNUNET_ERROR_TYPE_WARNING, "kill");
1246   GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (arm_pid));
1247   GNUNET_OS_process_close (arm_pid); @}
1248
1249 GNUNET_PROGRAM_run (argc, argv,
1250                     "NAME-OF-TEST",
1251                     "nohelp",
1252                     options,
1253                     &run,
1254                     cls);
1255 @end example
1256
1257
1258 An alternative way that works well to test plugins is to implement a
1259 mock-version of the environment that the plugin expects and then to
1260 simply load the plugin directly.
1261
1262 @c ***********************************************************************
1263 @node Performance regression analysis with Gauger
1264 @section Performance regression analysis with Gauger
1265
1266 To help avoid performance regressions, GNUnet uses Gauger. Gauger is a
1267 simple logging tool that allows remote hosts to send performance data to
1268 a central server, where this data can be analyzed and visualized. Gauger
1269 shows graphs of the repository revisions and the performace data recorded
1270 for each revision, so sudden performance peaks or drops can be identified
1271 and linked to a specific revision number.
1272
1273 In the case of GNUnet, the buildbots log the performance data obtained
1274 during the tests after each build. The data can be accesed on GNUnet's
1275 Gauger page.
1276
1277 The menu on the left allows to select either the results of just one
1278 build bot (under "Hosts") or review the data from all hosts for a given
1279 test result (under "Metrics"). In case of very different absolute value
1280 of the results, for instance arm vs. amd64 machines, the option
1281 "Normalize" on a metric view can help to get an idea about the
1282 performance evolution across all hosts.
1283
1284 Using Gauger in GNUnet and having the performance of a module tracked over
1285 time is very easy. First of course, the testcase must generate some
1286 consistent metric, which makes sense to have logged. Highly volatile or
1287 random dependant metrics probably are not ideal candidates for meaningful
1288 regression detection.
1289
1290 To start logging any value, just include @code{gauger.h} in your testcase
1291 code. Then, use the macro @code{GAUGER()} to make the Buildbots log
1292 whatever value is of interest for you to @code{gnunet.org}'s Gauger
1293 server. No setup is necessary as most Buildbots have already everything
1294 in place and new metrics are created on demand. To delete a metric, you
1295 need to contact a member of the GNUnet development team (a file will need
1296 to be removed manually from the respective directory).
1297
1298 The code in the test should look like this:
1299
1300 @example
1301 [other includes]
1302 #include <gauger.h>
1303
1304 int main (int argc, char *argv[]) @{
1305
1306   [run test, generate data]
1307     GAUGER("YOUR_MODULE",
1308            "METRIC_NAME",
1309            (float)value,
1310            "UNIT"); @}
1311 @end example
1312
1313 Where:
1314
1315 @table @asis
1316
1317 @item @strong{YOUR_MODULE} is a category in the gauger page and should be
1318 the name of the module or subsystem like "Core" or "DHT"
1319 @item @strong{METRIC} is
1320 the name of the metric being collected and should be concise and
1321 descriptive, like "PUT operations in sqlite-datastore".
1322 @item @strong{value} is the value
1323 of the metric that is logged for this run.
1324 @item @strong{UNIT} is the unit in
1325 which the value is measured, for instance "kb/s" or "kb of RAM/node".
1326 @end table
1327
1328 If you wish to use Gauger for your own project, you can grab a copy of the
1329 latest stable release or check out Gauger's Subversion repository.
1330
1331 @cindex TESTBED Subsystem
1332 @node TESTBED Subsystem
1333 @section TESTBED Subsystem
1334
1335 The TESTBED subsystem facilitates testing and measuring of multi-peer
1336 deployments on a single host or over multiple hosts.
1337
1338 The architecture of the testbed module is divided into the following:
1339 @itemize @bullet
1340
1341 @item Testbed API: An API which is used by the testing driver programs. It
1342 provides with functions for creating, destroying, starting, stopping
1343 peers, etc.
1344
1345 @item Testbed service (controller): A service which is started through the
1346 Testbed API. This service handles operations to create, destroy, start,
1347 stop peers, connect them, modify their configurations.
1348
1349 @item Testbed helper: When a controller has to be started on a host, the
1350 testbed API starts the testbed helper on that host which in turn starts
1351 the controller. The testbed helper receives a configuration for the
1352 controller through its stdin and changes it to ensure the controller
1353 doesn't run into any port conflict on that host.
1354 @end itemize
1355
1356
1357 The testbed service (controller) is different from the other GNUnet
1358 services in that it is not started by ARM and is not supposed to be run
1359 as a daemon. It is started by the testbed API through a testbed helper.
1360 In a typical scenario involving multiple hosts, a controller is started
1361 on each host. Controllers take up the actual task of creating peers,
1362 starting and stopping them on the hosts they run.
1363
1364 While running deployments on a single localhost the testbed API starts the
1365 testbed helper directly as a child process. When running deployments on
1366 remote hosts the testbed API starts Testbed Helpers on each remote host
1367 through remote shell. By default testbed API uses SSH as a remote shell.
1368 This can be changed by setting the environmental variable
1369 GNUNET_TESTBED_RSH_CMD to the required remote shell program. This
1370 variable can also contain parameters which are to be passed to the remote
1371 shell program. For e.g:
1372
1373 @example
1374 export GNUNET_TESTBED_RSH_CMD="ssh -o BatchMode=yes \
1375 -o NoHostAuthenticationForLocalhost=yes %h"
1376 @end example
1377
1378 Substitutions are allowed in the command string above,
1379 this allows for substitutions through placemarks which begin with a `%'.
1380 At present the following substitutions are supported
1381
1382 @itemize @bullet
1383 @item %h: hostname
1384 @item %u: username
1385 @item %p: port
1386 @end itemize
1387
1388 Note that the substitution placemark is replaced only when the
1389 corresponding field is available and only once. Specifying
1390
1391 @example
1392 %u@@%h
1393 @end example
1394
1395 doesn't work either. If you want to user username substitutions for
1396 @command{SSH}, use the argument @code{-l} before the
1397 username substitution.
1398
1399 For example:
1400 @example
1401 ssh -l %u -p %p %h
1402 @end example
1403
1404 The testbed API and the helper communicate through the helpers stdin and
1405 stdout. As the helper is started through a remote shell on remote hosts
1406 any output messages from the remote shell interfere with the communication
1407 and results in a failure while starting the helper. For this reason, it is
1408 suggested to use flags to make the remote shells produce no output
1409 messages and to have password-less logins. The default remote shell, SSH,
1410 the default options are:
1411
1412 @example
1413 -o BatchMode=yes -o NoHostBasedAuthenticationForLocalhost=yes"
1414 @end example
1415
1416 Password-less logins should be ensured by using SSH keys.
1417
1418 Since the testbed API executes the remote shell as a non-interactive
1419 shell, certain scripts like .bashrc, .profiler may not be executed. If
1420 this is the case testbed API can be forced to execute an interactive
1421 shell by setting up the environmental variable
1422 @code{GNUNET_TESTBED_RSH_CMD_SUFFIX} to a shell program.
1423
1424 An example could be:
1425
1426 @example
1427 export GNUNET_TESTBED_RSH_CMD_SUFFIX="sh -lc"
1428 @end example
1429
1430 The testbed API will then execute the remote shell program as:
1431
1432 @example
1433 $GNUNET_TESTBED_RSH_CMD -p $port $dest $GNUNET_TESTBED_RSH_CMD_SUFFIX \
1434 gnunet-helper-testbed
1435 @end example
1436
1437 On some systems, problems may arise while starting testbed helpers if
1438 GNUnet is installed into a custom location since the helper may not be
1439 found in the standard path. This can be addressed by setting the variable
1440 `@code{HELPER_BINARY_PATH}' to the path of the testbed helper.
1441 Testbed API will then use this path to start helper binaries both
1442 locally and remotely.
1443
1444 Testbed API can accessed by including the
1445 @file{gnunet_testbed_service.h} file and linking with
1446 @code{-lgnunettestbed}.
1447
1448 @c ***********************************************************************
1449 @menu
1450 * Supported Topologies::
1451 * Hosts file format::
1452 * Topology file format::
1453 * Testbed Barriers::
1454 * Automatic large-scale deployment in the PlanetLab testbed::
1455 * TESTBED Caveats::
1456 @end menu
1457
1458 @node Supported Topologies
1459 @subsection Supported Topologies
1460
1461 While testing multi-peer deployments, it is often needed that the peers
1462 are connected in some topology. This requirement is addressed by the
1463 function @code{GNUNET_TESTBED_overlay_connect()} which connects any given
1464 two peers in the testbed.
1465
1466 The API also provides a helper function
1467 @code{GNUNET_TESTBED_overlay_configure_topology()} to connect a given set
1468 of peers in any of the following supported topologies:
1469
1470 @itemize @bullet
1471
1472 @item @code{GNUNET_TESTBED_TOPOLOGY_CLIQUE}: All peers are connected with
1473 each other
1474
1475 @item @code{GNUNET_TESTBED_TOPOLOGY_LINE}: Peers are connected to form a
1476 line
1477
1478 @item @code{GNUNET_TESTBED_TOPOLOGY_RING}: Peers are connected to form a
1479 ring topology
1480
1481 @item @code{GNUNET_TESTBED_TOPOLOGY_2D_TORUS}: Peers are connected to
1482 form a 2 dimensional torus topology. The number of peers may not be a
1483 perfect square, in that case the resulting torus may not have the uniform
1484 poloidal and toroidal lengths
1485
1486 @item @code{GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI}: Topology is generated
1487 to form a random graph. The number of links to be present should be given
1488
1489 @item @code{GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD}: Peers are connected to
1490 form a 2D Torus with some random links among them. The number of random
1491 links are to be given
1492
1493 @item @code{GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD_RING}: Peers are
1494 connected to form a ring with some random links among them. The number of
1495 random links are to be given
1496
1497 @item @code{GNUNET_TESTBED_TOPOLOGY_SCALE_FREE}: Connects peers in a
1498 topology where peer connectivity follows power law - new peers are
1499 connected with high probabililty to well connected peers.
1500 @footnote{See Emergence of Scaling in Random Networks. Science 286,
1501 509-512, 1999
1502 (@uref{https://gnunet.org/git/bibliography.git/plain/docs/emergence_of_scaling_in_random_networks__barabasi_albert_science_286__1999.pdf, pdf})}
1503
1504 @item @code{GNUNET_TESTBED_TOPOLOGY_FROM_FILE}: The topology information
1505 is loaded from a file. The path to the file has to be given.
1506 @xref{Topology file format}, for the format of this file.
1507
1508 @item @code{GNUNET_TESTBED_TOPOLOGY_NONE}: No topology
1509 @end itemize
1510
1511
1512 The above supported topologies can be specified respectively by setting
1513 the variable @code{OVERLAY_TOPOLOGY} to the following values in the
1514 configuration passed to Testbed API functions
1515 @code{GNUNET_TESTBED_test_run()} and
1516 @code{GNUNET_TESTBED_run()}:
1517
1518 @itemize @bullet
1519 @item @code{CLIQUE}
1520 @item @code{RING}
1521 @item @code{LINE}
1522 @item @code{2D_TORUS}
1523 @item @code{RANDOM}
1524 @item @code{SMALL_WORLD}
1525 @item @code{SMALL_WORLD_RING}
1526 @item @code{SCALE_FREE}
1527 @item @code{FROM_FILE}
1528 @item @code{NONE}
1529 @end itemize
1530
1531
1532 Topologies @code{RANDOM}, @code{SMALL_WORLD} and @code{SMALL_WORLD_RING}
1533 require the option @code{OVERLAY_RANDOM_LINKS} to be set to the number of
1534 random links to be generated in the configuration. The option will be
1535 ignored for the rest of the topologies.
1536
1537 Topology @code{SCALE_FREE} requires the options
1538 @code{SCALE_FREE_TOPOLOGY_CAP} to be set to the maximum number of peers
1539 which can connect to a peer and @code{SCALE_FREE_TOPOLOGY_M} to be set to
1540 how many peers a peer should be atleast connected to.
1541
1542 Similarly, the topology @code{FROM_FILE} requires the option
1543 @code{OVERLAY_TOPOLOGY_FILE} to contain the path of the file containing
1544 the topology information. This option is ignored for the rest of the
1545 topologies. @xref{Topology file format}, for the format of this file.
1546
1547 @c ***********************************************************************
1548 @node Hosts file format
1549 @subsection Hosts file format
1550
1551 The testbed API offers the function
1552 @code{GNUNET_TESTBED_hosts_load_from_file()} to load from a given file
1553 details about the hosts which testbed can use for deploying peers.
1554 This function is useful to keep the data about hosts
1555 separate instead of hard coding them in code.
1556
1557 Another helper function from testbed API, @code{GNUNET_TESTBED_run()}
1558 also takes a hosts file name as its parameter. It uses the above
1559 function to populate the hosts data structures and start controllers to
1560 deploy peers.
1561
1562 These functions require the hosts file to be of the following format:
1563 @itemize @bullet
1564 @item Each line is interpreted to have details about a host
1565 @item Host details should include the username to use for logging into the
1566 host, the hostname of the host and the port number to use for the remote
1567 shell program. All thee values should be given.
1568 @item These details should be given in the following format:
1569 @example
1570 <username>@@<hostname>:<port>
1571 @end example
1572 @end itemize
1573
1574 Note that having canonical hostnames may cause problems while resolving
1575 the IP addresses (See this bug). Hence it is advised to provide the hosts'
1576 IP numerical addresses as hostnames whenever possible.
1577
1578 @c ***********************************************************************
1579 @node Topology file format
1580 @subsection Topology file format
1581
1582 A topology file describes how peers are to be connected. It should adhere
1583 to the following format for testbed to parse it correctly.
1584
1585 Each line should begin with the target peer id. This should be followed by
1586 a colon(`:') and origin peer ids seperated by `|'. All spaces except for
1587 newline characters are ignored. The API will then try to connect each
1588 origin peer to the target peer.
1589
1590 For example, the following file will result in 5 overlay connections:
1591 [2->1], [3->1],[4->3], [0->3], [2->0]@
1592 @code{@ 1:2|3@ 3:4| 0@ 0: 2@ }
1593
1594 @c ***********************************************************************
1595 @node Testbed Barriers
1596 @subsection Testbed Barriers
1597
1598 The testbed subsystem's barriers API facilitates coordination among the
1599 peers run by the testbed and the experiment driver. The concept is
1600 similar to the barrier synchronisation mechanism found in parallel
1601 programming or multi-threading paradigms - a peer waits at a barrier upon
1602 reaching it until the barrier is reached by a predefined number of peers.
1603 This predefined number of peers required to cross a barrier is also called
1604 quorum. We say a peer has reached a barrier if the peer is waiting for the
1605 barrier to be crossed. Similarly a barrier is said to be reached if the
1606 required quorum of peers reach the barrier. A barrier which is reached is
1607 deemed as crossed after all the peers waiting on it are notified.
1608
1609 The barriers API provides the following functions:
1610 @itemize @bullet
1611 @item @strong{@code{GNUNET_TESTBED_barrier_init()}:} function to
1612 initialse a barrier in the experiment
1613 @item @strong{@code{GNUNET_TESTBED_barrier_cancel()}:} function to cancel
1614 a barrier which has been initialised before
1615 @item @strong{@code{GNUNET_TESTBED_barrier_wait()}:} function to signal
1616 barrier service that the caller has reached a barrier and is waiting for
1617 it to be crossed
1618 @item @strong{@code{GNUNET_TESTBED_barrier_wait_cancel()}:} function to
1619 stop waiting for a barrier to be crossed
1620 @end itemize
1621
1622
1623 Among the above functions, the first two, namely
1624 @code{GNUNET_TESTBED_barrier_init()} and
1625 @code{GNUNET_TESTBED_barrier_cancel()} are used by experiment drivers. All
1626 barriers should be initialised by the experiment driver by calling
1627 @code{GNUNET_TESTBED_barrier_init()}. This function takes a name to
1628 identify the barrier, the quorum required for the barrier to be crossed
1629 and a notification callback for notifying the experiment driver when the
1630 barrier is crossed. @code{GNUNET_TESTBED_barrier_cancel()} cancels an
1631 initialised barrier and frees the resources allocated for it. This
1632 function can be called upon a initialised barrier before it is crossed.
1633
1634 The remaining two functions @code{GNUNET_TESTBED_barrier_wait()} and
1635 @code{GNUNET_TESTBED_barrier_wait_cancel()} are used in the peer's
1636 processes. @code{GNUNET_TESTBED_barrier_wait()} connects to the local
1637 barrier service running on the same host the peer is running on and
1638 registers that the caller has reached the barrier and is waiting for the
1639 barrier to be crossed. Note that this function can only be used by peers
1640 which are started by testbed as this function tries to access the local
1641 barrier service which is part of the testbed controller service. Calling
1642 @code{GNUNET_TESTBED_barrier_wait()} on an uninitialised barrier results
1643 in failure. @code{GNUNET_TESTBED_barrier_wait_cancel()} cancels the
1644 notification registered by @code{GNUNET_TESTBED_barrier_wait()}.
1645
1646
1647 @c ***********************************************************************
1648 @menu
1649 * Implementation::
1650 @end menu
1651
1652 @node Implementation
1653 @subsubsection Implementation
1654
1655 Since barriers involve coordination between experiment driver and peers,
1656 the barrier service in the testbed controller is split into two
1657 components. The first component responds to the message generated by the
1658 barrier API used by the experiment driver (functions
1659 @code{GNUNET_TESTBED_barrier_init()} and
1660 @code{GNUNET_TESTBED_barrier_cancel()}) and the second component to the
1661 messages generated by barrier API used by peers (functions
1662 @code{GNUNET_TESTBED_barrier_wait()} and
1663 @code{GNUNET_TESTBED_barrier_wait_cancel()}).
1664
1665 Calling @code{GNUNET_TESTBED_barrier_init()} sends a
1666 @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_INIT} message to the master
1667 controller. The master controller then registers a barrier and calls
1668 @code{GNUNET_TESTBED_barrier_init()} for each its subcontrollers. In this
1669 way barrier initialisation is propagated to the controller hierarchy.
1670 While propagating initialisation, any errors at a subcontroller such as
1671 timeout during further propagation are reported up the hierarchy back to
1672 the experiment driver.
1673
1674 Similar to @code{GNUNET_TESTBED_barrier_init()},
1675 @code{GNUNET_TESTBED_barrier_cancel()} propagates
1676 @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_CANCEL} message which causes
1677 controllers to remove an initialised barrier.
1678
1679 The second component is implemented as a separate service in the binary
1680 `gnunet-service-testbed' which already has the testbed controller service.
1681 Although this deviates from the gnunet process architecture of having one
1682 service per binary, it is needed in this case as this component needs
1683 access to barrier data created by the first component. This component
1684 responds to @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_WAIT} messages from
1685 local peers when they call @code{GNUNET_TESTBED_barrier_wait()}. Upon
1686 receiving @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_WAIT} message, the
1687 service checks if the requested barrier has been initialised before and
1688 if it was not initialised, an error status is sent through
1689 @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_STATUS} message to the local
1690 peer and the connection from the peer is terminated. If the barrier is
1691 initialised before, the barrier's counter for reached peers is incremented
1692 and a notification is registered to notify the peer when the barrier is
1693 reached. The connection from the peer is left open.
1694
1695 When enough peers required to attain the quorum send
1696 @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_WAIT} messages, the controller
1697 sends a @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_STATUS} message to its
1698 parent informing that the barrier is crossed. If the controller has
1699 started further subcontrollers, it delays this message until it receives
1700 a similar notification from each of those subcontrollers. Finally, the
1701 barriers API at the experiment driver receives the
1702 @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_STATUS} when the barrier is
1703 reached at all the controllers.
1704
1705 The barriers API at the experiment driver responds to the
1706 @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_STATUS} message by echoing it
1707 back to the master controller and notifying the experiment controller
1708 through the notification callback that a barrier has been crossed. The
1709 echoed @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_STATUS} message is
1710 propagated by the master controller to the controller hierarchy. This
1711 propagation triggers the notifications registered by peers at each of the
1712 controllers in the hierarchy. Note the difference between this downward
1713 propagation of the @code{GNUNET_MESSAGE_TYPE_TESTBED_BARRIER_STATUS}
1714 message from its upward propagation --- the upward propagation is needed
1715 for ensuring that the barrier is reached by all the controllers and the
1716 downward propagation is for triggering that the barrier is crossed.
1717
1718 @cindex PlanetLab testbed
1719 @node Automatic large-scale deployment in the PlanetLab testbed
1720 @subsection Automatic large-scale deployment in the PlanetLab testbed
1721
1722 PlanetLab is a testbed for computer networking and distributed systems
1723 research. It was established in 2002 and as of June 2010 was composed of
1724 1090 nodes at 507 sites worldwide.
1725
1726 To automate the GNUnet we created a set of automation tools to simplify
1727 the large-scale deployment. We provide you a set of scripts you can use
1728 to deploy GNUnet on a set of nodes and manage your installation.
1729
1730 Please also check @uref{https://gnunet.org/installation-fedora8-svn} and
1731 @uref{https://gnunet.org/installation-fedora12-svn} to find detailled
1732 instructions how to install GNUnet on a PlanetLab node.
1733
1734
1735 @c ***********************************************************************
1736 @menu
1737 * PlanetLab Automation for Fedora8 nodes::
1738 * Install buildslave on PlanetLab nodes running fedora core 8::
1739 * Setup a new PlanetLab testbed using GPLMT::
1740 * Why do i get an ssh error when using the regex profiler?::
1741 @end menu
1742
1743 @node PlanetLab Automation for Fedora8 nodes
1744 @subsubsection PlanetLab Automation for Fedora8 nodes
1745
1746 @c ***********************************************************************
1747 @node Install buildslave on PlanetLab nodes running fedora core 8
1748 @subsubsection Install buildslave on PlanetLab nodes running fedora core 8
1749 @c ** Actually this is a subsubsubsection, but must be fixed differently
1750 @c ** as subsubsection is the lowest.
1751
1752 Since most of the PlanetLab nodes are running the very old Fedora core 8
1753 image, installing the buildslave software is quite some pain. For our
1754 PlanetLab testbed we figured out how to install the buildslave software
1755 best.
1756
1757 @c This is a vvery terrible way to suggest installing software.
1758 @c FIXME: Is there an official, safer way instead of blind-piping a
1759 @c script?
1760 @c FIXME: Use newer pypi URLs below.
1761 Install Distribute for Python:
1762
1763 @example
1764 curl http://python-distribute.org/distribute_setup.py | sudo python
1765 @end example
1766
1767 Install Distribute for zope.interface <= 3.8.0 (4.0 and 4.0.1 will not
1768 work):
1769
1770 @example
1771 export PYPI=@value{PYPI-URL}
1772 wget $PYPI/z/zope.interface/zope.interface-3.8.0.tar.gz
1773 tar zvfz zope.interface-3.8.0.tar.gz
1774 cd zope.interface-3.8.0
1775 sudo python setup.py install
1776 @end example
1777
1778 Install the buildslave software (0.8.6 was the latest version):
1779
1780 @example
1781 export GCODE="http://buildbot.googlecode.com/files"
1782 wget $GCODE/buildbot-slave-0.8.6p1.tar.gz
1783 tar xvfz buildbot-slave-0.8.6p1.tar.gz
1784 cd buildslave-0.8.6p1
1785 sudo python setup.py install
1786 @end example
1787
1788 The setup will download the matching twisted package and install it.
1789 It will also try to install the latest version of zope.interface which
1790 will fail to install. Buildslave will work anyway since version 3.8.0
1791 was installed before!
1792
1793 @c ***********************************************************************
1794 @node Setup a new PlanetLab testbed using GPLMT
1795 @subsubsection Setup a new PlanetLab testbed using GPLMT
1796
1797 @itemize @bullet
1798 @item Get a new slice and assign nodes
1799 Ask your PlanetLab PI to give you a new slice and assign the nodes you
1800 need
1801 @item Install a buildmaster
1802 You can stick to the buildbot documentation:@
1803 @uref{http://buildbot.net/buildbot/docs/current/manual/installation.html}
1804 @item Install the buildslave software on all nodes
1805 To install the buildslave on all nodes assigned to your slice you can use
1806 the tasklist @code{install_buildslave_fc8.xml} provided with GPLMT:
1807
1808 @example
1809 ./gplmt.py -c contrib/tumple_gnunet.conf -t \
1810 contrib/tasklists/install_buildslave_fc8.xml -a -p <planetlab password>
1811 @end example
1812
1813 @item Create the buildmaster configuration and the slave setup commands
1814
1815 The master and the and the slaves have need to have credentials and the
1816 master has to have all nodes configured. This can be done with the
1817 @file{create_buildbot_configuration.py} script in the @file{scripts}
1818 directory.
1819
1820 This scripts takes a list of nodes retrieved directly from PlanetLab or
1821 read from a file and a configuration template and creates:
1822
1823 @itemize @bullet
1824 @item a tasklist which can be executed with gplmt to setup the slaves
1825 @item a master.cfg file containing a PlanetLab nodes
1826 @end itemize
1827
1828 A configuration template is included in the <contrib>, most important is
1829 that the script replaces the following tags in the template:
1830
1831 %GPLMT_BUILDER_DEFINITION :@ GPLMT_BUILDER_SUMMARY@ GPLMT_SLAVES@
1832 %GPLMT_SCHEDULER_BUILDERS
1833
1834 Create configuration for all nodes assigned to a slice:
1835
1836 @example
1837 ./create_buildbot_configuration.py -u <planetlab username> \
1838 -p <planetlab password> -s <slice> -m <buildmaster+port> \
1839 -t <template>
1840 @end example
1841
1842 Create configuration for some nodes in a file:
1843
1844 @example
1845 ./create_buildbot_configuration.p -f <node_file> \
1846 -m <buildmaster+port> -t <template>
1847 @end example
1848
1849 @item Copy the @file{master.cfg} to the buildmaster and start it
1850 Use @code{buildbot start <basedir>} to start the server
1851 @item Setup the buildslaves
1852 @end itemize
1853
1854 @c ***********************************************************************
1855 @node Why do i get an ssh error when using the regex profiler?
1856 @subsubsection Why do i get an ssh error when using the regex profiler?
1857
1858 Why do i get an ssh error "Permission denied (publickey,password)." when
1859 using the regex profiler although passwordless ssh to localhost works
1860 using publickey and ssh-agent?
1861
1862 You have to generate a public/private-key pair with no password:@
1863 @code{ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_localhost}@
1864 and then add the following to your ~/.ssh/config file:
1865
1866 @code{Host 127.0.0.1@ IdentityFile ~/.ssh/id_localhost}
1867
1868 now make sure your hostsfile looks like
1869
1870 @example
1871 [USERNAME]@@127.0.0.1:22@
1872 [USERNAME]@@127.0.0.1:22
1873 @end example
1874
1875 You can test your setup by running @code{ssh 127.0.0.1} in a
1876 terminal and then in the opened session run it again.
1877 If you were not asked for a password on either login,
1878 then you should be good to go.
1879
1880 @cindex TESTBED Caveats
1881 @node TESTBED Caveats
1882 @subsection TESTBED Caveats
1883
1884 This section documents a few caveats when using the GNUnet testbed
1885 subsystem.
1886
1887 @c ***********************************************************************
1888 @menu
1889 * CORE must be started::
1890 * ATS must want the connections::
1891 @end menu
1892
1893 @node CORE must be started
1894 @subsubsection CORE must be started
1895
1896 A simple issue is #3993: Your configuration MUST somehow ensure that for
1897 each peer the CORE service is started when the peer is setup, otherwise
1898 TESTBED may fail to connect peers when the topology is initialized, as
1899 TESTBED will start some CORE services but not necessarily all (but it
1900 relies on all of them running). The easiest way is to set
1901 'FORCESTART = YES' in the '[core]' section of the configuration file.
1902 Alternatively, having any service that directly or indirectly depends on
1903 CORE being started with FORCESTART will also do. This issue largely arises
1904 if users try to over-optimize by not starting any services with
1905 FORCESTART.
1906
1907 @c ***********************************************************************
1908 @node ATS must want the connections
1909 @subsubsection ATS must want the connections
1910
1911 When TESTBED sets up connections, it only offers the respective HELLO
1912 information to the TRANSPORT service. It is then up to the ATS service to
1913 @strong{decide} to use the connection. The ATS service will typically
1914 eagerly establish any connection if the number of total connections is
1915 low (relative to bandwidth). Details may further depend on the
1916 specific ATS backend that was configured. If ATS decides to NOT establish
1917 a connection (even though TESTBED provided the required information), then
1918 that connection will count as failed for TESTBED. Note that you can
1919 configure TESTBED to tolerate a certain number of connection failures
1920 (see '-e' option of gnunet-testbed-profiler). This issue largely arises
1921 for dense overlay topologies, especially if you try to create cliques
1922 with more than 20 peers.
1923
1924 @cindex libgnunetutil
1925 @node libgnunetutil
1926 @section libgnunetutil
1927
1928 libgnunetutil is the fundamental library that all GNUnet code builds upon.
1929 Ideally, this library should contain most of the platform dependent code
1930 (except for user interfaces and really special needs that only few
1931 applications have). It is also supposed to offer basic services that most
1932 if not all GNUnet binaries require. The code of libgnunetutil is in the
1933 @file{src/util/} directory. The public interface to the library is in the
1934 gnunet_util.h header. The functions provided by libgnunetutil fall
1935 roughly into the following categories (in roughly the order of importance
1936 for new developers):
1937
1938 @itemize @bullet
1939 @item logging (common_logging.c)
1940 @item memory allocation (common_allocation.c)
1941 @item endianess conversion (common_endian.c)
1942 @item internationalization (common_gettext.c)
1943 @item String manipulation (string.c)
1944 @item file access (disk.c)
1945 @item buffered disk IO (bio.c)
1946 @item time manipulation (time.c)
1947 @item configuration parsing (configuration.c)
1948 @item command-line handling (getopt*.c)
1949 @item cryptography (crypto_*.c)
1950 @item data structures (container_*.c)
1951 @item CPS-style scheduling (scheduler.c)
1952 @item Program initialization (program.c)
1953 @item Networking (network.c, client.c, server*.c, service.c)
1954 @item message queueing (mq.c)
1955 @item bandwidth calculations (bandwidth.c)
1956 @item Other OS-related (os*.c, plugin.c, signal.c)
1957 @item Pseudonym management (pseudonym.c)
1958 @end itemize
1959
1960 It should be noted that only developers that fully understand this entire
1961 API will be able to write good GNUnet code.
1962
1963 Ideally, porting GNUnet should only require porting the gnunetutil
1964 library. More testcases for the gnunetutil APIs are therefore a great
1965 way to make porting of GNUnet easier.
1966
1967 @menu
1968 * Logging::
1969 * Interprocess communication API (IPC)::
1970 * Cryptography API::
1971 * Message Queue API::
1972 * Service API::
1973 * Optimizing Memory Consumption of GNUnet's (Multi-) Hash Maps::
1974 * CONTAINER_MDLL API::
1975 @end menu
1976
1977 @cindex Logging
1978 @cindex log levels
1979 @node Logging
1980 @subsection Logging
1981
1982 GNUnet is able to log its activity, mostly for the purposes of debugging
1983 the program at various levels.
1984
1985 @file{gnunet_common.h} defines several @strong{log levels}:
1986 @table @asis
1987
1988 @item ERROR for errors (really problematic situations, often leading to
1989 crashes)
1990 @item WARNING for warnings (troubling situations that might have
1991 negative consequences, although not fatal)
1992 @item INFO for various information.
1993 Used somewhat rarely, as GNUnet statistics is used to hold and display
1994 most of the information that users might find interesting.
1995 @item DEBUG for debugging.
1996 Does not produce much output on normal builds, but when extra logging is
1997 enabled at compile time, a staggering amount of data is outputted under
1998 this log level.
1999 @end table
2000
2001
2002 Normal builds of GNUnet (configured with @code{--enable-logging[=yes]})
2003 are supposed to log nothing under DEBUG level. The
2004 @code{--enable-logging=verbose} configure option can be used to create a
2005 build with all logging enabled. However, such build will produce large
2006 amounts of log data, which is inconvenient when one tries to hunt down a
2007 specific problem.
2008
2009 To mitigate this problem, GNUnet provides facilities to apply a filter to
2010 reduce the logs:
2011 @table @asis
2012
2013 @item Logging by default When no log levels are configured in any other
2014 way (see below), GNUnet will default to the WARNING log level. This
2015 mostly applies to GNUnet command line utilities, services and daemons;
2016 tests will always set log level to WARNING or, if
2017 @code{--enable-logging=verbose} was passed to configure, to DEBUG. The
2018 default level is suggested for normal operation.
2019 @item The -L option Most GNUnet executables accept an "-L loglevel" or
2020 "--log=loglevel" option. If used, it makes the process set a global log
2021 level to "loglevel". Thus it is possible to run some processes
2022 with -L DEBUG, for example, and others with -L ERROR to enable specific
2023 settings to diagnose problems with a particular process.
2024 @item Configuration files.  Because GNUnet
2025 service and deamon processes are usually launched by gnunet-arm, it is not
2026 possible to pass different custom command line options directly to every
2027 one of them. The options passed to @code{gnunet-arm} only affect
2028 gnunet-arm and not the rest of GNUnet. However, one can specify a
2029 configuration key "OPTIONS" in the section that corresponds to a service
2030 or a daemon, and put a value of "-L loglevel" there. This will make the
2031 respective service or daemon set its log level to "loglevel" (as the
2032 value of OPTIONS will be passed as a command-line argument).
2033
2034 To specify the same log level for all services without creating separate
2035 "OPTIONS" entries in the configuration for each one, the user can specify
2036 a config key "GLOBAL_POSTFIX" in the [arm] section of the configuration
2037 file. The value of GLOBAL_POSTFIX will be appended to all command lines
2038 used by the ARM service to run other services. It can contain any option
2039 valid for all GNUnet commands, thus in particular the "-L loglevel"
2040 option. The ARM service itself is, however, unaffected by GLOBAL_POSTFIX;
2041 to set log level for it, one has to specify "OPTIONS" key in the [arm]
2042 section.
2043 @item Environment variables.
2044 Setting global per-process log levels with "-L loglevel" does not offer
2045 sufficient log filtering granularity, as one service will call interface
2046 libraries and supporting libraries of other GNUnet services, potentially
2047 producing lots of debug log messages from these libraries. Also, changing
2048 the config file is not always convenient (especially when running the
2049 GNUnet test suite).@ To fix that, and to allow GNUnet to use different
2050 log filtering at runtime without re-compiling the whole source tree, the
2051 log calls were changed to be configurable at run time. To configure them
2052 one has to define environment variables "GNUNET_FORCE_LOGFILE",
2053 "GNUNET_LOG" and/or "GNUNET_FORCE_LOG":
2054 @itemize @bullet
2055
2056 @item "GNUNET_LOG" only affects the logging when no global log level is
2057 configured by any other means (that is, the process does not explicitly
2058 set its own log level, there are no "-L loglevel" options on command line
2059 or in configuration files), and can be used to override the default
2060 WARNING log level.
2061
2062 @item "GNUNET_FORCE_LOG" will completely override any other log
2063 configuration options given.
2064
2065 @item "GNUNET_FORCE_LOGFILE" will completely override the location of the
2066 file to log messages to. It should contain a relative or absolute file
2067 name. Setting GNUNET_FORCE_LOGFILE is equivalent to passing
2068 "--log-file=logfile" or "-l logfile" option (see below). It supports "[]"
2069 format in file names, but not "@{@}" (see below).
2070 @end itemize
2071
2072
2073 Because environment variables are inherited by child processes when they
2074 are launched, starting or re-starting the ARM service with these
2075 variables will propagate them to all other services.
2076
2077 "GNUNET_LOG" and "GNUNET_FORCE_LOG" variables must contain a specially
2078 formatted @strong{logging definition} string, which looks like this:@
2079
2080 @c FIXME: Can we close this with [/component] instead?
2081 @example
2082 [component];[file];[function];[from_line[-to_line]];loglevel[/component...]
2083 @end example
2084
2085 That is, a logging definition consists of definition entries, separated by
2086 slashes ('/'). If only one entry is present, there is no need to add a
2087 slash to its end (although it is not forbidden either).@ All definition
2088 fields (component, file, function, lines and loglevel) are mandatory, but
2089 (except for the loglevel) they can be empty. An empty field means
2090 "match anything". Note that even if fields are empty, the semicolon (';')
2091 separators must be present.@ The loglevel field is mandatory, and must
2092 contain one of the log level names (ERROR, WARNING, INFO or DEBUG).@
2093 The lines field might contain one non-negative number, in which case it
2094 matches only one line, or a range "from_line-to_line", in which case it
2095 matches any line in the interval [from_line;to_line] (that is, including
2096 both start and end line).@ GNUnet mostly defaults component name to the
2097 name of the service that is implemented in a process ('transport',
2098 'core', 'peerinfo', etc), but logging calls can specify custom component
2099 names using @code{GNUNET_log_from}.@ File name and function name are
2100 provided by the compiler (__FILE__ and __FUNCTION__ built-ins).
2101
2102 Component, file and function fields are interpreted as non-extended
2103 regular expressions (GNU libc regex functions are used). Matching is
2104 case-sensitive, "^" and "$" will match the beginning and the end of the
2105 text. If a field is empty, its contents are automatically replaced with
2106 a ".*" regular expression, which matches anything. Matching is done in
2107 the default way, which means that the expression matches as long as it's
2108 contained anywhere in the string. Thus "GNUNET_" will match both
2109 "GNUNET_foo" and "BAR_GNUNET_BAZ". Use '^' and/or '$' to make sure that
2110 the expression matches at the start and/or at the end of the string.
2111 The semicolon (';') can't be escaped, and GNUnet will not use it in
2112 component names (it can't be used in function names and file names
2113 anyway).
2114
2115 @end table
2116
2117
2118 Every logging call in GNUnet code will be (at run time) matched against
2119 the log definitions passed to the process. If a log definition fields are
2120 matching the call arguments, then the call log level is compared the the
2121 log level of that definition. If the call log level is less or equal to
2122 the definition log level, the call is allowed to proceed. Otherwise the
2123 logging call is forbidden, and nothing is logged. If no definitions
2124 matched at all, GNUnet will use the global log level or (if a global log
2125 level is not specified) will default to WARNING (that is, it will allow
2126 the call to proceed, if its level is less or equal to the global log
2127 level or to WARNING).
2128
2129 That is, definitions are evaluated from left to right, and the first
2130 matching definition is used to allow or deny the logging call. Thus it is
2131 advised to place narrow definitions at the beginning of the logdef
2132 string, and generic definitions - at the end.
2133
2134 Whether a call is allowed or not is only decided the first time this
2135 particular call is made. The evaluation result is then cached, so that
2136 any attempts to make the same call later will be allowed or disallowed
2137 right away. Because of that runtime log level evaluation should not
2138 significantly affect the process performance.
2139 Log definition parsing is only done once, at the first call to
2140 GNUNET_log_setup () made by the process (which is usually done soon after
2141 it starts).
2142
2143 At the moment of writing there is no way to specify logging definitions
2144 from configuration files, only via environment variables.
2145
2146 At the moment GNUnet will stop processing a log definition when it
2147 encounters an error in definition formatting or an error in regular
2148 expression syntax, and will not report the failure in any way.
2149
2150
2151 @c ***********************************************************************
2152 @menu
2153 * Examples::
2154 * Log files::
2155 * Updated behavior of GNUNET_log::
2156 @end menu
2157
2158 @node Examples
2159 @subsubsection Examples
2160
2161 @table @asis
2162
2163 @item @code{GNUNET_FORCE_LOG=";;;;DEBUG" gnunet-arm -s} Start GNUnet
2164 process tree, running all processes with DEBUG level (one should be
2165 careful with it, as log files will grow at alarming rate!)
2166 @item @code{GNUNET_FORCE_LOG="core;;;;DEBUG" gnunet-arm -s} Start GNUnet
2167 process tree, running the core service under DEBUG level (everything else
2168 will use configured or default level).
2169
2170 @item Start GNUnet process tree, allowing any logging calls from
2171 gnunet-service-transport_validation.c (everything else will use
2172 configured or default level).
2173
2174 @example
2175 GNUNET_FORCE_LOG=";gnunet-service-transport_validation.c;;; DEBUG" \
2176 gnunet-arm -s
2177 @end example
2178
2179 @item Start GNUnet process tree, allowing any logging calls from
2180 gnunet-gnunet-service-fs_push.c (everything else will use configured or
2181 default level).
2182
2183 @example
2184 GNUNET_FORCE_LOG="fs;gnunet-service-fs_push.c;;;DEBUG" gnunet-arm -s
2185 @end example
2186
2187 @item Start GNUnet process tree, allowing any logging calls from the
2188 GNUNET_NETWORK_socket_select function (everything else will use
2189 configured or default level).
2190
2191 @example
2192 GNUNET_FORCE_LOG=";;GNUNET_NETWORK_socket_select;;DEBUG" gnunet-arm -s
2193 @end example
2194
2195 @item Start GNUnet process tree, allowing any logging calls from the
2196 components that have "transport" in their names, and are made from
2197 function that have "send" in their names. Everything else will be allowed
2198 to be logged only if it has WARNING level.
2199
2200 @example
2201 GNUNET_FORCE_LOG="transport.*;;.*send.*;;DEBUG/;;;;WARNING" gnunet-arm -s
2202 @end example
2203
2204 @end table
2205
2206
2207 On Windows, one can use batch files to run GNUnet processes with special
2208 environment variables, without affecting the whole system. Such batch
2209 file will look like this:
2210
2211 @example
2212 set GNUNET_FORCE_LOG=;;do_transmit;;DEBUG@ gnunet-arm -s
2213 @end example
2214
2215 (note the absence of double quotes in the environment variable definition,
2216 as opposed to earlier examples, which use the shell).
2217 Another limitation, on Windows, GNUNET_FORCE_LOGFILE @strong{MUST} be set
2218 in order to GNUNET_FORCE_LOG to work.
2219
2220
2221 @cindex Log files
2222 @node Log files
2223 @subsubsection Log files
2224
2225 GNUnet can be told to log everything into a file instead of stderr (which
2226 is the default) using the "--log-file=logfile" or "-l logfile" option.
2227 This option can also be passed via command line, or from the "OPTION" and
2228 "GLOBAL_POSTFIX" configuration keys (see above). The file name passed
2229 with this option is subject to GNUnet filename expansion. If specified in
2230 "GLOBAL_POSTFIX", it is also subject to ARM service filename expansion,
2231 in particular, it may contain "@{@}" (left and right curly brace)
2232 sequence, which will be replaced by ARM with the name of the service.
2233 This is used to keep logs from more than one service separate, while only
2234 specifying one template containing "@{@}" in GLOBAL_POSTFIX.
2235
2236 As part of a secondary file name expansion, the first occurrence of "[]"
2237 sequence ("left square brace" followed by "right square brace") in the
2238 file name will be replaced with a process identifier or the process when
2239 it initializes its logging subsystem. As a result, all processes will log
2240 into different files. This is convenient for isolating messages of a
2241 particular process, and prevents I/O races when multiple processes try to
2242 write into the file at the same time. This expansion is done
2243 independently of "@{@}" expansion that ARM service does (see above).
2244
2245 The log file name that is specified via "-l" can contain format characters
2246 from the 'strftime' function family. For example, "%Y" will be replaced
2247 with the current year. Using "basename-%Y-%m-%d.log" would include the
2248 current year, month and day in the log file. If a GNUnet process runs for
2249 long enough to need more than one log file, it will eventually clean up
2250 old log files. Currently, only the last three log files (plus the current
2251 log file) are preserved. So once the fifth log file goes into use (so
2252 after 4 days if you use "%Y-%m-%d" as above), the first log file will be
2253 automatically deleted. Note that if your log file name only contains "%Y",
2254 then log files would be kept for 4 years and the logs from the first year
2255 would be deleted once year 5 begins. If you do not use any date-related
2256 string format codes, logs would never be automatically deleted by GNUnet.
2257
2258
2259 @c ***********************************************************************
2260
2261 @node Updated behavior of GNUNET_log
2262 @subsubsection Updated behavior of GNUNET_log
2263
2264 It's currently quite common to see constructions like this all over the
2265 code:
2266
2267 @example
2268 #if MESH_DEBUG
2269 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
2270 #endif
2271 @end example
2272
2273 The reason for the #if is not to avoid displaying the message when
2274 disabled (GNUNET_ERROR_TYPE takes care of that), but to avoid the
2275 compiler including it in the binary at all, when compiling GNUnet for
2276 platforms with restricted storage space / memory (MIPS routers,
2277 ARM plug computers / dev boards, etc).
2278
2279 This presents several problems: the code gets ugly, hard to write and it
2280 is very easy to forget to include the #if guards, creating non-consistent
2281 code. A new change in GNUNET_log aims to solve these problems.
2282
2283 @strong{This change requires to @file{./configure} with at least
2284 @code{--enable-logging=verbose} to see debug messages.}
2285
2286 Here is an example of code with dense debug statements:
2287
2288 @example
2289 switch (restrict_topology) @{
2290 case GNUNET_TESTING_TOPOLOGY_CLIQUE:#if VERBOSE_TESTING
2291 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Blacklisting all but clique
2292 topology\n")); #endif unblacklisted_connections = create_clique (pg,
2293 &remove_connections, BLACKLIST, GNUNET_NO); break; case
2294 GNUNET_TESTING_TOPOLOGY_SMALL_WORLD_RING: #if VERBOSE_TESTING GNUNET_log
2295 (GNUNET_ERROR_TYPE_DEBUG, _("Blacklisting all but small world (ring)
2296 topology\n")); #endif unblacklisted_connections = create_small_world_ring
2297 (pg,&remove_connections, BLACKLIST); break;
2298 @end example
2299
2300
2301 Pretty hard to follow, huh?
2302
2303 From now on, it is not necessary to include the #if / #endif statements to
2304 achieve the same behavior. The GNUNET_log and GNUNET_log_from macros take
2305 care of it for you, depending on the configure option:
2306
2307 @itemize @bullet
2308 @item If @code{--enable-logging} is set to @code{no}, the binary will
2309 contain no log messages at all.
2310 @item If @code{--enable-logging} is set to @code{yes}, the binary will
2311 contain no DEBUG messages, and therefore running with -L DEBUG will have
2312 no effect. Other messages (ERROR, WARNING, INFO, etc) will be included.
2313 @item If @code{--enable-logging} is set to @code{verbose}, or
2314 @code{veryverbose} the binary will contain DEBUG messages (still, it will
2315 be neccessary to run with -L DEBUG or set the DEBUG config option to show
2316 them).
2317 @end itemize
2318
2319
2320 If you are a developer:
2321 @itemize @bullet
2322 @item please make sure that you @code{./configure
2323 --enable-logging=@{verbose,veryverbose@}}, so you can see DEBUG messages.
2324 @item please remove the @code{#if} statements around @code{GNUNET_log
2325 (GNUNET_ERROR_TYPE_DEBUG, ...)} lines, to improve the readibility of your
2326 code.
2327 @end itemize
2328
2329 Since now activating DEBUG automatically makes it VERBOSE and activates
2330 @strong{all} debug messages by default, you probably want to use the
2331 https://gnunet.org/logging functionality to filter only relevant messages.
2332 A suitable configuration could be:
2333
2334 @example
2335 $ export GNUNET_FORCE_LOG="^YOUR_SUBSYSTEM$;;;;DEBUG/;;;;WARNING"
2336 @end example
2337
2338 Which will behave almost like enabling DEBUG in that subsytem before the
2339 change. Of course you can adapt it to your particular needs, this is only
2340 a quick example.
2341
2342 @cindex Interprocess communication API
2343 @cindex ICP
2344 @node Interprocess communication API (IPC)
2345 @subsection Interprocess communication API (IPC)
2346
2347 In GNUnet a variety of new message types might be defined and used in
2348 interprocess communication, in this tutorial we use the
2349 @code{struct AddressLookupMessage} as a example to introduce how to
2350 construct our own message type in GNUnet and how to implement the message
2351 communication between service and client.
2352 (Here, a client uses the @code{struct AddressLookupMessage} as a request
2353 to ask the server to return the address of any other peer connecting to
2354 the service.)
2355
2356
2357 @c ***********************************************************************
2358 @menu
2359 * Define new message types::
2360 * Define message struct::
2361 * Client - Establish connection::
2362 * Client - Initialize request message::
2363 * Client - Send request and receive response::
2364 * Server - Startup service::
2365 * Server - Add new handles for specified messages::
2366 * Server - Process request message::
2367 * Server - Response to client::
2368 * Server - Notification of clients::
2369 * Conversion between Network Byte Order (Big Endian) and Host Byte Order::
2370 @end menu
2371
2372 @node Define new message types
2373 @subsubsection Define new message types
2374
2375 First of all, you should define the new message type in
2376 @file{gnunet_protocols.h}:
2377
2378 @example
2379  // Request to look addresses of peers in server.
2380 #define GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP 29
2381   // Response to the address lookup request.
2382 #define GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY 30
2383 @end example
2384
2385 @c ***********************************************************************
2386 @node Define message struct
2387 @subsubsection Define message struct
2388
2389 After the type definition, the specified message structure should also be
2390 described in the header file, e.g. transport.h in our case.
2391
2392 @example
2393 struct AddressLookupMessage @{
2394   struct GNUNET_MessageHeader header;
2395   int32_t numeric_only GNUNET_PACKED;
2396   struct GNUNET_TIME_AbsoluteNBO timeout;
2397   uint32_t addrlen GNUNET_PACKED;
2398   /* followed by 'addrlen' bytes of the actual address, then
2399      followed by the 0-terminated name of the transport */ @};
2400 GNUNET_NETWORK_STRUCT_END
2401 @end example
2402
2403
2404 Please note @code{GNUNET_NETWORK_STRUCT_BEGIN} and @code{GNUNET_PACKED}
2405 which both ensure correct alignment when sending structs over the network.
2406
2407 @menu
2408 @end menu
2409
2410 @c ***********************************************************************
2411 @node Client - Establish connection
2412 @subsubsection Client - Establish connection
2413 @c %**end of header
2414
2415
2416 At first, on the client side, the underlying API is employed to create a
2417 new connection to a service, in our example the transport service would be
2418 connected.
2419
2420 @example
2421 struct GNUNET_CLIENT_Connection *client;
2422 client = GNUNET_CLIENT_connect ("transport", cfg);
2423 @end example
2424
2425 @c ***********************************************************************
2426 @node Client - Initialize request message
2427 @subsubsection Client - Initialize request message
2428 @c %**end of header
2429
2430 When the connection is ready, we initialize the message. In this step,
2431 all the fields of the message should be properly initialized, namely the
2432 size, type, and some extra user-defined data, such as timeout, name of
2433 transport, address and name of transport.
2434
2435 @example
2436 struct AddressLookupMessage *msg;
2437 size_t len = sizeof (struct AddressLookupMessage)
2438   + addressLen
2439   + strlen (nameTrans)
2440   + 1;
2441 msg->header->size = htons (len);
2442 msg->header->type = htons
2443 (GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP);
2444 msg->timeout = GNUNET_TIME_absolute_hton (abs_timeout);
2445 msg->addrlen = htonl (addressLen);
2446 char *addrbuf = (char *) &msg[1];
2447 memcpy (addrbuf, address, addressLen);
2448 char *tbuf = &addrbuf[addressLen];
2449 memcpy (tbuf, nameTrans, strlen (nameTrans) + 1);
2450 @end example
2451
2452 Note that, here the functions @code{htonl}, @code{htons} and
2453 @code{GNUNET_TIME_absolute_hton} are applied to convert little endian
2454 into big endian, about the usage of the big/small endian order and the
2455 corresponding conversion function please refer to Introduction of
2456 Big Endian and Little Endian.
2457
2458 @c ***********************************************************************
2459 @node Client - Send request and receive response
2460 @subsubsection Client - Send request and receive response
2461 @c %**end of header
2462
2463 @b{FIXME: This is very outdated, see the tutorial for the current API!}
2464
2465 Next, the client would send the constructed message as a request to the
2466 service and wait for the response from the service. To accomplish this
2467 goal, there are a number of API calls that can be used. In this example,
2468 @code{GNUNET_CLIENT_transmit_and_get_response} is chosen as the most
2469 appropriate function to use.
2470
2471 @example
2472 GNUNET_CLIENT_transmit_and_get_response
2473 (client, msg->header, timeout, GNUNET_YES, &address_response_processor,
2474 arp_ctx);
2475 @end example
2476
2477 the argument @code{address_response_processor} is a function with
2478 @code{GNUNET_CLIENT_MessageHandler} type, which is used to process the
2479 reply message from the service.
2480
2481 @node Server - Startup service
2482 @subsubsection Server - Startup service
2483
2484 After receiving the request message, we run a standard GNUnet service
2485 startup sequence using @code{GNUNET_SERVICE_run}, as follows,
2486
2487 @example
2488 int main(int argc, char**argv) @{
2489   GNUNET_SERVICE_run(argc, argv, "transport"
2490   GNUNET_SERVICE_OPTION_NONE, &run, NULL)); @}
2491 @end example
2492
2493 @c ***********************************************************************
2494 @node Server - Add new handles for specified messages
2495 @subsubsection Server - Add new handles for specified messages
2496 @c %**end of header
2497
2498 in the function above the argument @code{run} is used to initiate
2499 transport service,and defined like this:
2500
2501 @example
2502 static void run (void *cls,
2503 struct GNUNET_SERVER_Handle *serv,
2504 const struct GNUNET_CONFIGURATION_Handle *cfg) @{
2505   GNUNET_SERVER_add_handlers (serv, handlers); @}
2506 @end example
2507
2508
2509 Here, @code{GNUNET_SERVER_add_handlers} must be called in the run
2510 function to add new handlers in the service. The parameter
2511 @code{handlers} is a list of @code{struct GNUNET_SERVER_MessageHandler}
2512 to tell the service which function should be called when a particular
2513 type of message is received, and should be defined in this way:
2514
2515 @example
2516 static struct GNUNET_SERVER_MessageHandler handlers[] = @{
2517   @{&handle_start,
2518    NULL,
2519    GNUNET_MESSAGE_TYPE_TRANSPORT_START,
2520    0@},
2521   @{&handle_send,
2522    NULL,
2523    GNUNET_MESSAGE_TYPE_TRANSPORT_SEND,
2524    0@},
2525   @{&handle_try_connect,
2526    NULL,
2527    GNUNET_MESSAGE_TYPE_TRANSPORT_TRY_CONNECT,
2528    sizeof (struct TryConnectMessage)
2529   @},
2530   @{&handle_address_lookup,
2531    NULL,
2532    GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP,
2533    0@},
2534   @{NULL,
2535    NULL,
2536    0,
2537    0@}
2538 @};
2539 @end example
2540
2541
2542 As shown, the first member of the struct in the first area is a callback
2543 function, which is called to process the specified message types, given
2544 as the third member. The second parameter is the closure for the callback
2545 function, which is set to @code{NULL} in most cases, and the last
2546 parameter is the expected size of the message of this type, usually we
2547 set it to 0 to accept variable size, for special cases the exact size of
2548 the specified message also can be set. In addition, the terminator sign
2549 depicted as @code{@{NULL, NULL, 0, 0@}} is set in the last aera.
2550
2551 @c ***********************************************************************
2552 @node Server - Process request message
2553 @subsubsection Server - Process request message
2554 @c %**end of header
2555
2556 After the initialization of transport service, the request message would
2557 be processed. Before handling the main message data, the validity of this
2558 message should be checked out, e.g., to check whether the size of message
2559 is correct.
2560
2561 @example
2562 size = ntohs (message->size);
2563 if (size < sizeof (struct AddressLookupMessage)) @{
2564   GNUNET_break_op (0);
2565   GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2566   return; @}
2567 @end example
2568
2569
2570 Note that, opposite to the construction method of the request message in
2571 the client, in the server the function @code{nothl} and @code{ntohs}
2572 should be employed during the extraction of the data from the message, so
2573 that the data in big endian order can be converted back into little
2574 endian order. See more in detail please refer to Introduction of
2575 Big Endian and Little Endian.
2576
2577 Moreover in this example, the name of the transport stored in the message
2578 is a 0-terminated string, so we should also check whether the name of the
2579 transport in the received message is 0-terminated:
2580
2581 @example
2582 nameTransport = (const char *) &address[addressLen];
2583 if (nameTransport[size - sizeof
2584                   (struct AddressLookupMessage)
2585                   - addressLen - 1] != '\0') @{
2586   GNUNET_break_op (0);
2587   GNUNET_SERVER_receive_done (client,
2588                               GNUNET_SYSERR);
2589   return; @}
2590 @end example
2591
2592 Here, @code{GNUNET_SERVER_receive_done} should be called to tell the
2593 service that the request is done and can receive the next message. The
2594 argument @code{GNUNET_SYSERR} here indicates that the service didn't
2595 understand the request message, and the processing of this request would
2596 be terminated.
2597
2598 In comparison to the aforementioned situation, when the argument is equal
2599 to @code{GNUNET_OK}, the service would continue to process the requst
2600 message.
2601
2602 @c ***********************************************************************
2603 @node Server - Response to client
2604 @subsubsection Server - Response to client
2605 @c %**end of header
2606
2607 Once the processing of current request is done, the server should give the
2608 response to the client. A new @code{struct AddressLookupMessage} would be
2609 produced by the server in a similar way as the client did and sent to the
2610 client, but here the type should be
2611 @code{GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY} rather than
2612 @code{GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_LOOKUP} in client.
2613 @example
2614 struct AddressLookupMessage *msg;
2615 size_t len = sizeof (struct AddressLookupMessage)
2616   + addressLen
2617   + strlen (nameTrans) + 1;
2618 msg->header->size = htons (len);
2619 msg->header->type = htons
2620   (GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
2621
2622 // ...
2623
2624 struct GNUNET_SERVER_TransmitContext *tc;
2625 tc = GNUNET_SERVER_transmit_context_create (client);
2626 GNUNET_SERVER_transmit_context_append_data
2627 (tc,
2628  NULL,
2629  0,
2630  GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_REPLY);
2631 GNUNET_SERVER_transmit_context_run (tc, rtimeout);
2632 @end example
2633
2634
2635 Note that, there are also a number of other APIs provided to the service
2636 to send the message.
2637
2638 @c ***********************************************************************
2639 @node Server - Notification of clients
2640 @subsubsection Server - Notification of clients
2641 @c %**end of header
2642
2643 Often a service needs to (repeatedly) transmit notifications to a client
2644 or a group of clients. In these cases, the client typically has once
2645 registered for a set of events and then needs to receive a message
2646 whenever such an event happens (until the client disconnects). The use of
2647 a notification context can help manage message queues to clients and
2648 handle disconnects. Notification contexts can be used to send
2649 individualized messages to a particular client or to broadcast messages
2650 to a group of clients. An individualized notification might look like
2651 this:
2652
2653 @example
2654 GNUNET_SERVER_notification_context_unicast(nc,
2655                                            client,
2656                                            msg,
2657                                            GNUNET_YES);
2658 @end example
2659
2660
2661 Note that after processing the original registration message for
2662 notifications, the server code still typically needs to call
2663 @code{GNUNET_SERVER_receive_done} so that the client can transmit further
2664 messages to the server.
2665
2666 @c ***********************************************************************
2667 @node Conversion between Network Byte Order (Big Endian) and Host Byte Order
2668 @subsubsection Conversion between Network Byte Order (Big Endian) and Host Byte Order
2669 @c %** subsub? it's a referenced page on the ipc document.
2670 @c %**end of header
2671
2672 Here we can simply comprehend big endian and little endian as Network Byte
2673 Order and Host Byte Order respectively. What is the difference between
2674 both two?
2675
2676 Usually in our host computer we store the data byte as Host Byte Order,
2677 for example, we store a integer in the RAM which might occupies 4 Byte,
2678 as Host Byte Order the higher Byte would be stored at the lower address
2679 of RAM, and the lower Byte would be stored at the higher address of RAM.
2680 However, contrast to this, Network Byte Order just take the totally
2681 opposite way to store the data, says, it will store the lower Byte at the
2682 lower address, and the higher Byte will stay at higher address.
2683
2684 For the current communication of network, we normally exchange the
2685 information by surveying the data package, every two host wants to
2686 communicate with each other must send and receive data package through
2687 network. In order to maintain the identity of data through the
2688 transmission in the network, the order of the Byte storage must changed
2689 before sending and after receiving the data.
2690
2691 There ten convenient functions to realize the conversion of Byte Order in
2692 GNUnet, as following:
2693
2694 @table @asis
2695
2696 @item uint16_t htons(uint16_t hostshort) Convert host byte order to net
2697 byte order with short int
2698 @item uint32_t htonl(uint32_t hostlong) Convert host byte
2699 order to net byte order with long int
2700 @item uint16_t ntohs(uint16_t netshort)
2701 Convert net byte order to host byte order with short int
2702 @item uint32_t
2703 ntohl(uint32_t netlong) Convert net byte order to host byte order with
2704 long int
2705 @item unsigned long long GNUNET_ntohll (unsigned long long netlonglong)
2706 Convert net byte order to host byte order with long long int
2707 @item unsigned long long GNUNET_htonll (unsigned long long hostlonglong)
2708 Convert host byte order to net byte order with long long int
2709 @item struct GNUNET_TIME_RelativeNBO GNUNET_TIME_relative_hton
2710 (struct GNUNET_TIME_Relative a) Convert relative time to network byte
2711 order.
2712 @item struct GNUNET_TIME_Relative GNUNET_TIME_relative_ntoh
2713 (struct GNUNET_TIME_RelativeNBO a) Convert relative time from network
2714 byte order.
2715 @item struct GNUNET_TIME_AbsoluteNBO GNUNET_TIME_absolute_hton
2716 (struct GNUNET_TIME_Absolute a) Convert relative time to network byte
2717 order.
2718 @item struct GNUNET_TIME_Absolute GNUNET_TIME_absolute_ntoh
2719 (struct GNUNET_TIME_AbsoluteNBO a) Convert relative time from network
2720 byte order.
2721 @end table
2722
2723 @cindex Cryptography API
2724 @node Cryptography API
2725 @subsection Cryptography API
2726 @c %**end of header
2727
2728 The gnunetutil APIs provides the cryptographic primitives used in GNUnet.
2729 GNUnet uses 2048 bit RSA keys for the session key exchange and for signing
2730 messages by peers and most other public-key operations. Most researchers
2731 in cryptography consider 2048 bit RSA keys as secure and practically
2732 unbreakable for a long time. The API provides functions to create a fresh
2733 key pair, read a private key from a file (or create a new file if the
2734 file does not exist), encrypt, decrypt, sign, verify and extraction of
2735 the public key into a format suitable for network transmission.
2736
2737 For the encryption of files and the actual data exchanged between peers
2738 GNUnet uses 256-bit AES encryption. Fresh, session keys are negotiated
2739 for every new connection.@ Again, there is no published technique to
2740 break this cipher in any realistic amount of time. The API provides
2741 functions for generation of keys, validation of keys (important for
2742 checking that decryptions using RSA succeeded), encryption and decryption.
2743
2744 GNUnet uses SHA-512 for computing one-way hash codes. The API provides
2745 functions to compute a hash over a block in memory or over a file on disk.
2746
2747 The crypto API also provides functions for randomizing a block of memory,
2748 obtaining a single random number and for generating a permuation of the
2749 numbers 0 to n-1. Random number generation distinguishes between WEAK and
2750 STRONG random number quality; WEAK random numbers are pseudo-random
2751 whereas STRONG random numbers use entropy gathered from the operating
2752 system.
2753
2754 Finally, the crypto API provides a means to deterministically generate a
2755 1024-bit RSA key from a hash code. These functions should most likely not
2756 be used by most applications; most importantly,
2757 GNUNET_CRYPTO_rsa_key_create_from_hash does not create an RSA-key that
2758 should be considered secure for traditional applications of RSA.
2759
2760 @cindex Message Queue API
2761 @node Message Queue API
2762 @subsection Message Queue API
2763 @c %**end of header
2764
2765 @strong{ Introduction }@
2766 Often, applications need to queue messages that
2767 are to be sent to other GNUnet peers, clients or services. As all of
2768 GNUnet's message-based communication APIs, by design, do not allow
2769 messages to be queued, it is common to implement custom message queues
2770 manually when they are needed. However, writing very similar code in
2771 multiple places is tedious and leads to code duplication.
2772
2773 MQ (for Message Queue) is an API that provides the functionality to
2774 implement and use message queues. We intend to eventually replace all of
2775 the custom message queue implementations in GNUnet with MQ.
2776
2777 @strong{ Basic Concepts }@
2778 The two most important entities in MQ are queues and envelopes.
2779
2780 Every queue is backed by a specific implementation (e.g. for mesh, stream,
2781 connection, server client, etc.) that will actually deliver the queued
2782 messages. For convenience,@ some queues also allow to specify a list of
2783 message handlers. The message queue will then also wait for incoming
2784 messages and dispatch them appropriately.
2785
2786 An envelope holds the the memory for a message, as well as metadata
2787 (Where is the envelope queued? What should happen after it has been
2788 sent?). Any envelope can only be queued in one message queue.
2789
2790 @strong{ Creating Queues }@
2791 The following is a list of currently available message queues. Note that
2792 to avoid layering issues, message queues for higher level APIs are not
2793 part of @code{libgnunetutil}, but@ the respective API itself provides the
2794 queue implementation.
2795
2796 @table @asis
2797
2798 @item @code{GNUNET_MQ_queue_for_connection_client}
2799 Transmits queued messages over a @code{GNUNET_CLIENT_Connection} handle.
2800 Also supports receiving with message handlers.
2801
2802 @item @code{GNUNET_MQ_queue_for_server_client}
2803 Transmits queued messages over a @code{GNUNET_SERVER_Client} handle. Does
2804 not support incoming message handlers.
2805
2806 @item @code{GNUNET_MESH_mq_create} Transmits queued messages over a
2807 @code{GNUNET_MESH_Tunnel} handle. Does not support incoming message
2808 handlers.
2809
2810 @item @code{GNUNET_MQ_queue_for_callbacks} This is the most general
2811 implementation. Instead of delivering and receiving messages with one of
2812 GNUnet's communication APIs, implementation callbacks are called. Refer to
2813 "Implementing Queues" for a more detailed explanation.
2814 @end table
2815
2816
2817 @strong{ Allocating Envelopes }@
2818 A GNUnet message (as defined by the GNUNET_MessageHeader) has three
2819 parts: The size, the type, and the body.
2820
2821 MQ provides macros to allocate an envelope containing a message
2822 conveniently, automatically setting the size and type fields of the
2823 message.
2824
2825 Consider the following simple message, with the body consisting of a
2826 single number value.
2827 @c why the empy code function?
2828 @code{}
2829
2830 @example
2831 struct NumberMessage @{
2832   /** Type: GNUNET_MESSAGE_TYPE_EXAMPLE_1 */
2833   struct GNUNET_MessageHeader header;
2834   uint32_t number GNUNET_PACKED;
2835 @};
2836 @end example
2837
2838 An envelope containing an instance of the NumberMessage can be
2839 constructed like this:
2840
2841 @example
2842 struct GNUNET_MQ_Envelope *ev;
2843 struct NumberMessage *msg;
2844 ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_EXAMPLE_1);
2845 msg->number = htonl (42);
2846 @end example
2847
2848 In the above code, @code{GNUNET_MQ_msg} is a macro. The return value is
2849 the newly allocated envelope. The first argument must be a pointer to some
2850 @code{struct} containing a @code{struct GNUNET_MessageHeader header}
2851 field, while the second argument is the desired message type, in host
2852 byte order.
2853
2854 The @code{msg} pointer now points to an allocated message, where the
2855 message type and the message size are already set. The message's size is
2856 inferred from the type of the @code{msg} pointer: It will be set to
2857 'sizeof(*msg)', properly converted to network byte order.
2858
2859 If the message body's size is dynamic, the the macro
2860 @code{GNUNET_MQ_msg_extra} can be used to allocate an envelope whose
2861 message has additional space allocated after the @code{msg} structure.
2862
2863 If no structure has been defined for the message,
2864 @code{GNUNET_MQ_msg_header_extra} can be used to allocate additional space
2865 after the message header. The first argument then must be a pointer to a
2866 @code{GNUNET_MessageHeader}.
2867
2868 @strong{Envelope Properties}@
2869 A few functions in MQ allow to set additional properties on envelopes:
2870
2871 @table @asis
2872
2873 @item @code{GNUNET_MQ_notify_sent} Allows to specify a function that will
2874 be called once the envelope's message has been sent irrevocably.
2875 An envelope can be canceled precisely up to the@ point where the notify
2876 sent callback has been called.
2877
2878 @item @code{GNUNET_MQ_disable_corking} No corking will be used when
2879 sending the message. Not every@ queue supports this flag, per default,
2880 envelopes are sent with corking.@
2881
2882 @end table
2883
2884
2885 @strong{Sending Envelopes}@
2886 Once an envelope has been constructed, it can be queued for sending with
2887 @code{GNUNET_MQ_send}.
2888
2889 Note that in order to avoid memory leaks, an envelope must either be sent
2890 (the queue will free it) or destroyed explicitly with
2891 @code{GNUNET_MQ_discard}.
2892
2893 @strong{Canceling Envelopes}@
2894 An envelope queued with @code{GNUNET_MQ_send} can be canceled with
2895 @code{GNUNET_MQ_cancel}. Note that after the notify sent callback has
2896 been called, canceling a message results in undefined behavior.
2897 Thus it is unsafe to cancel an envelope that does not have a notify sent
2898 callback. When canceling an envelope, it is not necessary@ to call
2899 @code{GNUNET_MQ_discard}, and the envelope can't be sent again.
2900
2901 @strong{ Implementing Queues }@
2902 @code{TODO}
2903
2904 @cindex Service API
2905 @node Service API
2906 @subsection Service API
2907 @c %**end of header
2908
2909 Most GNUnet code lives in the form of services. Services are processes
2910 that offer an API for other components of the system to build on. Those
2911 other components can be command-line tools for users, graphical user
2912 interfaces or other services. Services provide their API using an IPC
2913 protocol. For this, each service must listen on either a TCP port or a
2914 UNIX domain socket; for this, the service implementation uses the server
2915 API. This use of server is exposed directly to the users of the service
2916 API. Thus, when using the service API, one is usually also often using
2917 large parts of the server API. The service API provides various
2918 convenience functions, such as parsing command-line arguments and the
2919 configuration file, which are not found in the server API.
2920 The dual to the service/server API is the client API, which can be used to
2921 access services.
2922
2923 The most common way to start a service is to use the
2924 @code{GNUNET_SERVICE_run} function from the program's main function.
2925 @code{GNUNET_SERVICE_run} will then parse the command line and
2926 configuration files and, based on the options found there,
2927 start the server. It will then give back control to the main
2928 program, passing the server and the configuration to the
2929 @code{GNUNET_SERVICE_Main} callback. @code{GNUNET_SERVICE_run}
2930 will also take care of starting the scheduler loop.
2931 If this is inappropriate (for example, because the scheduler loop
2932 is already running), @code{GNUNET_SERVICE_start} and
2933 related functions provide an alternative to @code{GNUNET_SERVICE_run}.
2934
2935 When starting a service, the service_name option is used to determine
2936 which sections in the configuration file should be used to configure the
2937 service. A typical value here is the name of the @file{src/}
2938 sub-directory, for example @file{statistics}.
2939 The same string would also be given to
2940 @code{GNUNET_CLIENT_connect} to access the service.
2941
2942 Once a service has been initialized, the program should use the
2943 @code{GNUNET_SERVICE_Main} callback to register message handlers
2944 using @code{GNUNET_SERVER_add_handlers}.
2945 The service will already have registered a handler for the
2946 "TEST" message.
2947
2948 @fnindex GNUNET_SERVICE_Options
2949 The option bitfield (@code{enum GNUNET_SERVICE_Options})
2950 determines how a service should behave during shutdown.
2951 There are three key strategies:
2952
2953 @table @asis
2954
2955 @item instant (@code{GNUNET_SERVICE_OPTION_NONE})
2956 Upon receiving the shutdown
2957 signal from the scheduler, the service immediately terminates the server,
2958 closing all existing connections with clients.
2959 @item manual (@code{GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN})
2960 The service does nothing by itself
2961 during shutdown. The main program will need to take the appropriate
2962 action by calling GNUNET_SERVER_destroy or GNUNET_SERVICE_stop (depending
2963 on how the service was initialized) to terminate the service. This method
2964 is used by gnunet-service-arm and rather uncommon.
2965 @item soft (@code{GNUNET_SERVICE_OPTION_SOFT_SHUTDOWN})
2966 Upon receiving the shutdown signal from the scheduler,
2967 the service immediately tells the server to stop
2968 listening for incoming clients. Requests from normal existing clients are
2969 still processed and the server/service terminates once all normal clients
2970 have disconnected. Clients that are not expected to ever disconnect (such
2971 as clients that monitor performance values) can be marked as 'monitor'
2972 clients using GNUNET_SERVER_client_mark_monitor. Those clients will
2973 continue to be processed until all 'normal' clients have disconnected.
2974 Then, the server will terminate, closing the monitor connections.
2975 This mode is for example used by 'statistics', allowing existing 'normal'
2976 clients to set (possibly persistent) statistic values before terminating.
2977
2978 @end table
2979
2980 @c ***********************************************************************
2981 @node Optimizing Memory Consumption of GNUnet's (Multi-) Hash Maps
2982 @subsection Optimizing Memory Consumption of GNUnet's (Multi-) Hash Maps
2983 @c %**end of header
2984
2985 A commonly used data structure in GNUnet is a (multi-)hash map. It is most
2986 often used to map a peer identity to some data structure, but also to map
2987 arbitrary keys to values (for example to track requests in the distributed
2988 hash table or in file-sharing). As it is commonly used, the DHT is
2989 actually sometimes responsible for a large share of GNUnet's overall
2990 memory consumption (for some processes, 30% is not uncommon). The
2991 following text documents some API quirks (and their implications for
2992 applications) that were recently introduced to minimize the footprint of
2993 the hash map.
2994
2995
2996 @c ***********************************************************************
2997 @menu
2998 * Analysis::
2999 * Solution::
3000 * Migration::
3001 * Conclusion::
3002 * Availability::
3003 @end menu
3004
3005 @node Analysis
3006 @subsubsection Analysis
3007 @c %**end of header
3008
3009 The main reason for the "excessive" memory consumption by the hash map is
3010 that GNUnet uses 512-bit cryptographic hash codes --- and the
3011 (multi-)hash map also uses the same 512-bit 'struct GNUNET_HashCode'. As
3012 a result, storing just the keys requires 64 bytes of memory for each key.
3013 As some applications like to keep a large number of entries in the hash
3014 map (after all, that's what maps are good for), 64 bytes per hash is
3015 significant: keeping a pointer to the value and having a linked list for
3016 collisions consume between 8 and 16 bytes, and 'malloc' may add about the
3017 same overhead per allocation, putting us in the 16 to 32 byte per entry
3018 ballpark. Adding a 64-byte key then triples the overall memory
3019 requirement for the hash map.
3020
3021 To make things "worse", most of the time storing the key in the hash map
3022 is not required: it is typically already in memory elsewhere! In most
3023 cases, the values stored in the hash map are some application-specific
3024 struct that _also_ contains the hash. Here is a simplified example:
3025
3026 @example
3027 struct MyValue @{
3028 struct GNUNET_HashCode key;
3029 unsigned int my_data; @};
3030
3031 // ...
3032 val = GNUNET_malloc (sizeof (struct MyValue));
3033 val->key = key;
3034 val->my_data = 42;
3035 GNUNET_CONTAINER_multihashmap_put (map, &key, val, ...);
3036 @end example
3037
3038 This is a common pattern as later the entries might need to be removed,
3039 and at that time it is convenient to have the key immediately at hand:
3040
3041 @example
3042 GNUNET_CONTAINER_multihashmap_remove (map, &val->key, val);
3043 @end example
3044
3045
3046 Note that here we end up with two times 64 bytes for the key, plus maybe
3047 64 bytes total for the rest of the 'struct MyValue' and the map entry in
3048 the hash map. The resulting redundant storage of the key increases
3049 overall memory consumption per entry from the "optimal" 128 bytes to 192
3050 bytes. This is not just an extreme example: overheads in practice are
3051 actually sometimes close to those highlighted in this example. This is
3052 especially true for maps with a significant number of entries, as there
3053 we tend to really try to keep the entries small.
3054
3055 @c ***********************************************************************
3056 @node Solution
3057 @subsubsection Solution
3058 @c %**end of header
3059
3060 The solution that has now been implemented is to @strong{optionally}
3061 allow the hash map to not make a (deep) copy of the hash but instead have
3062 a pointer to the hash/key in the entry. This reduces the memory
3063 consumption for the key from 64 bytes to 4 to 8 bytes. However, it can
3064 also only work if the key is actually stored in the entry (which is the
3065 case most of the time) and if the entry does not modify the key (which in
3066 all of the code I'm aware of has been always the case if there key is
3067 stored in the entry). Finally, when the client stores an entry in the
3068 hash map, it @strong{must} provide a pointer to the key within the entry,
3069 not just a pointer to a transient location of the key. If
3070 the client code does not meet these requirements, the result is a dangling
3071 pointer and undefined behavior of the (multi-)hash map API.
3072
3073 @c ***********************************************************************
3074 @node Migration
3075 @subsubsection Migration
3076 @c %**end of header
3077
3078 To use the new feature, first check that the values contain the respective
3079 key (and never modify it). Then, all calls to
3080 @code{GNUNET_CONTAINER_multihashmap_put} on the respective map must be
3081 audited and most likely changed to pass a pointer into the value's struct.
3082 For the initial example, the new code would look like this:
3083
3084 @example
3085 struct MyValue @{
3086 struct GNUNET_HashCode key;
3087 unsigned int my_data; @};
3088
3089 // ...
3090 val = GNUNET_malloc (sizeof (struct MyValue));
3091 val->key = key; val->my_data = 42;
3092 GNUNET_CONTAINER_multihashmap_put (map, &val->key, val, ...);
3093 @end example
3094
3095
3096 Note that @code{&val} was changed to @code{&val->key} in the argument to
3097 the @code{put} call. This is critical as often @code{key} is on the stack
3098 or in some other transient data structure and thus having the hash map
3099 keep a pointer to @code{key} would not work. Only the key inside of
3100 @code{val} has the same lifetime as the entry in the map (this must of
3101 course be checked as well). Naturally, @code{val->key} must be
3102 intiialized before the @code{put} call. Once all @code{put} calls have
3103 been converted and double-checked, you can change the call to create the
3104 hash map from
3105
3106 @example
3107 map =
3108 GNUNET_CONTAINER_multihashmap_create (SIZE, GNUNET_NO);
3109 @end example
3110
3111 to
3112
3113 @example
3114 map = GNUNET_CONTAINER_multihashmap_create (SIZE, GNUNET_YES);
3115 @end example
3116
3117 If everything was done correctly, you now use about 60 bytes less memory
3118 per entry in @code{map}. However, if now (or in the future) any call to
3119 @code{put} does not ensure that the given key is valid until the entry is
3120 removed from the map, undefined behavior is likely to be observed.
3121
3122 @c ***********************************************************************
3123 @node Conclusion
3124 @subsubsection Conclusion
3125 @c %**end of header
3126
3127 The new optimization can is often applicable and can result in a
3128 reduction in memory consumption of up to 30% in practice. However, it
3129 makes the code less robust as additional invariants are imposed on the
3130 multi hash map client. Thus applications should refrain from enabling the
3131 new mode unless the resulting performance increase is deemed significant
3132 enough. In particular, it should generally not be used in new code (wait
3133 at least until benchmarks exist).
3134
3135 @c ***********************************************************************
3136 @node Availability
3137 @subsubsection Availability
3138 @c %**end of header
3139
3140 The new multi hash map code was committed in SVN 24319 (will be in GNUnet
3141 0.9.4). Various subsystems (transport, core, dht, file-sharing) were
3142 previously audited and modified to take advantage of the new capability.
3143 In particular, memory consumption of the file-sharing service is expected
3144 to drop by 20-30% due to this change.
3145
3146
3147 @cindex CONTAINER_MDLL API
3148 @node CONTAINER_MDLL API
3149 @subsection CONTAINER_MDLL API
3150 @c %**end of header
3151
3152 This text documents the GNUNET_CONTAINER_MDLL API. The
3153 GNUNET_CONTAINER_MDLL API is similar to the GNUNET_CONTAINER_DLL API in
3154 that it provides operations for the construction and manipulation of
3155 doubly-linked lists. The key difference to the (simpler) DLL-API is that
3156 the MDLL-version allows a single element (instance of a "struct") to be
3157 in multiple linked lists at the same time.
3158
3159 Like the DLL API, the MDLL API stores (most of) the data structures for
3160 the doubly-linked list with the respective elements; only the 'head' and
3161 'tail' pointers are stored "elsewhere" --- and the application needs to
3162 provide the locations of head and tail to each of the calls in the
3163 MDLL API. The key difference for the MDLL API is that the "next" and
3164 "previous" pointers in the struct can no longer be simply called "next"
3165 and "prev" --- after all, the element may be in multiple doubly-linked
3166 lists, so we cannot just have one "next" and one "prev" pointer!
3167
3168 The solution is to have multiple fields that must have a name of the
3169 format "next_XX" and "prev_XX" where "XX" is the name of one of the
3170 doubly-linked lists. Here is a simple example:
3171
3172 @example
3173 struct MyMultiListElement @{
3174   struct MyMultiListElement *next_ALIST;
3175   struct MyMultiListElement *prev_ALIST;
3176   struct MyMultiListElement *next_BLIST;
3177   struct MyMultiListElement *prev_BLIST;
3178   void
3179   *data;
3180 @};
3181 @end example
3182
3183
3184 Note that by convention, we use all-uppercase letters for the list names.
3185 In addition, the program needs to have a location for the head and tail
3186 pointers for both lists, for example:
3187
3188 @example
3189 static struct MyMultiListElement *head_ALIST;
3190 static struct MyMultiListElement *tail_ALIST;
3191 static struct MyMultiListElement *head_BLIST;
3192 static struct MyMultiListElement *tail_BLIST;
3193 @end example
3194
3195
3196 Using the MDLL-macros, we can now insert an element into the ALIST:
3197
3198 @example
3199 GNUNET_CONTAINER_MDLL_insert (ALIST, head_ALIST, tail_ALIST, element);
3200 @end example
3201
3202
3203 Passing "ALIST" as the first argument to MDLL specifies which of the
3204 next/prev fields in the 'struct MyMultiListElement' should be used. The
3205 extra "ALIST" argument and the "_ALIST" in the names of the
3206 next/prev-members are the only differences between the MDDL and DLL-API.
3207 Like the DLL-API, the MDLL-API offers functions for inserting (at head,
3208 at tail, after a given element) and removing elements from the list.
3209 Iterating over the list should be done by directly accessing the
3210 "next_XX" and/or "prev_XX" members.
3211
3212 @cindex Automatic Restart Manager
3213 @cindex ARM
3214 @node Automatic Restart Manager (ARM)
3215 @section Automatic Restart Manager (ARM)
3216 @c %**end of header
3217
3218 GNUnet's Automated Restart Manager (ARM) is the GNUnet service responsible
3219 for system initialization and service babysitting. ARM starts and halts
3220 services, detects configuration changes and restarts services impacted by
3221 the changes as needed. It's also responsible for restarting services in
3222 case of crashes and is planned to incorporate automatic debugging for
3223 diagnosing service crashes providing developers insights about crash
3224 reasons. The purpose of this document is to give GNUnet developer an idea
3225 about how ARM works and how to interact with it.
3226
3227 @menu
3228 * Basic functionality::
3229 * Key configuration options::
3230 * ARM - Availability::
3231 * Reliability::
3232 @end menu
3233
3234 @c ***********************************************************************
3235 @node Basic functionality
3236 @subsection Basic functionality
3237 @c %**end of header
3238
3239 @itemize @bullet
3240 @item ARM source code can be found under "src/arm".@ Service processes are
3241 managed by the functions in "gnunet-service-arm.c" which is controlled
3242 with "gnunet-arm.c" (main function in that file is ARM's entry point).
3243
3244 @item The functions responsible for communicating with ARM , starting and
3245 stopping services -including ARM service itself- are provided by the
3246 ARM API "arm_api.c".@ Function: GNUNET_ARM_connect() returns to the caller
3247 an ARM handle after setting it to the caller's context (configuration and
3248 scheduler in use). This handle can be used afterwards by the caller to
3249 communicate with ARM. Functions GNUNET_ARM_start_service() and
3250 GNUNET_ARM_stop_service() are used for starting and stopping services
3251 respectively.
3252
3253 @item A typical example of using these basic ARM services can be found in
3254 file test_arm_api.c. The test case connects to ARM, starts it, then uses
3255 it to start a service "resolver", stops the "resolver" then stops "ARM".
3256 @end itemize
3257
3258 @c ***********************************************************************
3259 @node Key configuration options
3260 @subsection Key configuration options
3261 @c %**end of header
3262
3263 Configurations for ARM and services should be available in a .conf file
3264 (As an example, see test_arm_api_data.conf). When running ARM, the
3265 configuration file to use should be passed to the command:
3266
3267 @example
3268 $ gnunet-arm -s -c configuration_to_use.conf
3269 @end example
3270
3271 If no configuration is passed, the default configuration file will be used
3272 (see GNUNET_PREFIX/share/gnunet/defaults.conf which is created from
3273 contrib/defaults.conf).@ Each of the services is having a section starting
3274 by the service name between square brackets, for example: "[arm]".
3275 The following options configure how ARM configures or interacts with the
3276 various services:
3277
3278 @table @asis
3279
3280 @item PORT Port number on which the service is listening for incoming TCP
3281 connections. ARM will start the services should it notice a request at
3282 this port.
3283
3284 @item HOSTNAME Specifies on which host the service is deployed. Note
3285 that ARM can only start services that are running on the local system
3286 (but will not check that the hostname matches the local machine name).
3287 This option is used by the @code{gnunet_client_lib.h} implementation to
3288 determine which system to connect to. The default is "localhost".
3289
3290 @item BINARY The name of the service binary file.
3291
3292 @item OPTIONS To be passed to the service.
3293
3294 @item PREFIX A command to pre-pend to the actual command, for example,
3295 running a service with "valgrind" or "gdb"
3296
3297 @item DEBUG Run in debug mode (much verbosity).
3298
3299 @item AUTOSTART ARM will listen to UNIX domain socket and/or TCP port of
3300 the service and start the service on-demand.
3301
3302 @item FORCESTART ARM will always start this service when the peer
3303 is started.
3304
3305 @item ACCEPT_FROM IPv4 addresses the service accepts connections from.
3306
3307 @item ACCEPT_FROM6 IPv6 addresses the service accepts connections from.
3308
3309 @end table
3310
3311
3312 Options that impact the operation of ARM overall are in the "[arm]"
3313 section. ARM is a normal service and has (except for AUTOSTART) all of the
3314 options that other services do. In addition, ARM has the
3315 following options:
3316
3317 @table @asis
3318
3319 @item GLOBAL_PREFIX Command to be pre-pended to all services that are
3320 going to run.
3321
3322 @item GLOBAL_POSTFIX Global option that will be supplied to all the
3323 services that are going to run.
3324
3325 @end table
3326
3327 @c ***********************************************************************
3328 @node ARM - Availability
3329 @subsection ARM - Availability
3330 @c %**end of header
3331
3332 As mentioned before, one of the features provided by ARM is starting
3333 services on demand. Consider the example of one service "client" that
3334 wants to connect to another service a "server". The "client" will ask ARM
3335 to run the "server". ARM starts the "server". The "server" starts
3336 listening to incoming connections. The "client" will establish a
3337 connection with the "server". And then, they will start to communicate
3338 together.@ One problem with that scheme is that it's slow!@
3339 The "client" service wants to communicate with the "server" service at
3340 once and is not willing wait for it to be started and listening to
3341 incoming connections before serving its request.@ One solution for that
3342 problem will be that ARM starts all services as default services. That
3343 solution will solve the problem, yet, it's not quite practical, for some
3344 services that are going to be started can never be used or are going to
3345 be used after a relatively long time.@
3346 The approach followed by ARM to solve this problem is as follows:
3347
3348 @itemize @bullet
3349
3350 @item For each service having a PORT field in the configuration file and
3351 that is not one of the default services ( a service that accepts incoming
3352 connections from clients), ARM creates listening sockets for all addresses
3353 associated with that service.
3354
3355 @item The "client" will immediately establish a connection with
3356 the "server".
3357
3358 @item ARM --- pretending to be the "server" --- will listen on the
3359 respective port and notice the incoming connection from the "client"
3360 (but not accept it), instead
3361
3362 @item Once there is an incoming connection, ARM will start the "server",
3363 passing on the listen sockets (now, the service is started and can do its
3364 work).
3365
3366 @item Other client services now can directly connect directly to the
3367 "server".
3368
3369 @end itemize
3370
3371 @c ***********************************************************************
3372 @node Reliability
3373 @subsection Reliability
3374
3375 One of the features provided by ARM, is the automatic restart of crashed
3376 services.@ ARM needs to know which of the running services died. Function
3377 "gnunet-service-arm.c/maint_child_death()" is responsible for that. The
3378 function is scheduled to run upon receiving a SIGCHLD signal. The
3379 function, then, iterates ARM's list of services running and monitors
3380 which service has died (crashed). For all crashing services, ARM restarts
3381 them.@
3382 Now, considering the case of a service having a serious problem causing it
3383 to crash each time it's started by ARM. If ARM keeps blindly restarting
3384 such a service, we are going to have the pattern:
3385 start-crash-restart-crash-restart-crash and so forth!! Which is of course
3386 not practical.@
3387 For that reason, ARM schedules the service to be restarted after waiting
3388 for some delay that grows exponentially with each crash/restart of that
3389 service.@ To clarify the idea, considering the following example:
3390
3391 @itemize @bullet
3392
3393 @item Service S crashed.
3394
3395 @item ARM receives the SIGCHLD and inspects its list of services to find
3396 the dead one(s).
3397
3398 @item ARM finds S dead and schedules it for restarting after "backoff"
3399 time which is initially set to 1ms. ARM will double the backoff time
3400 correspondent to S (now backoff(S) = 2ms)
3401
3402 @item Because there is a severe problem with S, it crashed again.
3403
3404 @item Again ARM receives the SIGCHLD and detects that it's S again that's
3405 crashed. ARM schedules it for restarting but after its new backoff time
3406 (which became 2ms), and doubles its backoff time (now backoff(S) = 4).
3407
3408 @item and so on, until backoff(S) reaches a certain threshold
3409 (@code{EXPONENTIAL_BACKOFF_THRESHOLD} is set to half an hour),
3410 after reaching it, backoff(S) will remain half an hour,
3411 hence ARM won't be busy for a lot of time trying to restart a
3412 problematic service.
3413 @end itemize
3414
3415 @cindex TRANSPORT Subsystem
3416 @node TRANSPORT Subsystem
3417 @section TRANSPORT Subsystem
3418 @c %**end of header
3419
3420 This chapter documents how the GNUnet transport subsystem works. The
3421 GNUnet transport subsystem consists of three main components: the
3422 transport API (the interface used by the rest of the system to access the
3423 transport service), the transport service itself (most of the interesting
3424 functions, such as choosing transports, happens here) and the transport
3425 plugins. A transport plugin is a concrete implementation for how two
3426 GNUnet peers communicate; many plugins exist, for example for
3427 communication via TCP, UDP, HTTP, HTTPS and others. Finally, the
3428 transport subsystem uses supporting code, especially the NAT/UPnP
3429 library to help with tasks such as NAT traversal.
3430
3431 Key tasks of the transport service include:
3432
3433 @itemize @bullet
3434
3435 @item Create our HELLO message, notify clients and neighbours if our HELLO
3436 changes (using NAT library as necessary)
3437
3438 @item Validate HELLOs from other peers (send PING), allow other peers to
3439 validate our HELLO's addresses (send PONG)
3440
3441 @item Upon request, establish connections to other peers (using address
3442 selection from ATS subsystem) and maintain them (again using PINGs and
3443 PONGs) as long as desired
3444
3445 @item Accept incoming connections, give ATS service the opportunity to
3446 switch communication channels
3447
3448 @item Notify clients about peers that have connected to us or that have
3449 been disconnected from us
3450
3451 @item If a (stateful) connection goes down unexpectedly (without explicit
3452 DISCONNECT), quickly attempt to recover (without notifying clients) but do
3453 notify clients quickly if reconnecting fails
3454
3455 @item Send (payload) messages arriving from clients to other peers via
3456 transport plugins and receive messages from other peers, forwarding
3457 those to clients
3458
3459 @item Enforce inbound traffic limits (using flow-control if it is
3460 applicable); outbound traffic limits are enforced by CORE, not by us (!)
3461
3462 @item Enforce restrictions on P2P connection as specified by the blacklist
3463 configuration and blacklisting clients
3464 @end itemize
3465
3466 Note that the term "clients" in the list above really refers to the
3467 GNUnet-CORE service, as CORE is typically the only client of the
3468 transport service.
3469
3470 @menu
3471 * Address validation protocol::
3472 @end menu
3473
3474 @node Address validation protocol
3475 @subsection Address validation protocol
3476 @c %**end of header
3477
3478 This section documents how the GNUnet transport service validates
3479 connections with other peers. It is a high-level description of the
3480 protocol necessary to understand the details of the implementation. It
3481 should be noted that when we talk about PING and PONG messages in this
3482 section, we refer to transport-level PING and PONG messages, which are
3483 different from core-level PING and PONG messages (both in implementation
3484 and function).
3485
3486 The goal of transport-level address validation is to minimize the chances
3487 of a successful man-in-the-middle attack against GNUnet peers on the
3488 transport level. Such an attack would not allow the adversary to decrypt
3489 the P2P transmissions, but a successful attacker could at least measure
3490 traffic volumes and latencies (raising the adversaries capablities by
3491 those of a global passive adversary in the worst case). The scenarios we
3492 are concerned about is an attacker, Mallory, giving a @code{HELLO} to
3493 Alice that claims to be for Bob, but contains Mallory's IP address
3494 instead of Bobs (for some transport).
3495 Mallory would then forward the traffic to Bob (by initiating a
3496 connection to Bob and claiming to be Alice). As a further
3497 complication, the scheme has to work even if say Alice is behind a NAT
3498 without traversal support and hence has no address of her own (and thus
3499 Alice must always initiate the connection to Bob).
3500
3501 An additional constraint is that @code{HELLO} messages do not contain a
3502 cryptographic signature since other peers must be able to edit
3503 (i.e. remove) addresses from the @code{HELLO} at any time (this was
3504 not true in GNUnet 0.8.x). A basic @strong{assumption} is that each peer
3505 knows the set of possible network addresses that it @strong{might}
3506 be reachable under (so for example, the external IP address of the
3507 NAT plus the LAN address(es) with the respective ports).
3508
3509 The solution is the following. If Alice wants to validate that a given
3510 address for Bob is valid (i.e. is actually established @strong{directly}
3511 with the intended target), she sends a PING message over that connection
3512 to Bob. Note that in this case, Alice initiated the connection so only
3513 Alice knows which address was used for sure (Alice may be behind NAT, so
3514 whatever address Bob sees may not be an address Alice knows she has).
3515 Bob checks that the address given in the @code{PING} is actually one
3516 of Bob's addresses (ie: does not belong to Mallory), and if it is,
3517 sends back a @code{PONG} (with a signature that says that Bob
3518 owns/uses the address from the @code{PING}).
3519 Alice checks the signature and is happy if it is valid and the address
3520 in the @code{PONG} is the address Alice used.
3521 This is similar to the 0.8.x protocol where the @code{HELLO} contained a
3522 signature from Bob for each address used by Bob.
3523 Here, the purpose code for the signature is
3524 @code{GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN}. After this, Alice will
3525 remember Bob's address and consider the address valid for a while (12h in
3526 the current implementation). Note that after this exchange, Alice only
3527 considers Bob's address to be valid, the connection itself is not
3528 considered 'established'. In particular, Alice may have many addresses
3529 for Bob that Alice considers valid.
3530
3531 @c TODO: reference Footnotes so that I don't have to duplicate the
3532 @c footnotes or add them to an index at the end. Is this possible at
3533 @c all in Texinfo?
3534 The @code{PONG} message is protected with a nonce/challenge against replay
3535 attacks@footnote{@uref{http://en.wikipedia.org/wiki/Replay_attack, replay}}
3536 and uses an expiration time for the signature (but those are almost
3537 implementation details).
3538
3539 @cindex NAT library
3540 @node NAT library
3541 @section NAT library
3542 @c %**end of header
3543
3544 The goal of the GNUnet NAT library is to provide a general-purpose API for
3545 NAT traversal @strong{without} third-party support. So protocols that
3546 involve contacting a third peer to help establish a connection between
3547 two peers are outside of the scope of this API. That does not mean that
3548 GNUnet doesn't support involving a third peer (we can do this with the
3549 distance-vector transport or using application-level protocols), it just
3550 means that the NAT API is not concerned with this possibility. The API is
3551 written so that it will work for IPv6-NAT in the future as well as
3552 current IPv4-NAT. Furthermore, the NAT API is always used, even for peers
3553 that are not behind NAT --- in that case, the mapping provided is simply
3554 the identity.
3555
3556 NAT traversal is initiated by calling @code{GNUNET_NAT_register}. Given a
3557 set of addresses that the peer has locally bound to (TCP or UDP), the NAT
3558 library will return (via callback) a (possibly longer) list of addresses
3559 the peer @strong{might} be reachable under. Internally, depending on the
3560 configuration, the NAT library will try to punch a hole (using UPnP) or
3561 just "know" that the NAT was manually punched and generate the respective
3562 external IP address (the one that should be globally visible) based on
3563 the given information.
3564
3565 The NAT library also supports ICMP-based NAT traversal. Here, the other
3566 peer can request connection-reversal by this peer (in this special case,
3567 the peer is even allowed to configure a port number of zero). If the NAT
3568 library detects a connection-reversal request, it returns the respective
3569 target address to the client as well. It should be noted that
3570 connection-reversal is currently only intended for TCP, so other plugins
3571 @strong{must} pass @code{NULL} for the reversal callback. Naturally, the
3572 NAT library also supports requesting connection reversal from a remote
3573 peer (@code{GNUNET_NAT_run_client}).
3574
3575 Once initialized, the NAT handle can be used to test if a given address is
3576 possibly a valid address for this peer (@code{GNUNET_NAT_test_address}).
3577 This is used for validating our addresses when generating PONGs.
3578
3579 Finally, the NAT library contains an API to test if our NAT configuration
3580 is correct. Using @code{GNUNET_NAT_test_start} @strong{before} binding to
3581 the respective port, the NAT library can be used to test if the
3582 configuration works. The test function act as a local client, initialize
3583 the NAT traversal and then contact a @code{gnunet-nat-server} (running by
3584 default on @code{gnunet.org}) and ask for a connection to be established.
3585 This way, it is easy to test if the current NAT configuration is valid.
3586
3587 @node Distance-Vector plugin
3588 @section Distance-Vector plugin
3589 @c %**end of header
3590
3591 The Distance Vector (DV) transport is a transport mechanism that allows
3592 peers to act as relays for each other, thereby connecting peers that would
3593 otherwise be unable to connect. This gives a larger connection set to
3594 applications that may work better with more peers to choose from (for
3595 example, File Sharing and/or DHT).
3596
3597 The Distance Vector transport essentially has two functions. The first is
3598 "gossiping" connection information about more distant peers to directly
3599 connected peers. The second is taking messages intended for non-directly
3600 connected peers and encapsulating them in a DV wrapper that contains the
3601 required information for routing the message through forwarding peers. Via
3602 gossiping, optimal routes through the known DV neighborhood are discovered
3603 and utilized and the message encapsulation provides some benefits in
3604 addition to simply getting the message from the correct source to the
3605 proper destination.
3606
3607 The gossiping function of DV provides an up to date routing table of
3608 peers that are available up to some number of hops. We call this a
3609 fisheye view of the network (like a fish, nearby objects are known while
3610 more distant ones unknown). Gossip messages are sent only to directly
3611 connected peers, but they are sent about other knowns peers within the
3612 "fisheye distance". Whenever two peers connect, they immediately gossip
3613 to each other about their appropriate other neighbors. They also gossip
3614 about the newly connected peer to previously
3615 connected neighbors. In order to keep the routing tables up to date,
3616 disconnect notifications are propogated as gossip as well (because
3617 disconnects may not be sent/received, timeouts are also used remove
3618 stagnant routing table entries).
3619
3620 Routing of messages via DV is straightforward. When the DV transport is
3621 notified of a message destined for a non-direct neighbor, the appropriate
3622 forwarding peer is selected, and the base message is encapsulated in a DV
3623 message which contains information about the initial peer and the intended
3624 recipient. At each forwarding hop, the initial peer is validated (the
3625 forwarding peer ensures that it has the initial peer in its neighborhood,
3626 otherwise the message is dropped). Next the base message is
3627 re-encapsulated in a new DV message for the next hop in the forwarding
3628 chain (or delivered to the current peer, if it has arrived at the
3629 destination).
3630
3631 Assume a three peer network with peers Alice, Bob and Carol. Assume that
3632
3633 @example
3634 Alice <-> Bob and Bob <-> Carol
3635 @end example
3636
3637 @noindent
3638 are direct (e.g. over TCP or UDP transports) connections, but that
3639 Alice cannot directly connect to Carol.
3640 This may be the case due to NAT or firewall restrictions, or perhaps
3641 based on one of the peers respective configurations. If the Distance
3642 Vector transport is enabled on all three peers, it will automatically
3643 discover (from the gossip protocol) that Alice and Carol can connect via
3644 Bob and provide a "virtual" Alice <-> Carol connection. Routing between
3645 Alice and Carol happens as follows; Alice creates a message destined for
3646 Carol and notifies the DV transport about it. The DV transport at Alice
3647 looks up Carol in the routing table and finds that the message must be
3648 sent through Bob for Carol. The message is encapsulated setting Alice as
3649 the initiator and Carol as the destination and sent to Bob. Bob receives
3650 the messages, verifies that both Alice and Carol are known to Bob, and
3651 re-wraps the message in a new DV message for Carol.
3652 The DV transport at Carol receives this message, unwraps the original
3653 message, and delivers it to Carol as though it came directly from Alice.
3654
3655 @cindex SMTP plugin
3656 @node SMTP plugin
3657 @section SMTP plugin
3658 @c %**end of header
3659
3660 This section describes the new SMTP transport plugin for GNUnet as it
3661 exists in the 0.7.x and 0.8.x branch. SMTP support is currently not
3662 available in GNUnet 0.9.x. This page also describes the transport layer
3663 abstraction (as it existed in 0.7.x and 0.8.x) in more detail and gives
3664 some benchmarking results. The performance results presented are quite
3665 old and maybe outdated at this point.
3666
3667 @itemize @bullet
3668 @item Why use SMTP for a peer-to-peer transport?
3669 @item SMTPHow does it work?
3670 @item How do I configure my peer?
3671 @item How do I test if it works?
3672 @item How fast is it?
3673 @item Is there any additional documentation?
3674 @end itemize
3675
3676
3677 @menu
3678 * Why use SMTP for a peer-to-peer transport?::
3679 * How does it work?::
3680 * How do I configure my peer?::
3681 * How do I test if it works?::
3682 * How fast is it?::
3683 @end menu
3684
3685 @node Why use SMTP for a peer-to-peer transport?
3686 @subsection Why use SMTP for a peer-to-peer transport?
3687 @c %**end of header
3688
3689 There are many reasons why one would not want to use SMTP:
3690
3691 @itemize @bullet
3692 @item SMTP is using more bandwidth than TCP, UDP or HTTP
3693 @item SMTP has a much higher latency.
3694 @item SMTP requires significantly more computation (encoding and decoding
3695 time) for the peers.
3696 @item SMTP is significantly more complicated to configure.
3697 @item SMTP may be abused by tricking GNUnet into sending mail to@
3698 non-participating third parties.
3699 @end itemize
3700
3701 So why would anybody want to use SMTP?
3702 @itemize @bullet
3703 @item SMTP can be used to contact peers behind NAT boxes (in virtual
3704 private networks).
3705 @item SMTP can be used to circumvent policies that limit or prohibit
3706 peer-to-peer traffic by masking as "legitimate" traffic.
3707 @item SMTP uses E-mail addresses which are independent of a specific IP,
3708 which can be useful to address peers that use dynamic IP addresses.
3709 @item SMTP can be used to initiate a connection (e.g. initial address
3710 exchange) and peers can then negotiate the use of a more efficient
3711 protocol (e.g. TCP) for the actual communication.
3712 @end itemize
3713
3714 In summary, SMTP can for example be used to send a message to a peer
3715 behind a NAT box that has a dynamic IP to tell the peer to establish a
3716 TCP connection to a peer outside of the private network. Even an
3717 extraordinary overhead for this first message would be irrelevant in this
3718 type of situation.
3719
3720 @node How does it work?
3721 @subsection How does it work?
3722 @c %**end of header
3723
3724 When a GNUnet peer needs to send a message to another GNUnet peer that has
3725 advertised (only) an SMTP transport address, GNUnet base64-encodes the
3726 message and sends it in an E-mail to the advertised address. The
3727 advertisement contains a filter which is placed in the E-mail header,
3728 such that the receiving host can filter the tagged E-mails and forward it
3729 to the GNUnet peer process. The filter can be specified individually by
3730 each peer and be changed over time. This makes it impossible to censor
3731 GNUnet E-mail messages by searching for a generic filter.
3732
3733 @node How do I configure my peer?
3734 @subsection How do I configure my peer?
3735 @c %**end of header
3736
3737 First, you need to configure @code{procmail} to filter your inbound E-mail
3738 for GNUnet traffic. The GNUnet messages must be delivered into a pipe, for
3739 example @code{/tmp/gnunet.smtp}. You also need to define a filter that is
3740 used by @command{procmail} to detect GNUnet messages. You are free to
3741 choose whichever filter you like, but you should make sure that it does
3742 not occur in your other E-mail. In our example, we will use
3743 @code{X-mailer: GNUnet}. The @code{~/.procmailrc} configuration file then
3744 looks like this:
3745
3746 @example
3747 :0:
3748 * ^X-mailer: GNUnet
3749 /tmp/gnunet.smtp
3750 # where do you want your other e-mail delivered to
3751 # (default: /var/spool/mail/)
3752 :0: /var/spool/mail/
3753 @end example
3754
3755 After adding this file, first make sure that your regular E-mail still
3756 works (e.g. by sending an E-mail to yourself). Then edit the GNUnet
3757 configuration. In the section @code{SMTP} you need to specify your E-mail
3758 address under @code{EMAIL}, your mail server (for outgoing mail) under
3759 @code{SERVER}, the filter (X-mailer: GNUnet in the example) under
3760 @code{FILTER} and the name of the pipe under @code{PIPE}.@ The completed
3761 section could then look like this:
3762
3763 @example
3764 EMAIL = me@@mail.gnu.org MTU = 65000 SERVER = mail.gnu.org:25 FILTER =
3765 "X-mailer: GNUnet" PIPE = /tmp/gnunet.smtp
3766 @end example
3767
3768 Finally, you need to add @code{smtp} to the list of @code{TRANSPORTS} in
3769 the @code{GNUNETD} section. GNUnet peers will use the E-mail address that
3770 you specified to contact your peer until the advertisement times out.
3771 Thus, if you are not sure if everything works properly or if you are not
3772 planning to be online for a long time, you may want to configure this
3773 timeout to be short, e.g. just one hour. For this, set
3774 @code{HELLOEXPIRES} to @code{1} in the @code{GNUNETD} section.
3775
3776 This should be it, but you may probably want to test it first.
3777
3778 @node How do I test if it works?
3779 @subsection How do I test if it works?
3780 @c %**end of header
3781
3782 Any transport can be subjected to some rudimentary tests using the
3783 @code{gnunet-transport-check} tool. The tool sends a message to the local
3784 node via the transport and checks that a valid message is received. While
3785 this test does not involve other peers and can not check if firewalls or
3786 other network obstacles prohibit proper operation, this is a great
3787 testcase for the SMTP transport since it tests pretty much nearly all of
3788 the functionality.
3789
3790 @code{gnunet-transport-check} should only be used without running
3791 @code{gnunetd} at the same time. By default, @code{gnunet-transport-check}
3792 tests all transports that are specified in the configuration file. But
3793 you can specifically test SMTP by giving the option
3794 @code{--transport=smtp}.
3795
3796 Note that this test always checks if a transport can receive and send.
3797 While you can configure most transports to only receive or only send
3798 messages, this test will only work if you have configured the transport
3799 to send and receive messages.
3800
3801 @node How fast is it?
3802 @subsection How fast is it?
3803 @c %**end of header
3804
3805 We have measured the performance of the UDP, TCP and SMTP transport layer
3806 directly and when used from an application using the GNUnet core.
3807 Measureing just the transport layer gives the better view of the actual
3808 overhead of the protocol, whereas evaluating the transport from the
3809 application puts the overhead into perspective from a practical point of
3810 view.
3811
3812 The loopback measurements of the SMTP transport were performed on three
3813 different machines spanning a range of modern SMTP configurations. We
3814 used a PIII-800 running RedHat 7.3 with the Purdue Computer Science
3815 configuration which includes filters for spam. We also used a Xenon 2 GHZ
3816 with a vanilla RedHat 8.0 sendmail configuration. Furthermore, we used
3817 qmail on a PIII-1000 running Sorcerer GNU Linux (SGL). The numbers for
3818 UDP and TCP are provided using the SGL configuration. The qmail benchmark
3819 uses qmail's internal filtering whereas the sendmail benchmarks relies on
3820 procmail to filter and deliver the mail. We used the transport layer to
3821 send a message of b bytes (excluding transport protocol headers) directly
3822 to the local machine. This way, network latency and packet loss on the
3823 wire have no impact on the timings. n messages were sent sequentially over
3824 the transport layer, sending message i+1 after the i-th message was
3825 received. All messages were sent over the same connection and the time to
3826 establish the connection was not taken into account since this overhead is
3827 miniscule in practice --- as long as a connection is used for a
3828 significant number of messages.
3829
3830 @multitable @columnfractions .20 .15 .15 .15 .15 .15
3831 @headitem Transport @tab UDP @tab TCP @tab SMTP (Purdue sendmail)
3832 @tab SMTP (RH 8.0) @tab SMTP (SGL qmail)
3833 @item  11 bytes @tab 31 ms @tab 55 ms @tab  781 s @tab 77 s @tab 24 s
3834 @item  407 bytes @tab 37 ms @tab 62 ms @tab  789 s @tab 78 s @tab 25 s
3835 @item 1,221 bytes @tab 46 ms @tab 73 ms @tab  804 s @tab 78 s @tab 25 s
3836 @end multitable
3837
3838 The benchmarks show that UDP and TCP are, as expected, both significantly
3839 faster compared with any of the SMTP services. Among the SMTP
3840 implementations, there can be significant differences depending on the
3841 SMTP configuration. Filtering with an external tool like procmail that
3842 needs to re-parse its configuration for each mail can be very expensive.
3843 Applying spam filters can also significantly impact the performance of
3844 the underlying SMTP implementation. The microbenchmark shows that SMTP
3845 can be a viable solution for initiating peer-to-peer sessions: a couple of
3846 seconds to connect to a peer are probably not even going to be noticed by
3847 users. The next benchmark measures the possible throughput for a
3848 transport. Throughput can be measured by sending multiple messages in
3849 parallel and measuring packet loss. Note that not only UDP but also the
3850 TCP transport can actually loose messages since the TCP implementation
3851 drops messages if the @code{write} to the socket would block. While the
3852 SMTP protocol never drops messages itself, it is often so
3853 slow that only a fraction of the messages can be sent and received in the
3854 given time-bounds. For this benchmark we report the message loss after
3855 allowing t time for sending m messages. If messages were not sent (or
3856 received) after an overall timeout of t, they were considered lost. The
3857 benchmark was performed using two Xeon 2 GHZ machines running RedHat 8.0
3858 with sendmail. The machines were connected with a direct 100 MBit ethernet
3859 connection.@ Figures udp1200, tcp1200 and smtp-MTUs show that the
3860 throughput for messages of size 1,200 octects is 2,343 kbps, 3,310 kbps
3861 and 6 kbps for UDP, TCP and SMTP respectively. The high per-message
3862 overhead of SMTP can be improved by increasing the MTU, for example, an
3863 MTU of 12,000 octets improves the throughput to 13 kbps as figure
3864 smtp-MTUs shows. Our research paper) has some more details on the
3865 benchmarking results.
3866
3867 @cindex Bluetooth plugin
3868 @node Bluetooth plugin
3869 @section Bluetooth plugin
3870 @c %**end of header
3871
3872 This page describes the new Bluetooth transport plugin for GNUnet. The
3873 plugin is still in the testing stage so don't expect it to work
3874 perfectly. If you have any questions or problems just post them here or
3875 ask on the IRC channel.
3876
3877 @itemize @bullet
3878 @item What do I need to use the Bluetooth plugin transport?
3879 @item BluetoothHow does it work?
3880 @item What possible errors should I be aware of?
3881 @item How do I configure my peer?
3882 @item How can I test it?
3883 @end itemize
3884
3885 @menu
3886 * What do I need to use the Bluetooth plugin transport?::
3887 * How does it work2?::
3888 * What possible errors should I be aware of?::
3889 * How do I configure my peer2?::
3890 * How can I test it?::
3891 * The implementation of the Bluetooth transport plugin::
3892 @end menu
3893
3894 @node What do I need to use the Bluetooth plugin transport?
3895 @subsection What do I need to use the Bluetooth plugin transport?
3896 @c %**end of header
3897
3898 If you are a GNU/Linux user and you want to use the Bluetooth
3899 transport plugin you should install the
3900 @command{BlueZ development libraries} (if they aren't already
3901 installed).
3902 For instructions about how to install the libraries you should
3903 check out the BlueZ site
3904 (@uref{http://www.bluez.org/, http://www.bluez.org}). If you don't know if
3905 you have the necesarry libraries, don't worry, just run the GNUnet
3906 configure script and you will be able to see a notification at the end
3907 which will warn you if you don't have the necessary libraries.
3908
3909 If you are a Windows user you should have installed the
3910 @emph{MinGW}/@emph{MSys2} with the latest updates (especially the
3911 @emph{ws2bth} header). If this is your first build of GNUnet on Windows
3912 you should check out the SBuild repository. It will semi-automatically
3913 assembles a @emph{MinGW}/@emph{MSys2} installation with a lot of extra
3914 packages which are needed for the GNUnet build. So this will ease your
3915 work!@ Finally you just have to be sure that you have the correct drivers
3916 for your Bluetooth device installed and that your device is on and in a
3917 discoverable mode. The Windows Bluetooth Stack supports only the RFCOMM
3918 protocol so we cannot turn on your device programatically!
3919
3920 @c FIXME: Change to unique title
3921 @node How does it work2?
3922 @subsection How does it work2?
3923 @c %**end of header
3924
3925 The Bluetooth transport plugin uses virtually the same code as the WLAN
3926 plugin and only the helper binary is different. The helper takes a single
3927 argument, which represents the interface name and is specified in the
3928 configuration file. Here are the basic steps that are followed by the
3929 helper binary used on GNU/Linux:
3930
3931 @itemize @bullet
3932 @item it verifies if the name corresponds to a Bluetooth interface name
3933 @item it verifies if the iterface is up (if it is not, it tries to bring
3934 it up)
3935 @item it tries to enable the page and inquiry scan in order to make the
3936 device discoverable and to accept incoming connection requests
3937 @emph{The above operations require root access so you should start the
3938 transport plugin with root privileges.}
3939 @item it finds an available port number and registers a SDP service which
3940 will be used to find out on which port number is the server listening on
3941 and switch the socket in listening mode
3942 @item it sends a HELLO message with its address
3943 @item finally it forwards traffic from the reading sockets to the STDOUT
3944 and from the STDIN to the writing socket
3945 @end itemize
3946
3947 Once in a while the device will make an inquiry scan to discover the
3948 nearby devices and it will send them randomly HELLO messages for peer
3949 discovery.
3950
3951 @node What possible errors should I be aware of?
3952 @subsection What possible errors should I be aware of?
3953 @c %**end of header
3954
3955 @emph{This section is dedicated for GNU/Linux users}
3956
3957 Well there are many ways in which things could go wrong but I will try to
3958 present some tools that you could use to debug and some scenarios.
3959
3960 @itemize @bullet
3961
3962 @item @code{bluetoothd -n -d} : use this command to enable logging in the
3963 foreground and to print the logging messages
3964
3965 @item @code{hciconfig}: can be used to configure the Bluetooth devices.
3966 If you run it without any arguments it will print information about the
3967 state of the interfaces. So if you receive an error that the device
3968 couldn't be brought up you should try to bring it manually and to see if
3969 it works (use @code{hciconfig -a hciX up}). If you can't and the
3970 Bluetooth address has the form 00:00:00:00:00:00 it means that there is
3971 something wrong with the D-Bus daemon or with the Bluetooth daemon. Use
3972 @code{bluetoothd} tool to see the logs
3973
3974 @item @code{sdptool} can be used to control and interogate SDP servers.
3975 If you encounter problems regarding the SDP server (like the SDP server is
3976 down) you should check out if the D-Bus daemon is running correctly and to
3977 see if the Bluetooth daemon started correctly(use @code{bluetoothd} tool).
3978 Also, sometimes the SDP service could work but somehow the device couldn't
3979 register his service. Use @code{sdptool browse [dev-address]} to see if
3980 the service is registered. There should be a service with the name of the
3981 interface and GNUnet as provider.
3982
3983 @item @code{hcitool} : another useful tool which can be used to configure
3984 the device and to send some particular commands to it.
3985
3986 @item @code{hcidump} : could be used for low level debugging
3987 @end itemize
3988
3989 @c FIXME: A more unique name
3990 @node How do I configure my peer2?
3991 @subsection How do I configure my peer2?
3992 @c %**end of header
3993
3994 On GNU/Linux, you just have to be sure that the interface name
3995 corresponds to the one that you want to use.
3996 Use the @code{hciconfig} tool to check that.
3997 By default it is set to hci0 but you can change it.
3998
3999 A basic configuration looks like this:
4000
4001 @example
4002 [transport-bluetooth]
4003 # Name of the interface (typically hciX)
4004 INTERFACE = hci0
4005 # Real hardware, no testing
4006 TESTMODE = 0 TESTING_IGNORE_KEYS = ACCEPT_FROM;
4007 @end example
4008
4009 In order to use the Bluetooth transport plugin when the transport service
4010 is started, you must add the plugin name to the default transport service
4011 plugins list. For example:
4012
4013 @example
4014 [transport] ...  PLUGINS = dns bluetooth ...
4015 @end example
4016
4017 If you want to use only the Bluetooth plugin set
4018 @emph{PLUGINS = bluetooth}
4019
4020 On Windows, you cannot specify which device to use. The only thing that
4021 you should do is to add @emph{bluetooth} on the plugins list of the
4022 transport service.
4023
4024 @node How can I test it?
4025 @subsection How can I test it?
4026 @c %**end of header
4027
4028 If you have two Bluetooth devices on the same machine and you are using
4029 GNU/Linux you must:
4030
4031 @itemize @bullet
4032
4033 @item create two different file configuration (one which will use the
4034 first interface (@emph{hci0}) and the other which will use the second
4035 interface (@emph{hci1})). Let's name them @emph{peer1.conf} and
4036 @emph{peer2.conf}.
4037
4038 @item run @emph{gnunet-peerinfo -c peerX.conf -s} in order to generate the
4039 peers private keys. The @strong{X} must be replace with 1 or 2.
4040
4041 @item run @emph{gnunet-arm -c peerX.conf -s -i=transport} in order to
4042 start the transport service. (Make sure that you have "bluetooth" on the
4043 transport plugins list if the Bluetooth transport service doesn't start.)
4044
4045 @item run @emph{gnunet-peerinfo -c peer1.conf -s} to get the first peer's
4046 ID. If you already know your peer ID (you saved it from the first
4047 command), this can be skipped.
4048
4049 @item run @emph{gnunet-transport -c peer2.conf -p=PEER1_ID -s} to start
4050 sending data for benchmarking to the other peer.
4051
4052 @end itemize
4053
4054
4055 This scenario will try to connect the second peer to the first one and
4056 then start sending data for benchmarking.
4057
4058 On Windows you cannot test the plugin functionality using two Bluetooth
4059 devices from the same machine because after you install the drivers there
4060 will occur some conflicts between the Bluetooth stacks. (At least that is
4061 what happend on my machine : I wasn't able to use the Bluesoleil stack and
4062 the WINDCOMM one in the same time).
4063
4064 If you have two different machines and your configuration files are good
4065 you can use the same scenario presented on the begining of this section.
4066
4067 Another way to test the plugin functionality is to create your own
4068 application which will use the GNUnet framework with the Bluetooth
4069 transport service.
4070
4071 @node The implementation of the Bluetooth transport plugin
4072 @subsection The implementation of the Bluetooth transport plugin
4073 @c %**end of header
4074
4075 This page describes the implementation of the Bluetooth transport plugin.
4076
4077 First I want to remind you that the Bluetooth transport plugin uses
4078 virtually the same code as the WLAN plugin and only the helper binary is
4079 different. Also the scope of the helper binary from the Bluetooth
4080 transport plugin is the same as the one used for the wlan transport
4081 plugin: it acceses the interface and then it forwards traffic in both
4082 directions between the Bluetooth interface and stdin/stdout of the
4083 process involved.
4084
4085 The Bluetooth plugin transport could be used both on GNU/Linux and Windows
4086 platforms.
4087
4088 @itemize @bullet
4089 @item Linux functionality
4090 @item Windows functionality
4091 @item Pending Features
4092 @end itemize
4093
4094
4095
4096 @menu
4097 * Linux functionality::
4098 * THE INITIALIZATION::
4099 * THE LOOP::
4100 * Details about the broadcast implementation::
4101 * Windows functionality::
4102 * Pending features::
4103 @end menu
4104
4105 @node Linux functionality
4106 @subsubsection Linux functionality
4107 @c %**end of header
4108
4109 In order to implement the plugin functionality on GNU/Linux I
4110 used the BlueZ stack.
4111 For the communication with the other devices I used the RFCOMM
4112 protocol. Also I used the HCI protocol to gain some control over the
4113 device. The helper binary takes a single argument (the name of the
4114 Bluetooth interface) and is separated in two stages:
4115
4116 @c %** 'THE INITIALIZATION' should be in bigger letters or stand out, not
4117 @c %** starting a new section?
4118 @node THE INITIALIZATION
4119 @subsubsection THE INITIALIZATION
4120
4121 @itemize @bullet
4122 @item first, it checks if we have root privilegies
4123 (@emph{Remember that we need to have root privilegies in order to be able
4124 to bring the interface up if it is down or to change its state.}).
4125
4126 @item second, it verifies if the interface with the given name exists.
4127
4128 @strong{If the interface with that name exists and it is a Bluetooth
4129 interface:}
4130
4131 @item it creates a RFCOMM socket which will be used for listening and call
4132 the @emph{open_device} method
4133
4134 On the @emph{open_device} method:
4135 @itemize @bullet
4136 @item creates a HCI socket used to send control events to the the device
4137 @item searches for the device ID using the interface name
4138 @item saves the device MAC address
4139 @item checks if the interface is down and tries to bring it UP
4140 @item checks if the interface is in discoverable mode and tries to make it
4141 discoverable
4142 @item closes the HCI socket and binds the RFCOMM one
4143 @item switches the RFCOMM socket in listening mode
4144 @item registers the SDP service (the service will be used by the other
4145 devices to get the port on which this device is listening on)
4146 @end itemize
4147
4148 @item drops the root privilegies
4149
4150 @strong{If the interface is not a Bluetooth interface the helper exits
4151 with a suitable error}
4152 @end itemize
4153
4154 @c %** Same as for @node entry above
4155 @node THE LOOP
4156 @subsubsection THE LOOP
4157
4158 The helper binary uses a list where it saves all the connected neighbour
4159 devices (@emph{neighbours.devices}) and two buffers (@emph{write_pout} and
4160 @emph{write_std}). The first message which is send is a control message
4161 with the device's MAC address in order to announce the peer presence to
4162 the neighbours. Here are a short description of what happens in the main
4163 loop:
4164
4165 @itemize @bullet
4166 @item Every time when it receives something from the STDIN it processes
4167 the data and saves the message in the first buffer (@emph{write_pout}).
4168 When it has something in the buffer, it gets the destination address from
4169 the buffer, searches the destination address in the list (if there is no
4170 connection with that device, it creates a new one and saves it to the
4171 list) and sends the message.
4172 @item Every time when it receives something on the listening socket it
4173 accepts the connection and saves the socket on a list with the reading
4174 sockets. @item Every time when it receives something from a reading
4175 socket it parses the message, verifies the CRC and saves it in the
4176 @emph{write_std} buffer in order to be sent later to the STDOUT.
4177 @end itemize
4178
4179 So in the main loop we use the select function to wait until one of the
4180 file descriptor saved in one of the two file descriptors sets used is
4181 ready to use. The first set (@emph{rfds}) represents the reading set and
4182 it could contain the list with the reading sockets, the STDIN file
4183 descriptor or the listening socket. The second set (@emph{wfds}) is the
4184 writing set and it could contain the sending socket or the STDOUT file
4185 descriptor. After the select function returns, we check which file
4186 descriptor is ready to use and we do what is supposed to do on that kind
4187 of event. @emph{For example:} if it is the listening socket then we
4188 accept a new connection and save the socket in the reading list; if it is
4189 the STDOUT file descriptor, then we write to STDOUT the message from the
4190 @emph{write_std} buffer.
4191
4192 To find out on which port a device is listening on we connect to the local
4193 SDP server and searche the registered service for that device.
4194
4195 @emph{You should be aware of the fact that if the device fails to connect
4196 to another one when trying to send a message it will attempt one more
4197 time. If it fails again, then it skips the message.}
4198 @emph{Also you should know that the transport Bluetooth plugin has
4199 support for @strong{broadcast messages}.}
4200
4201 @node Details about the broadcast implementation
4202 @subsubsection Details about the broadcast implementation
4203 @c %**end of header
4204
4205 First I want to point out that the broadcast functionality for the CONTROL
4206 messages is not implemented in a conventional way. Since the inquiry scan
4207 time is too big and it will take some time to send a message to all the
4208 discoverable devices I decided to tackle the problem in a different way.
4209 Here is how I did it:
4210
4211 @itemize @bullet
4212 @item If it is the first time when I have to broadcast a message I make an
4213 inquiry scan and save all the devices' addresses to a vector.
4214 @item After the inquiry scan ends I take the first address from the list
4215 and I try to connect to it. If it fails, I try to connect to the next one.
4216 If it succeeds, I save the socket to a list and send the message to the
4217 device.
4218 @item When I have to broadcast another message, first I search on the list
4219 for a new device which I'm not connected to. If there is no new device on
4220 the list I go to the beginning of the list and send the message to the
4221 old devices. After 5 cycles I make a new inquiry scan to check out if
4222 there are new discoverable devices and save them to the list. If there
4223 are no new discoverable devices I reset the cycling counter and go again
4224 through the old list and send messages to the devices saved in it.
4225 @end itemize
4226
4227 @strong{Therefore}:
4228
4229 @itemize @bullet
4230 @item every time when I have a broadcast message I look up on the list
4231 for a new device and send the message to it
4232 @item if I reached the end of the list for 5 times and I'm connected to
4233 all the devices from the list I make a new inquiry scan.
4234 @emph{The number of the list's cycles after an inquiry scan could be
4235 increased by redefining the MAX_LOOPS variable}
4236 @item when there are no new devices I send messages to the old ones.
4237 @end itemize
4238
4239 Doing so, the broadcast control messages will reach the devices but with
4240 delay.
4241
4242 @emph{NOTICE:} When I have to send a message to a certain device first I
4243 check on the broadcast list to see if we are connected to that device. If
4244 not we try to connect to it and in case of success we save the address and
4245 the socket on the list. If we are already connected to that device we
4246 simply use the socket.
4247
4248 @node Windows functionality
4249 @subsubsection Windows functionality
4250 @c %**end of header
4251
4252 For Windows I decided to use the Microsoft Bluetooth stack which has the
4253 advantage of coming standard from Windows XP SP2. The main disadvantage is
4254 that it only supports the RFCOMM protocol so we will not be able to have
4255 a low level control over the Bluetooth device. Therefore it is the user
4256 responsability to check if the device is up and in the discoverable mode.
4257 Also there are no tools which could be used for debugging in order to read
4258 the data coming from and going to a Bluetooth device, which obviously
4259 hindered my work. Another thing that slowed down the implementation of the
4260 plugin (besides that I wasn't too accomodated with the win32 API) was that
4261 there were some bugs on MinGW regarding the Bluetooth. Now they are solved
4262 but you should keep in mind that you should have the latest updates
4263 (especially the @emph{ws2bth} header).
4264
4265 Besides the fact that it uses the Windows Sockets, the Windows
4266 implemenation follows the same principles as the GNU/Linux one:
4267
4268 @itemize @bullet
4269 @item It has a initalization part where it initializes the
4270 Windows Sockets, creates a RFCOMM socket which will be binded and switched
4271 to the listening mode and registers a SDP service. In the Microsoft
4272 Bluetooth API there are two ways to work with the SDP:
4273 @itemize @bullet
4274 @item an easy way which works with very simple service records
4275 @item a hard way which is useful when you need to update or to delete the
4276 record
4277 @end itemize
4278 @end itemize
4279
4280 Since I only needed the SDP service to find out on which port the device
4281 is listening on and that did not change, I decided to use the easy way.
4282 In order to register the service I used the @emph{WSASetService} function
4283 and I generated the @emph{Universally Unique Identifier} with the
4284 @emph{guidgen.exe} Windows's tool.
4285
4286 In the loop section the only difference from the GNU/Linux implementation
4287 is that I used the @code{GNUNET_NETWORK} library for
4288 functions like @emph{accept}, @emph{bind}, @emph{connect} or
4289 @emph{select}. I decided to use the
4290 @code{GNUNET_NETWORK} library because I also needed to interact
4291 with the STDIN and STDOUT handles and on Windows
4292 the select function is only defined for sockets,
4293 and it will not work for arbitrary file handles.
4294
4295 Another difference between GNU/Linux and Windows implementation is that in
4296 GNU/Linux, the Bluetooth address is represented in 48 bits
4297 while in Windows is represented in 64 bits.
4298 Therefore I had to do some changes on @emph{plugin_transport_wlan} header.
4299
4300 Also, currently on Windows the Bluetooth plugin doesn't have support for
4301 broadcast messages. When it receives a broadcast message it will skip it.
4302
4303 @node Pending features
4304 @subsubsection Pending features
4305 @c %**end of header
4306
4307 @itemize @bullet
4308 @item Implement the broadcast functionality on Windows @emph{(currently
4309 working on)}
4310 @item Implement a testcase for the helper :@ @emph{The testcase
4311 consists of a program which emaluates the plugin and uses the helper. It
4312 will simulate connections, disconnections and data transfers.}
4313 @end itemize
4314
4315 If you have a new idea about a feature of the plugin or suggestions about
4316 how I could improve the implementation you are welcome to comment or to
4317 contact me.
4318
4319 @node WLAN plugin
4320 @section WLAN plugin
4321 @c %**end of header
4322
4323 This section documents how the wlan transport plugin works. Parts which
4324 are not implemented yet or could be better implemented are described at
4325 the end.
4326
4327 @cindex ATS Subsystem
4328 @node ATS Subsystem
4329 @section ATS Subsystem
4330 @c %**end of header
4331
4332 ATS stands for "automatic transport selection", and the function of ATS in
4333 GNUnet is to decide on which address (and thus transport plugin) should
4334 be used for two peers to communicate, and what bandwidth limits should be
4335 imposed on such an individual connection. To help ATS make an informed
4336 decision, higher-level services inform the ATS service about their
4337 requirements and the quality of the service rendered. The ATS service
4338 also interacts with the transport service to be appraised of working
4339 addresses and to communicate its resource allocation decisions. Finally,
4340 the ATS service's operation can be observed using a monitoring API.
4341
4342 The main logic of the ATS service only collects the available addresses,
4343 their performance characteristics and the applications requirements, but
4344 does not make the actual allocation decision. This last critical step is
4345 left to an ATS plugin, as we have implemented (currently three) different
4346 allocation strategies which differ significantly in their performance and
4347 maturity, and it is still unclear if any particular plugin is generally
4348 superior.
4349
4350 @cindex CORE Subsystem
4351 @node CORE Subsystem
4352 @section CORE Subsystem
4353 @c %**end of header
4354
4355 The CORE subsystem in GNUnet is responsible for securing link-layer
4356 communications between nodes in the GNUnet overlay network. CORE builds
4357 on the TRANSPORT subsystem which provides for the actual, insecure,
4358 unreliable link-layer communication (for example, via UDP or WLAN), and
4359 then adds fundamental security to the connections:
4360
4361 @itemize @bullet
4362 @item confidentiality with so-called perfect forward secrecy; we use
4363 ECDHE@footnote{@uref{http://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman, Elliptic-curve Diffie---Hellman}}
4364 powered by Curve25519
4365 @footnote{@uref{http://cr.yp.to/ecdh.html, Curve25519}} for the key
4366 exchange and then use symmetric encryption, encrypting with both AES-256
4367 @footnote{@uref{http://en.wikipedia.org/wiki/Rijndael, AES-256}} and
4368 Twofish @footnote{@uref{http://en.wikipedia.org/wiki/Twofish, Twofish}}
4369 @item @uref{http://en.wikipedia.org/wiki/Authentication, authentication}
4370 is achieved by signing the ephemeral keys using Ed25519
4371 @footnote{@uref{http://ed25519.cr.yp.to/, Ed25519}}, a deterministic
4372 variant of ECDSA
4373 @footnote{@uref{http://en.wikipedia.org/wiki/ECDSA, ECDSA}}
4374 @item integrity protection (using SHA-512
4375 @footnote{@uref{http://en.wikipedia.org/wiki/SHA-2, SHA-512}} to do
4376 encrypt-then-MAC
4377 @footnote{@uref{http://en.wikipedia.org/wiki/Authenticated_encryption, encrypt-then-MAC}})
4378 @item Replay
4379 @footnote{@uref{http://en.wikipedia.org/wiki/Replay_attack, replay}}
4380 protection (using nonces, timestamps, challenge-response,
4381 message counters and ephemeral keys)
4382 @item liveness (keep-alive messages, timeout)
4383 @end itemize
4384
4385 @menu
4386 * Limitations::
4387 * When is a peer "connected"?::
4388 * libgnunetcore::
4389 * The CORE Client-Service Protocol::
4390 * The CORE Peer-to-Peer Protocol::
4391 @end menu
4392
4393 @cindex core subsystem limitations
4394 @node Limitations
4395 @subsection Limitations
4396 @c %**end of header
4397
4398 CORE does not perform
4399 @uref{http://en.wikipedia.org/wiki/Routing, routing}; using CORE it is
4400 only possible to communicate with peers that happen to already be
4401 "directly" connected with each other. CORE also does not have an
4402 API to allow applications to establish such "direct" connections --- for
4403 this, applications can ask TRANSPORT, but TRANSPORT might not be able to
4404 establish a "direct" connection. The TOPOLOGY subsystem is responsible for
4405 trying to keep a few "direct" connections open at all times. Applications
4406 that need to talk to particular peers should use the CADET subsystem, as
4407 it can establish arbitrary "indirect" connections.
4408
4409 Because CORE does not perform routing, CORE must only be used directly by
4410 applications that either perform their own routing logic (such as
4411 anonymous file-sharing) or that do not require routing, for example
4412 because they are based on flooding the network. CORE communication is
4413 unreliable and delivery is possibly out-of-order. Applications that
4414 require reliable communication should use the CADET service. Each
4415 application can only queue one message per target peer with the CORE
4416 service at any time; messages cannot be larger than approximately
4417 63 kilobytes. If messages are small, CORE may group multiple messages
4418 (possibly from different applications) prior to encryption. If permitted
4419 by the application (using the @uref{http://baus.net/on-tcp_cork/, cork}
4420 option), CORE may delay transmissions to facilitate grouping of multiple
4421 small messages. If cork is not enabled, CORE will transmit the message as
4422 soon as TRANSPORT allows it (TRANSPORT is responsible for limiting
4423 bandwidth and congestion control). CORE does not allow flow control;
4424 applications are expected to process messages at line-speed. If flow
4425 control is needed, applications should use the CADET service.
4426
4427 @cindex when is a peer connected
4428 @node When is a peer "connected"?
4429 @subsection When is a peer "connected"?
4430 @c %**end of header
4431
4432 In addition to the security features mentioned above, CORE also provides
4433 one additional key feature to applications using it, and that is a
4434 limited form of protocol-compatibility checking. CORE distinguishes
4435 between TRANSPORT-level connections (which enable communication with other
4436 peers) and application-level connections. Applications using the CORE API
4437 will (typically) learn about application-level connections from CORE, and
4438 not about TRANSPORT-level connections. When a typical application uses
4439 CORE, it will specify a set of message types
4440 (from @code{gnunet_protocols.h}) that it understands. CORE will then
4441 notify the application about connections it has with other peers if and
4442 only if those applications registered an intersecting set of message
4443 types with their CORE service. Thus, it is quite possible that CORE only
4444 exposes a subset of the established direct connections to a particular
4445 application --- and different applications running above CORE might see
4446 different sets of connections at the same time.
4447
4448 A special case are applications that do not register a handler for any
4449 message type.
4450 CORE assumes that these applications merely want to monitor connections
4451 (or "all" messages via other callbacks) and will notify those applications
4452 about all connections. This is used, for example, by the
4453 @code{gnunet-core} command-line tool to display the active connections.
4454 Note that it is also possible that the TRANSPORT service has more active
4455 connections than the CORE service, as the CORE service first has to
4456 perform a key exchange with connecting peers before exchanging information
4457 about supported message types and notifying applications about the new
4458 connection.
4459
4460 @cindex libgnunetcore
4461 @node libgnunetcore
4462 @subsection libgnunetcore
4463 @c %**end of header
4464
4465 The CORE API (defined in @file{gnunet_core_service.h}) is the basic
4466 messaging API used by P2P applications built using GNUnet. It provides
4467 applications the ability to send and receive encrypted messages to the
4468 peer's "directly" connected neighbours.
4469
4470 As CORE connections are generally "direct" connections,@ applications must
4471 not assume that they can connect to arbitrary peers this way, as "direct"
4472 connections may not always be possible. Applications using CORE are
4473 notified about which peers are connected. Creating new "direct"
4474 connections must be done using the TRANSPORT API.
4475
4476 The CORE API provides unreliable, out-of-order delivery. While the
4477 implementation tries to ensure timely, in-order delivery, both message
4478 losses and reordering are not detected and must be tolerated by the
4479 application. Most important, the core will NOT perform retransmission if
4480 messages could not be delivered.
4481
4482 Note that CORE allows applications to queue one message per connected
4483 peer. The rate at which each connection operates is influenced by the
4484 preferences expressed by local application as well as restrictions
4485 imposed by the other peer. Local applications can express their
4486 preferences for particular connections using the "performance" API of the
4487 ATS service.
4488
4489 Applications that require more sophisticated transmission capabilities
4490 such as TCP-like behavior, or if you intend to send messages to arbitrary
4491 remote peers, should use the CADET API.
4492
4493 The typical use of the CORE API is to connect to the CORE service using
4494 @code{GNUNET_CORE_connect}, process events from the CORE service (such as
4495 peers connecting, peers disconnecting and incoming messages) and send
4496 messages to connected peers using
4497 @code{GNUNET_CORE_notify_transmit_ready}. Note that applications must
4498 cancel pending transmission requests if they receive a disconnect event
4499 for a peer that had a transmission pending; furthermore, queueing more
4500 than one transmission request per peer per application using the
4501 service is not permitted.
4502
4503 The CORE API also allows applications to monitor all communications of the
4504 peer prior to encryption (for outgoing messages) or after decryption (for
4505 incoming messages). This can be useful for debugging, diagnostics or to
4506 establish the presence of cover traffic (for anonymity). As monitoring
4507 applications are often not interested in the payload, the monitoring
4508 callbacks can be configured to only provide the message headers (including
4509 the message type and size) instead of copying the full data stream to the
4510 monitoring client.
4511
4512 The init callback of the @code{GNUNET_CORE_connect} function is called
4513 with the hash of the public key of the peer. This public key is used to
4514 identify the peer globally in the GNUnet network. Applications are
4515 encouraged to check that the provided hash matches the hash that they are
4516 using (as theoretically the application may be using a different
4517 configuration file with a different private key, which would result in
4518 hard to find bugs).
4519
4520 As with most service APIs, the CORE API isolates applications from crashes
4521 of the CORE service. If the CORE service crashes, the application will see
4522 disconnect events for all existing connections. Once the connections are
4523 re-established, the applications will be receive matching connect events.
4524
4525 @cindex core clinet-service protocol
4526 @node The CORE Client-Service Protocol
4527 @subsection The CORE Client-Service Protocol
4528 @c %**end of header
4529
4530 This section describes the protocol between an application using the CORE
4531 service (the client) and the CORE service process itself.
4532
4533
4534 @menu
4535 * Setup2::
4536 * Notifications::
4537 * Sending::
4538 @end menu
4539
4540 @node Setup2
4541 @subsubsection Setup2
4542 @c %**end of header
4543
4544 When a client connects to the CORE service, it first sends a
4545 @code{InitMessage} which specifies options for the connection and a set of
4546 message type values which are supported by the application. The options
4547 bitmask specifies which events the client would like to be notified about.
4548 The options include:
4549
4550 @table @asis
4551 @item GNUNET_CORE_OPTION_NOTHING No notifications
4552 @item GNUNET_CORE_OPTION_STATUS_CHANGE Peers connecting and disconnecting
4553 @item GNUNET_CORE_OPTION_FULL_INBOUND All inbound messages (after
4554 decryption) with full payload
4555 @item GNUNET_CORE_OPTION_HDR_INBOUND Just the @code{MessageHeader}
4556 of all inbound messages
4557 @item GNUNET_CORE_OPTION_FULL_OUTBOUND All outbound
4558 messages (prior to encryption) with full payload
4559 @item GNUNET_CORE_OPTION_HDR_OUTBOUND Just the @code{MessageHeader} of all
4560 outbound messages
4561 @end table
4562
4563 Typical applications will only monitor for connection status changes.
4564
4565 The CORE service responds to the @code{InitMessage} with an
4566 @code{InitReplyMessage} which contains the peer's identity. Afterwards,
4567 both CORE and the client can send messages.
4568
4569 @node Notifications
4570 @subsubsection Notifications
4571 @c %**end of header
4572
4573 The CORE will send @code{ConnectNotifyMessage}s and
4574 @code{DisconnectNotifyMessage}s whenever peers connect or disconnect from
4575 the CORE (assuming their type maps overlap with the message types
4576 registered by the client). When the CORE receives a message that matches
4577 the set of message types specified during the @code{InitMessage} (or if
4578 monitoring is enabled in for inbound messages in the options), it sends a
4579 @code{NotifyTrafficMessage} with the peer identity of the sender and the
4580 decrypted payload. The same message format (except with
4581 @code{GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND} for the message type) is
4582 used to notify clients monitoring outbound messages; here, the peer
4583 identity given is that of the receiver.
4584
4585 @node Sending
4586 @subsubsection Sending
4587 @c %**end of header
4588
4589 When a client wants to transmit a message, it first requests a
4590 transmission slot by sending a @code{SendMessageRequest} which specifies
4591 the priority, deadline and size of the message. Note that these values
4592 may be ignored by CORE. When CORE is ready for the message, it answers
4593 with a @code{SendMessageReady} response. The client can then transmit the
4594 payload with a @code{SendMessage} message. Note that the actual message
4595 size in the @code{SendMessage} is allowed to be smaller than the size in
4596 the original request. A client may at any time send a fresh
4597 @code{SendMessageRequest}, which then superceeds the previous
4598 @code{SendMessageRequest}, which is then no longer valid. The client can
4599 tell which @code{SendMessageRequest} the CORE service's
4600 @code{SendMessageReady} message is for as all of these messages contain a
4601 "unique" request ID (based on a counter incremented by the client
4602 for each request).
4603
4604 @cindex CORE Peer-to-Peer Protocol
4605 @node The CORE Peer-to-Peer Protocol
4606 @subsection The CORE Peer-to-Peer Protocol
4607 @c %**end of header
4608
4609
4610 @menu
4611 * Creating the EphemeralKeyMessage::
4612 * Establishing a connection::
4613 * Encryption and Decryption::
4614 * Type maps::
4615 @end menu
4616
4617 @cindex EphemeralKeyMessage creation
4618 @node Creating the EphemeralKeyMessage
4619 @subsubsection Creating the EphemeralKeyMessage
4620 @c %**end of header
4621
4622 When the CORE service starts, each peer creates a fresh ephemeral (ECC)
4623 public-private key pair and signs the corresponding
4624 @code{EphemeralKeyMessage} with its long-term key (which we usually call
4625 the peer's identity; the hash of the public long term key is what results
4626 in a @code{struct GNUNET_PeerIdentity} in all GNUnet APIs. The ephemeral
4627 key is ONLY used for an ECDHE@footnote{@uref{http://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman, Elliptic-curve Diffie---Hellman}}
4628 exchange by the CORE service to establish symmetric session keys. A peer
4629 will use the same @code{EphemeralKeyMessage} for all peers for
4630 @code{REKEY_FREQUENCY}, which is usually 12 hours. After that time, it
4631 will create a fresh ephemeral key (forgetting the old one) and broadcast
4632 the new @code{EphemeralKeyMessage} to all connected peers, resulting in
4633 fresh symmetric session keys. Note that peers independently decide on
4634 when to discard ephemeral keys; it is not a protocol violation to discard
4635 keys more often. Ephemeral keys are also never stored to disk; restarting
4636 a peer will thus always create a fresh ephemeral key. The use of ephemeral
4637 keys is what provides @uref{http://en.wikipedia.org/wiki/Forward_secrecy, forward secrecy}.
4638
4639 Just before transmission, the @code{EphemeralKeyMessage} is patched to
4640 reflect the current sender_status, which specifies the current state of
4641 the connection from the point of view of the sender. The possible values
4642 are:
4643
4644 @itemize @bullet
4645 @item @code{KX_STATE_DOWN} Initial value, never used on the network
4646 @item @code{KX_STATE_KEY_SENT} We sent our ephemeral key, do not know the
4647 key of the other peer
4648 @item @code{KX_STATE_KEY_RECEIVED} This peer has received a valid
4649 ephemeral key of the other peer, but we are waiting for the other peer to
4650 confirm it's authenticity (ability to decode) via challenge-response.
4651 @item @code{KX_STATE_UP} The connection is fully up from the point of
4652 view of the sender (now performing keep-alives)
4653 @item @code{KX_STATE_REKEY_SENT} The sender has initiated a rekeying
4654 operation; the other peer has so far failed to confirm a working
4655 connection using the new ephemeral key
4656 @end itemize
4657
4658 @node Establishing a connection
4659 @subsubsection Establishing a connection
4660 @c %**end of header
4661
4662 Peers begin their interaction by sending a @code{EphemeralKeyMessage} to
4663 the other peer once the TRANSPORT service notifies the CORE service about
4664 the connection.
4665 A peer receiving an @code{EphemeralKeyMessage} with a status
4666 indicating that the sender does not have the receiver's ephemeral key, the
4667 receiver's @code{EphemeralKeyMessage} is sent in response.
4668 Additionally, if the receiver has not yet confirmed the authenticity of
4669 the sender, it also sends an (encrypted)@code{PingMessage} with a
4670 challenge (and the identity of the target) to the other peer. Peers
4671 receiving a @code{PingMessage} respond with an (encrypted)
4672 @code{PongMessage} which includes the challenge. Peers receiving a
4673 @code{PongMessage} check the challenge, and if it matches set the
4674 connection to @code{KX_STATE_UP}.
4675
4676 @node Encryption and Decryption
4677 @subsubsection Encryption and Decryption
4678 @c %**end of header
4679
4680 All functions related to the key exchange and encryption/decryption of
4681 messages can be found in @file{gnunet-service-core_kx.c} (except for the
4682 cryptographic primitives, which are in @file{util/crypto*.c}).
4683 Given the key material from ECDHE, a Key derivation function
4684 @footnote{@uref{https://en.wikipedia.org/wiki/Key_derivation_function, Key derivation function}}
4685 is used to derive two pairs of encryption and decryption keys for AES-256
4686 and TwoFish, as well as initialization vectors and authentication keys
4687 (for HMAC@footnote{@uref{https://en.wikipedia.org/wiki/HMAC, HMAC}}).
4688 The HMAC is computed over the encrypted payload.
4689 Encrypted messages include an iv_seed and the HMAC in the header.
4690
4691 Each encrypted message in the CORE service includes a sequence number and
4692 a timestamp in the encrypted payload. The CORE service remembers the
4693 largest observed sequence number and a bit-mask which represents which of
4694 the previous 32 sequence numbers were already used.
4695 Messages with sequence numbers lower than the largest observed sequence
4696 number minus 32 are discarded. Messages with a timestamp that is less
4697 than @code{REKEY_TOLERANCE} off (5 minutes) are also discarded. This of
4698 course means that system clocks need to be reasonably synchronized for
4699 peers to be able to communicate. Additionally, as the ephemeral key
4700 changes every 12 hours, a peer would not even be able to decrypt messages
4701 older than 12 hours.
4702
4703 @node Type maps
4704 @subsubsection Type maps
4705 @c %**end of header
4706
4707 Once an encrypted connection has been established, peers begin to exchange
4708 type maps. Type maps are used to allow the CORE service to determine which
4709 (encrypted) connections should be shown to which applications. A type map
4710 is an array of 65536 bits representing the different types of messages
4711 understood by applications using the CORE service. Each CORE service
4712 maintains this map, simply by setting the respective bit for each message
4713 type supported by any of the applications using the CORE service. Note
4714 that bits for message types embedded in higher-level protocols (such as
4715 MESH) will not be included in these type maps.
4716
4717 Typically, the type map of a peer will be sparse. Thus, the CORE service
4718 attempts to compress its type map using @code{gzip}-style compression
4719 ("deflate") prior to transmission. However, if the compression fails to
4720 compact the map, the map may also be transmitted without compression
4721 (resulting in @code{GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP} or
4722 @code{GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP} messages respectively).
4723 Upon receiving a type map, the respective CORE service notifies
4724 applications about the connection to the other peer if they support any
4725 message type indicated in the type map (or no message type at all).
4726 If the CORE service experience a connect or disconnect event from an
4727 application, it updates its type map (setting or unsetting the respective
4728 bits) and notifies its neighbours about the change.
4729 The CORE services of the neighbours then in turn generate connect and
4730 disconnect events for the peer that sent the type map for their respective
4731 applications. As CORE messages may be lost, the CORE service confirms
4732 receiving a type map by sending back a
4733 @code{GNUNET_MESSAGE_TYPE_CORE_CONFIRM_TYPE_MAP}. If such a confirmation
4734 (with the correct hash of the type map) is not received, the sender will
4735 retransmit the type map (with exponential back-off).
4736
4737 @cindex CADET Subsystem
4738 @node CADET Subsystem
4739 @section CADET Subsystem
4740
4741 The CADET subsystem in GNUnet is responsible for secure end-to-end
4742 communications between nodes in the GNUnet overlay network. CADET builds
4743 on the CORE subsystem which provides for the link-layer communication and
4744 then adds routing, forwarding and additional security to the connections.
4745 CADET offers the same cryptographic services as CORE, but on an
4746 end-to-end level. This is done so peers retransmitting traffic on behalf
4747 of other peers cannot access the payload data.
4748
4749 @itemize @bullet
4750 @item CADET provides confidentiality with so-called perfect forward
4751 secrecy; we use ECDHE powered by Curve25519 for the key exchange and then
4752 use symmetric encryption, encrypting with both AES-256 and Twofish
4753 @item authentication is achieved by signing the ephemeral keys using
4754 Ed25519, a deterministic variant of ECDSA
4755 @item integrity protection (using SHA-512 to do encrypt-then-MAC, although
4756 only 256 bits are sent to reduce overhead)
4757 @item replay protection (using nonces, timestamps, challenge-response,
4758 message counters and ephemeral keys)
4759 @item liveness (keep-alive messages, timeout)
4760 @end itemize
4761
4762 Additional to the CORE-like security benefits, CADET offers other
4763 properties that make it a more universal service than CORE.
4764
4765 @itemize @bullet
4766 @item CADET can establish channels to arbitrary peers in GNUnet. If a
4767 peer is not immediately reachable, CADET will find a path through the
4768 network and ask other peers to retransmit the traffic on its behalf.
4769 @item CADET offers (optional) reliability mechanisms. In a reliable
4770 channel traffic is guaranteed to arrive complete, unchanged and in-order.
4771 @item CADET takes care of flow and congestion control mechanisms, not
4772 allowing the sender to send more traffic than the receiver or the network
4773 are able to process.
4774 @end itemize
4775
4776 @menu
4777 * libgnunetcadet::
4778 @end menu
4779
4780 @cindex libgnunetcadet
4781 @node libgnunetcadet
4782 @subsection libgnunetcadet
4783
4784
4785 The CADET API (defined in @file{gnunet_cadet_service.h}) is the
4786 messaging API used by P2P applications built using GNUnet.
4787 It provides applications the ability to send and receive encrypted
4788 messages to any peer participating in GNUnet.
4789 The API is heavily base on the CORE API.
4790
4791 CADET delivers messages to other peers in "channels".
4792 A channel is a permanent connection defined by a destination peer
4793 (identified by its public key) and a port number.
4794 Internally, CADET tunnels all channels towards a destiantion peer
4795 using one session key and relays the data on multiple "connections",
4796 independent from the channels.
4797
4798 Each channel has optional paramenters, the most important being the
4799 reliability flag.
4800 Should a message get lost on TRANSPORT/CORE level, if a channel is
4801 created with as reliable, CADET will retransmit the lost message and
4802 deliver it in order to the destination application.
4803
4804 To communicate with other peers using CADET, it is necessary to first
4805 connect to the service using @code{GNUNET_CADET_connect}.
4806 This function takes several parameters in form of callbacks, to allow the
4807 client to react to various events, like incoming channels or channels that
4808 terminate, as well as specify a list of ports the client wishes to listen
4809 to (at the moment it is not possible to start listening on further ports
4810 once connected, but nothing prevents a client to connect several times to
4811 CADET, even do one connection per listening port).
4812 The function returns a handle which has to be used for any further
4813 interaction with the service.
4814
4815 To connect to a remote peer a client has to call the
4816 @code{GNUNET_CADET_channel_create} function. The most important parameters
4817 given are the remote peer's identity (it public key) and a port, which
4818 specifies which application on the remote peer to connect to, similar to
4819 TCP/UDP ports. CADET will then find the peer in the GNUnet network and
4820 establish the proper low-level connections and do the necessary key
4821 exchanges to assure and authenticated, secure and verified communication.
4822 Similar to @code{GNUNET_CADET_connect},@code{GNUNET_CADET_create_channel}
4823 returns a handle to interact with the created channel.
4824
4825 For every message the client wants to send to the remote application,
4826 @code{GNUNET_CADET_notify_transmit_ready} must be called, indicating the
4827 channel on which the message should be sent and the size of the message
4828 (but not the message itself!). Once CADET is ready to send the message,
4829 the provided callback will fire, and the message contents are provided to
4830 this callback.
4831
4832 Please note the CADET does not provide an explicit notification of when a
4833 channel is connected. In loosely connected networks, like big wireless
4834 mesh networks, this can take several seconds, even minutes in the worst
4835 case. To be alerted when a channel is online, a client can call
4836 @code{GNUNET_CADET_notify_transmit_ready} immediately after
4837 @code{GNUNET_CADET_create_channel}. When the callback is activated, it
4838 means that the channel is online. The callback can give 0 bytes to CADET
4839 if no message is to be sent, this is ok.
4840
4841 If a transmission was requested but before the callback fires it is no
4842 longer needed, it can be cancelled with
4843 @code{GNUNET_CADET_notify_transmit_ready_cancel}, which uses the handle
4844 given back by @code{GNUNET_CADET_notify_transmit_ready}.
4845 As in the case of CORE, only one message can be requested at a time: a
4846 client must not call @code{GNUNET_CADET_notify_transmit_ready} again until
4847 the callback is called or the request is cancelled.
4848
4849 When a channel is no longer needed, a client can call
4850 @code{GNUNET_CADET_channel_destroy} to get rid of it.
4851 Note that CADET will try to transmit all pending traffic before notifying
4852 the remote peer of the destruction of the channel, including
4853 retransmitting lost messages if the channel was reliable.
4854
4855 Incoming channels, channels being closed by the remote peer, and traffic
4856 on any incoming or outgoing channels are given to the client when CADET
4857 executes the callbacks given to it at the time of
4858 @code{GNUNET_CADET_connect}.
4859
4860 Finally, when an application no longer wants to use CADET, it should call
4861 @code{GNUNET_CADET_disconnect}, but first all channels and pending
4862 transmissions must be closed (otherwise CADET will complain).
4863
4864 @cindex NSE Subsystem
4865 @node NSE Subsystem
4866 @section NSE Subsystem
4867
4868
4869 NSE stands for @dfn{Network Size Estimation}. The NSE subsystem provides
4870 other subsystems and users with a rough estimate of the number of peers
4871 currently participating in the GNUnet overlay.
4872 The computed value is not a precise number as producing a precise number
4873 in a decentralized, efficient and secure way is impossible.
4874 While NSE's estimate is inherently imprecise, NSE also gives the expected
4875 range. For a peer that has been running in a stable network for a
4876 while, the real network size will typically (99.7% of the time) be in the
4877 range of [2/3 estimate, 3/2 estimate]. We will now give an overview of the
4878 algorithm used to calculate the estimate;
4879 all of the details can be found in this technical report.
4880
4881 @c FIXME: link to the report.
4882
4883 @menu
4884 * Motivation::
4885 * Principle::
4886 * libgnunetnse::
4887 * The NSE Client-Service Protocol::
4888 * The NSE Peer-to-Peer Protocol::
4889 @end menu
4890
4891 @node Motivation
4892 @subsection Motivation
4893
4894
4895 Some subsytems, like DHT, need to know the size of the GNUnet network to
4896 optimize some parameters of their own protocol. The decentralized nature
4897 of GNUnet makes efficient and securely counting the exact number of peers
4898 infeasable. Although there are several decentralized algorithms to count
4899 the number of peers in a system, so far there is none to do so securely.
4900 Other protocols may allow any malicious peer to manipulate the final
4901 result or to take advantage of the system to perform
4902 @dfn{Denial of Service} (DoS) attacks against the network.
4903 GNUnet's NSE protocol avoids these drawbacks.
4904
4905
4906
4907 @menu
4908 * Security::
4909 @end menu
4910
4911 @cindex NSE security
4912 @cindex nse security
4913 @node Security
4914 @subsubsection Security
4915
4916
4917 The NSE subsystem is designed to be resilient against these attacks.
4918 It uses @uref{http://en.wikipedia.org/wiki/Proof-of-work_system, proofs of work}
4919 to prevent one peer from impersonating a large number of participants,
4920 which would otherwise allow an adversary to artifically inflate the
4921 estimate.
4922 The DoS protection comes from the time-based nature of the protocol:
4923 the estimates are calculated periodically and out-of-time traffic is
4924 either ignored or stored for later retransmission by benign peers.
4925 In particular, peers cannot trigger global network communication at will.
4926
4927 @cindex NSE principle
4928 @cindex nse principle
4929 @node Principle
4930 @subsection Principle
4931
4932
4933 The algorithm calculates the estimate by finding the globally closest
4934 peer ID to a random, time-based value.
4935
4936 The idea is that the closer the ID is to the random value, the more
4937 "densely packed" the ID space is, and therefore, more peers are in the
4938 network.
4939
4940
4941
4942 @menu
4943 * Example::
4944 * Algorithm::
4945 * Target value::
4946 * Timing::
4947 * Controlled Flooding::
4948 * Calculating the estimate::
4949 @end menu
4950
4951 @node Example
4952 @subsubsection Example
4953
4954
4955 Suppose all peers have IDs between 0 and 100 (our ID space), and the
4956 random value is 42.
4957 If the closest peer has the ID 70 we can imagine that the average
4958 "distance" between peers is around 30 and therefore the are around 3
4959 peers in the whole ID space. On the other hand, if the closest peer has
4960 the ID 44, we can imagine that the space is rather packed with peers,
4961 maybe as much as 50 of them.
4962 Naturally, we could have been rather unlucky, and there is only one peer
4963 and happens to have the ID 44. Thus, the current estimate is calculated
4964 as the average over multiple rounds, and not just a single sample.
4965
4966 @node Algorithm
4967 @subsubsection Algorithm
4968
4969
4970 Given that example, one can imagine that the job of the subsystem is to
4971 efficiently communicate the ID of the closest peer to the target value
4972 to all the other peers, who will calculate the estimate from it.
4973
4974 @node Target value
4975 @subsubsection Target value
4976
4977 @c %**end of header
4978
4979 The target value itself is generated by hashing the current time, rounded
4980 down to an agreed value. If the rounding amount is 1h (default) and the
4981 time is 12:34:56, the time to hash would be 12:00:00. The process is
4982 repeated each rouning amount (in this example would be every hour).
4983 Every repetition is called a round.
4984
4985 @node Timing
4986 @subsubsection Timing
4987 @c %**end of header
4988
4989 The NSE subsystem has some timing control to avoid everybody broadcasting
4990 its ID all at one. Once each peer has the target random value, it
4991 compares its own ID to the target and calculates the hypothetical size of
4992 the network if that peer were to be the closest.
4993 Then it compares the hypothetical size with the estimate from the previous
4994 rounds. For each value there is an assiciated point in the period,
4995 let's call it "broadcast time". If its own hypothetical estimate
4996 is the same as the previous global estimate, its "broadcast time" will be
4997 in the middle of the round. If its bigger it will be earlier and if its
4998 smaller (the most likely case) it will be later. This ensures that the
4999 peers closests to the target value start broadcasting their ID the first.
5000
5001 @node Controlled Flooding
5002 @subsubsection Controlled Flooding
5003
5004 @c %**end of header
5005
5006 When a peer receives a value, first it verifies that it is closer than the
5007 closest value it had so far, otherwise it answers the incoming message
5008 with a message containing the better value. Then it checks a proof of
5009 work that must be included in the incoming message, to ensure that the
5010 other peer's ID is not made up (otherwise a malicious peer could claim to
5011 have an ID of exactly the target value every round). Once validated, it
5012 compares the brodcast time of the received value with the current time
5013 and if it's not too early, sends the received value to its neighbors.
5014 Otherwise it stores the value until the correct broadcast time comes.
5015 This prevents unnecessary traffic of sub-optimal values, since a better
5016 value can come before the broadcast time, rendering the previous one
5017 obsolete and saving the traffic that would have been used to broadcast it
5018 to the neighbors.
5019
5020 @node Calculating the estimate
5021 @subsubsection Calculating the estimate
5022
5023 @c %**end of header
5024
5025 Once the closest ID has been spread across the network each peer gets the
5026 exact distance betweed this ID and the target value of the round and
5027 calculates the estimate with a mathematical formula described in the tech
5028 report. The estimate generated with this method for a single round is not
5029 very precise. Remember the case of the example, where the only peer is the
5030 ID 44 and we happen to generate the target value 42, thinking there are
5031 50 peers in the network. Therefore, the NSE subsystem remembers the last
5032 64 estimates and calculates an average over them, giving a result of which
5033 usually has one bit of uncertainty (the real size could be half of the
5034 estimate or twice as much). Note that the actual network size is
5035 calculated in powers of two of the raw input, thus one bit of uncertainty
5036 means a factor of two in the size estimate.
5037
5038 @cindex libgnunetnse
5039 @node libgnunetnse
5040 @subsection libgnunetnse
5041
5042 @c %**end of header
5043
5044 The NSE subsystem has the simplest API of all services, with only two
5045 calls: @code{GNUNET_NSE_connect} and @code{GNUNET_NSE_disconnect}.
5046
5047 The connect call gets a callback function as a parameter and this function
5048 is called each time the network agrees on an estimate. This usually is
5049 once per round, with some exceptions: if the closest peer has a late
5050 local clock and starts spreading his ID after everyone else agreed on a
5051 value, the callback might be activated twice in a round, the second value
5052 being always bigger than the first. The default round time is set to
5053 1 hour.
5054
5055 The disconnect call disconnects from the NSE subsystem and the callback
5056 is no longer called with new estimates.
5057
5058
5059
5060 @menu
5061 * Results::
5062 * libgnunetnse - Examples::
5063 @end menu
5064
5065 @node Results
5066 @subsubsection Results
5067
5068 @c %**end of header
5069
5070 The callback provides two values: the average and the
5071 @uref{http://en.wikipedia.org/wiki/Standard_deviation, standard deviation}
5072 of the last 64 rounds. The values provided by the callback function are
5073 logarithmic, this means that the real estimate numbers can be obtained by
5074 calculating 2 to the power of the given value (2average). From a
5075 statistics point of view this means that:
5076
5077 @itemize @bullet
5078 @item 68% of the time the real size is included in the interval
5079 [(2average-stddev), 2]
5080 @item 95% of the time the real size is included in the interval
5081 [(2average-2*stddev, 2^average+2*stddev]
5082 @item 99.7% of the time the real size is included in the interval
5083 [(2average-3*stddev, 2average+3*stddev]
5084 @end itemize
5085
5086 The expected standard variation for 64 rounds in a network of stable size
5087 is 0.2. Thus, we can say that normally:
5088
5089 @itemize @bullet
5090 @item 68% of the time the real size is in the range [-13%, +15%]
5091 @item 95% of the time the real size is in the range [-24%, +32%]
5092 @item 99.7% of the time the real size is in the range [-34%, +52%]
5093 @end itemize
5094
5095 As said in the introduction, we can be quite sure that usually the real
5096 size is between one third and three times the estimate. This can of
5097 course vary with network conditions.
5098 Thus, applications may want to also consider the provided standard
5099 deviation value, not only the average (in particular, if the standard
5100 veriation is very high, the average maybe meaningless: the network size is
5101 changing rapidly).
5102
5103 @node libgnunetnse - Examples
5104 @subsubsection libgnunetnse -Examples
5105
5106 @c %**end of header
5107
5108 Let's close with a couple examples.
5109
5110 @table @asis
5111
5112 @item Average: 10, std dev: 1 Here the estimate would be
5113 2^10 = 1024 peers. @footnote{The range in which we can be 95% sure is:
5114 [2^8, 2^12] = [256, 4096]. We can be very (>99.7%) sure that the network
5115 is not a hundred peers and absolutely sure that it is not a million peers,
5116 but somewhere around a thousand.}
5117
5118 @item Average 22, std dev: 0.2 Here the estimate would be
5119 2^22 = 4 Million peers. @footnote{The range in which we can be 99.7% sure
5120 is: [2^21.4, 2^22.6] = [2.8M, 6.3M]. We can be sure that the network size
5121 is around four million, with absolutely way of it being 1 million.}
5122
5123 @end table
5124
5125 To put this in perspective, if someone remembers the LHC Higgs boson
5126 results, were announced with "5 sigma" and "6 sigma" certainties. In this
5127 case a 5 sigma minimum would be 2 million and a 6 sigma minimum,
5128 1.8 million.
5129
5130 @node The NSE Client-Service Protocol
5131 @subsection The NSE Client-Service Protocol
5132
5133 @c %**end of header
5134
5135 As with the API, the client-service protocol is very simple, only has 2
5136 different messages, defined in @code{src/nse/nse.h}:
5137
5138 @itemize @bullet
5139 @item @code{GNUNET_MESSAGE_TYPE_NSE_START}@ This message has no parameters
5140 and is sent from the client to the service upon connection.
5141 @item @code{GNUNET_MESSAGE_TYPE_NSE_ESTIMATE}@ This message is sent from
5142 the service to the client for every new estimate and upon connection.
5143 Contains a timestamp for the estimate, the average and the standard
5144 deviation for the respective round.
5145 @end itemize
5146
5147 When the @code{GNUNET_NSE_disconnect} API call is executed, the client
5148 simply disconnects from the service, with no message involved.
5149
5150 @cindex NSE Peer-to-Peer Protocol
5151 @node The NSE Peer-to-Peer Protocol
5152 @subsection The NSE Peer-to-Peer Protocol
5153
5154 @c %**end of header
5155
5156 The NSE subsystem only has one message in the P2P protocol, the
5157 @code{GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD} message.
5158
5159 This message key contents are the timestamp to identify the round
5160 (differences in system clocks may cause some peers to send messages way
5161 too early or way too late, so the timestamp allows other peers to
5162 identify such messages easily), the
5163 @uref{http://en.wikipedia.org/wiki/Proof-of-work_system, proof of work}
5164 used to make it difficult to mount a
5165 @uref{http://en.wikipedia.org/wiki/Sybil_attack, Sybil attack}, and the
5166 public key, which is used to verify the signature on the message.
5167
5168 Every peer stores a message for the previous, current and next round. The
5169 messages for the previous and current round are given to peers that
5170 connect to us. The message for the next round is simply stored until our
5171 system clock advances to the next round. The message for the current round
5172 is what we are flooding the network with right now.
5173 At the beginning of each round the peer does the following:
5174
5175 @itemize @bullet
5176 @item calculates his own distance to the target value
5177 @item creates, signs and stores the message for the current round (unless
5178 it has a better message in the "next round" slot which came early in the
5179 previous round)
5180 @item calculates, based on the stored round message (own or received) when
5181 to stard flooding it to its neighbors
5182 @end itemize
5183
5184 Upon receiving a message the peer checks the validity of the message
5185 (round, proof of work, signature). The next action depends on the
5186 contents of the incoming message:
5187
5188 @itemize @bullet
5189 @item if the message is worse than the current stored message, the peer
5190 sends the current message back immediately, to stop the other peer from
5191 spreading suboptimal results
5192 @item if the message is better than the current stored message, the peer
5193 stores the new message and calculates the new target time to start
5194 spreading it to its neighbors (excluding the one the message came from)
5195 @item if the message is for the previous round, it is compared to the
5196 message stored in the "previous round slot", which may then be updated
5197 @item if the message is for the next round, it is compared to the message
5198 stored in the "next round slot", which again may then be updated
5199 @end itemize
5200
5201 Finally, when it comes to send the stored message for the current round to
5202 the neighbors there is a random delay added for each neighbor, to avoid
5203 traffic spikes and minimize cross-messages.
5204
5205 @cindex HOSTLIST Subsystem
5206 @node HOSTLIST Subsystem
5207 @section HOSTLIST Subsystem
5208
5209 @c %**end of header
5210
5211 Peers in the GNUnet overlay network need address information so that they
5212 can connect with other peers. GNUnet uses so called HELLO messages to
5213 store and exchange peer addresses.
5214 GNUnet provides several methods for peers to obtain this information:
5215
5216 @itemize @bullet
5217 @item out-of-band exchange of HELLO messages (manually, using for example
5218 gnunet-peerinfo)
5219 @item HELLO messages shipped with GNUnet (automatic with distribution)
5220 @item UDP neighbor discovery in LAN (IPv4 broadcast, IPv6 multicast)
5221 @item topology gossiping (learning from other peers we already connected
5222 to), and
5223 @item the HOSTLIST daemon covered in this section, which is particularly
5224 relevant for bootstrapping new peers.
5225 @end itemize
5226
5227 New peers have no existing connections (and thus cannot learn from gossip
5228 among peers), may not have other peers in their LAN and might be started
5229 with an outdated set of HELLO messages from the distribution.
5230 In this case, getting new peers to connect to the network requires either
5231 manual effort or the use of a HOSTLIST to obtain HELLOs.
5232
5233 @menu
5234 * HELLOs::
5235 * Overview for the HOSTLIST subsystem::
5236 * Interacting with the HOSTLIST daemon::
5237 * Hostlist security address validation::
5238 * The HOSTLIST daemon::
5239 * The HOSTLIST server::
5240 * The HOSTLIST client::
5241 * Usage::
5242 @end menu
5243
5244 @node HELLOs
5245 @subsection HELLOs
5246
5247 @c %**end of header
5248
5249 The basic information peers require to connect to other peers are
5250 contained in so called HELLO messages you can think of as a business card.
5251 Besides the identity of the peer (based on the cryptographic public key) a
5252 HELLO message may contain address information that specifies ways to
5253 contact a peer. By obtaining HELLO messages, a peer can learn how to
5254 contact other peers.
5255
5256 @node Overview for the HOSTLIST subsystem
5257 @subsection Overview for the HOSTLIST subsystem
5258
5259 @c %**end of header
5260
5261 The HOSTLIST subsystem provides a way to distribute and obtain contact
5262 information to connect to other peers using a simple HTTP GET request.
5263 It's implementation is split in three parts, the main file for the daemon
5264 itself (@file{gnunet-daemon-hostlist.c}), the HTTP client used to download
5265 peer information (@file{hostlist-client.c}) and the server component used
5266 to provide this information to other peers (@file{hostlist-server.c}).
5267 The server is basically a small HTTP web server (based on GNU
5268 libmicrohttpd) which provides a list of HELLOs known to the local peer for
5269 download. The client component is basically a HTTP client
5270 (based on libcurl) which can download hostlists from one or more websites.
5271 The hostlist format is a binary blob containing a sequence of HELLO
5272 messages. Note that any HTTP server can theoretically serve a hostlist,
5273 the build-in hostlist server makes it simply convenient to offer this
5274 service.
5275
5276
5277 @menu
5278 * Features::
5279 * HOSTLIST - Limitations::
5280 @end menu
5281
5282 @node Features
5283 @subsubsection Features
5284
5285 @c %**end of header
5286
5287 The HOSTLIST daemon can:
5288
5289 @itemize @bullet
5290 @item provide HELLO messages with validated addresses obtained from
5291 PEERINFO to download for other peers
5292 @item download HELLO messages and forward these message to the TRANSPORT
5293 subsystem for validation
5294 @item advertises the URL of this peer's hostlist address to other peers
5295 via gossip
5296 @item automatically learn about hostlist servers from the gossip of other
5297 peers
5298 @end itemize
5299
5300 @node HOSTLIST - Limitations
5301 @subsubsection HOSTLIST - Limitations
5302
5303 @c %**end of header
5304
5305 The HOSTLIST daemon does not:
5306
5307 @itemize @bullet
5308 @item verify the cryptographic information in the HELLO messages
5309 @item verify the address information in the HELLO messages
5310 @end itemize
5311
5312 @node Interacting with the HOSTLIST daemon
5313 @subsection Interacting with the HOSTLIST daemon
5314
5315 @c %**end of header
5316
5317 The HOSTLIST subsystem is currently implemented as a daemon, so there is
5318 no need for the user to interact with it and therefore there is no
5319 command line tool and no API to communicate with the daemon. In the
5320 future, we can envision changing this to allow users to manually trigger
5321 the download of a hostlist.
5322
5323 Since there is no command line interface to interact with HOSTLIST, the
5324 only way to interact with the hostlist is to use STATISTICS to obtain or
5325 modify information about the status of HOSTLIST:
5326
5327 @example
5328 $ gnunet-statistics -s hostlist
5329 @end example
5330
5331 @noindent
5332 In particular, HOSTLIST includes a @strong{persistent} value in statistics
5333 that specifies when the hostlist server might be queried next. As this
5334 value is exponentially increasing during runtime, developers may want to
5335 reset or manually adjust it. Note that HOSTLIST (but not STATISTICS) needs
5336 to be shutdown if changes to this value are to have any effect on the
5337 daemon (as HOSTLIST does not monitor STATISTICS for changes to the
5338 download frequency).
5339
5340 @node Hostlist security address validation
5341 @subsection Hostlist security address validation
5342
5343 @c %**end of header
5344
5345 Since information obtained from other parties cannot be trusted without
5346 validation, we have to distinguish between @emph{validated} and
5347 @emph{not validated} addresses. Before using (and so trusting)
5348 information from other parties, this information has to be double-checked
5349 (validated). Address validation is not done by HOSTLIST but by the
5350 TRANSPORT service.
5351
5352 The HOSTLIST component is functionally located between the PEERINFO and
5353 the TRANSPORT subsystem. When acting as a server, the daemon obtains valid
5354 (@emph{validated}) peer information (HELLO messages) from the PEERINFO
5355 service and provides it to other peers. When acting as a client, it
5356 contacts the HOSTLIST servers specified in the configuration, downloads
5357 the (unvalidated) list of HELLO messages and forwards these information
5358 to the TRANSPORT server to validate the addresses.
5359
5360 @cindex HOSTLIST daemon
5361 @node The HOSTLIST daemon
5362 @subsection The HOSTLIST daemon
5363
5364 @c %**end of header
5365
5366 The hostlist daemon is the main component of the HOSTLIST subsystem. It is
5367 started by the ARM service and (if configured) starts the HOSTLIST client
5368 and server components.
5369
5370 If the daemon provides a hostlist itself it can advertise it's own
5371 hostlist to other peers. To do so it sends a
5372 @code{GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT} message to other peers
5373 when they connect to this peer on the CORE level. This hostlist
5374 advertisement message contains the URL to access the HOSTLIST HTTP
5375 server of the sender. The daemon may also subscribe to this type of
5376 message from CORE service, and then forward these kind of message to the
5377 HOSTLIST client. The client then uses all available URLs to download peer
5378 information when necessary.
5379
5380 When starting, the HOSTLIST daemon first connects to the CORE subsystem
5381 and if hostlist learning is enabled, registers a CORE handler to receive
5382 this kind of messages. Next it starts (if configured) the client and
5383 server. It passes pointers to CORE connect and disconnect and receive
5384 handlers where the client and server store their functions, so the daemon
5385 can notify them about CORE events.
5386
5387 To clean up on shutdown, the daemon has a cleaning task, shutting down all
5388 subsystems and disconnecting from CORE.
5389
5390 @cindex HOSTLIST server
5391 @node The HOSTLIST server
5392 @subsection The HOSTLIST server
5393
5394 @c %**end of header
5395
5396 The server provides a way for other peers to obtain HELLOs. Basically it
5397 is a small web server other peers can connect to and download a list of
5398 HELLOs using standard HTTP; it may also advertise the URL of the hostlist
5399 to other peers connecting on CORE level.
5400
5401
5402 @menu
5403 * The HTTP Server::
5404 * Advertising the URL::
5405 @end menu
5406
5407 @node The HTTP Server
5408 @subsubsection The HTTP Server
5409
5410 @c %**end of header
5411
5412 During startup, the server starts a web server listening on the port
5413 specified with the HTTPPORT value (default 8080). In addition it connects
5414 to the PEERINFO service to obtain peer information. The HOSTLIST server
5415 uses the GNUNET_PEERINFO_iterate function to request HELLO information for
5416 all peers and adds their information to a new hostlist if they are
5417 suitable (expired addresses and HELLOs without addresses are both not
5418 suitable) and the maximum size for a hostlist is not exceeded
5419 (MAX_BYTES_PER_HOSTLISTS = 500000).
5420 When PEERINFO finishes (with a last NULL callback), the server destroys
5421 the previous hostlist response available for download on the web server
5422 and replaces it with the updated hostlist. The hostlist format is
5423 basically a sequence of HELLO messages (as obtained from PEERINFO) without
5424 any special tokenization. Since each HELLO message contains a size field,
5425 the response can easily be split into separate HELLO messages by the
5426 client.
5427
5428 A HOSTLIST client connecting to the HOSTLIST server will receive the
5429 hostlist as a HTTP response and the the server will terminate the
5430 connection with the result code @code{HTTP 200 OK}.
5431 The connection will be closed immediately if no hostlist is available.
5432
5433 @node Advertising the URL
5434 @subsubsection Advertising the URL
5435
5436 @c %**end of header
5437
5438 The server also advertises the URL to download the hostlist to other peers
5439 if hostlist advertisement is enabled.
5440 When a new peer connects and has hostlist learning enabled, the server
5441 sends a @code{GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT} message to this
5442 peer using the CORE service.
5443
5444 @cindex HOSTLIST client
5445 @node The HOSTLIST client
5446 @subsection The HOSTLIST client
5447
5448 @c %**end of header
5449
5450 The client provides the functionality to download the list of HELLOs from
5451 a set of URLs.
5452 It performs a standard HTTP request to the URLs configured and learned
5453 from advertisement messages received from other peers. When a HELLO is
5454 downloaded, the HOSTLIST client forwards the HELLO to the TRANSPORT
5455 service for validation.
5456
5457 The client supports two modes of operation:
5458
5459 @itemize @bullet
5460 @item download of HELLOs (bootstrapping)
5461 @item learning of URLs
5462 @end itemize
5463
5464 @menu
5465 * Bootstrapping::
5466 * Learning::
5467 @end menu
5468
5469 @node Bootstrapping
5470 @subsubsection Bootstrapping
5471
5472 @c %**end of header
5473
5474 For bootstrapping, it schedules a task to download the hostlist from the
5475 set of known URLs.
5476 The downloads are only performed if the number of current
5477 connections is smaller than a minimum number of connections
5478 (at the moment 4).
5479 The interval between downloads increases exponentially; however, the
5480 exponential growth is limited if it becomes longer than an hour.
5481 At that point, the frequency growth is capped at
5482 (#number of connections * 1h).
5483
5484 Once the decision has been taken to download HELLOs, the daemon chooses a
5485 random URL from the list of known URLs. URLs can be configured in the
5486 configuration or be learned from advertisement messages.
5487 The client uses a HTTP client library (libcurl) to initiate the download
5488 using the libcurl multi interface.
5489 Libcurl passes the data to the callback_download function which
5490 stores the data in a buffer if space is available and the maximum size for
5491 a hostlist download is not exceeded (MAX_BYTES_PER_HOSTLISTS = 500000).
5492 When a full HELLO was downloaded, the HOSTLIST client offers this
5493 HELLO message to the TRANSPORT service for validation.
5494 When the download is finished or failed, statistical information about the
5495 quality of this URL is updated.
5496
5497 @cindex HOSTLIST learning
5498 @node Learning
5499 @subsubsection Learning
5500
5501 @c %**end of header
5502
5503 The client also manages hostlist advertisements from other peers. The
5504 HOSTLIST daemon forwards @code{GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT}
5505 messages to the client subsystem, which extracts the URL from the message.
5506 Next, a test of the newly obtained URL is performed by triggering a
5507 download from the new URL. If the URL works correctly, it is added to the
5508 list of working URLs.
5509
5510 The size of the list of URLs is restricted, so if an additional server is
5511 added and the list is full, the URL with the worst quality ranking
5512 (determined through successful downloads and number of HELLOs e.g.) is
5513 discarded. During shutdown the list of URLs is saved to a file for
5514 persistance and loaded on startup. URLs from the configuration file are
5515 never discarded.
5516
5517 @node Usage
5518 @subsection Usage
5519
5520 @c %**end of header
5521
5522 To start HOSTLIST by default, it has to be added to the DEFAULTSERVICES
5523 section for the ARM services. This is done in the default configuration.
5524
5525 For more information on how to configure the HOSTLIST subsystem see the
5526 installation handbook:@
5527 Configuring the hostlist to bootstrap@
5528 Configuring your peer to provide a hostlist
5529
5530 @cindex IDENTITY Subsystem
5531 @node IDENTITY Subsystem
5532 @section IDENTITY Subsystem
5533
5534 @c %**end of header
5535
5536 Identities of "users" in GNUnet are called egos.
5537 Egos can be used as pseudonyms ("fake names") or be tied to an
5538 organization (for example, "GNU") or even the actual identity of a human.
5539 GNUnet users are expected to have many egos. They might have one tied to
5540 their real identity, some for organizations they manage, and more for
5541 different domains where they want to operate under a pseudonym.
5542
5543 The IDENTITY service allows users to manage their egos. The identity
5544 service manages the private keys egos of the local user; it does not
5545 manage identities of other users (public keys). Public keys for other
5546 users need names to become manageable. GNUnet uses the
5547 @dfn{GNU Name System} (GNS) to give names to other users and manage their
5548 public keys securely. This chapter is about the IDENTITY service,
5549 which is about the management of private keys.
5550
5551 On the network, an ego corresponds to an ECDSA key (over Curve25519,
5552 using RFC 6979, as required by GNS). Thus, users can perform actions
5553 under a particular ego by using (signing with) a particular private key.
5554 Other users can then confirm that the action was really performed by that
5555 ego by checking the signature against the respective public key.
5556
5557 The IDENTITY service allows users to associate a human-readable name with
5558 each ego. This way, users can use names that will remind them of the
5559 purpose of a particular ego.
5560 The IDENTITY service will store the respective private keys and
5561 allows applications to access key information by name.
5562 Users can change the name that is locally (!) associated with an ego.
5563 Egos can also be deleted, which means that the private key will be removed
5564 and it thus will not be possible to perform actions with that ego in the
5565 future.
5566
5567 Additionally, the IDENTITY subsystem can associate service functions with
5568 egos.
5569 For example, GNS requires the ego that should be used for the shorten
5570 zone. GNS will ask IDENTITY for an ego for the "gns-short" service.
5571 The IDENTITY service has a mapping of such service strings to the name of
5572 the ego that the user wants to use for this service, for example
5573 "my-short-zone-ego".
5574
5575 Finally, the IDENTITY API provides access to a special ego, the
5576 anonymous ego. The anonymous ego is special in that its private key is not
5577 really private, but fixed and known to everyone.
5578 Thus, anyone can perform actions as anonymous. This can be useful as with
5579 this trick, code does not have to contain a special case to distinguish
5580 between anonymous and pseudonymous egos.
5581
5582 @menu
5583 * libgnunetidentity::
5584 * The IDENTITY Client-Service Protocol::
5585 @end menu
5586
5587 @cindex libgnunetidentity
5588 @node libgnunetidentity
5589 @subsection libgnunetidentity
5590 @c %**end of header
5591
5592
5593 @menu
5594 * Connecting to the service::
5595 * Operations on Egos::
5596 * The anonymous Ego::
5597 * Convenience API to lookup a single ego::
5598 * Associating egos with service functions::
5599 @end menu
5600
5601 @node Connecting to the service
5602 @subsubsection Connecting to the service
5603
5604 @c %**end of header
5605
5606 First, typical clients connect to the identity service using
5607 @code{GNUNET_IDENTITY_connect}. This function takes a callback as a
5608 parameter.
5609 If the given callback parameter is non-null, it will be invoked to notify
5610 the application about the current state of the identities in the system.
5611
5612 @itemize @bullet
5613 @item First, it will be invoked on all known egos at the time of the
5614 connection. For each ego, a handle to the ego and the user's name for the
5615 ego will be passed to the callback. Furthermore, a @code{void **} context
5616 argument will be provided which gives the client the opportunity to
5617 associate some state with the ego.
5618 @item Second, the callback will be invoked with NULL for the ego, the name
5619 and the context. This signals that the (initial) iteration over all egos
5620 has completed.
5621 @item Then, the callback will be invoked whenever something changes about
5622 an ego.
5623 If an ego is renamed, the callback is invoked with the ego handle of the
5624 ego that was renamed, and the new name. If an ego is deleted, the callback
5625 is invoked with the ego handle and a name of NULL. In the deletion case,
5626 the application should also release resources stored in the context.
5627 @item When the application destroys the connection to the identity service
5628 using @code{GNUNET_IDENTITY_disconnect}, the callback is again invoked
5629 with the ego and a name of NULL (equivalent to deletion of the egos).
5630 This should again be used to clean up the per-ego context.
5631 @end itemize
5632
5633 The ego handle passed to the callback remains valid until the callback is
5634 invoked with a name of NULL, so it is safe to store a reference to the
5635 ego's handle.
5636
5637 @node Operations on Egos
5638 @subsubsection Operations on Egos
5639
5640 @c %**end of header
5641
5642 Given an ego handle, the main operations are to get its associated private
5643 key using @code{GNUNET_IDENTITY_ego_get_private_key} or its associated
5644 public key using @code{GNUNET_IDENTITY_ego_get_public_key}.
5645
5646 The other operations on egos are pretty straightforward.
5647 Using @code{GNUNET_IDENTITY_create}, an application can request the
5648 creation of an ego by specifying the desired name.
5649 The operation will fail if that name is
5650 already in use. Using @code{GNUNET_IDENTITY_rename} the name of an
5651 existing ego can be changed. Finally, egos can be deleted using
5652 @code{GNUNET_IDENTITY_delete}. All of these operations will trigger
5653 updates to the callback given to the @code{GNUNET_IDENTITY_connect}
5654 function of all applications that are connected with the identity service
5655 at the time. @code{GNUNET_IDENTITY_cancel} can be used to cancel the
5656 operations before the respective continuations would be called.
5657 It is not guaranteed that the operation will not be completed anyway,
5658 only the continuation will no longer be called.
5659
5660 @node The anonymous Ego
5661 @subsubsection The anonymous Ego
5662
5663 @c %**end of header
5664
5665 A special way to obtain an ego handle is to call
5666 @code{GNUNET_IDENTITY_ego_get_anonymous}, which returns an ego for the
5667 "anonymous" user --- anyone knows and can get the private key for this
5668 user, so it is suitable for operations that are supposed to be anonymous
5669 but require signatures (for example, to avoid a special path in the code).
5670 The anonymous ego is always valid and accessing it does not require a
5671 connection to the identity service.
5672
5673 @node Convenience API to lookup a single ego
5674 @subsubsection Convenience API to lookup a single ego
5675
5676
5677 As applications commonly simply have to lookup a single ego, there is a
5678 convenience API to do just that. Use @code{GNUNET_IDENTITY_ego_lookup} to
5679 lookup a single ego by name. Note that this is the user's name for the
5680 ego, not the service function. The resulting ego will be returned via a
5681 callback and will only be valid during that callback. The operation can
5682 be cancelled via @code{GNUNET_IDENTITY_ego_lookup_cancel}
5683 (cancellation is only legal before the callback is invoked).
5684
5685 @node Associating egos with service functions
5686 @subsubsection Associating egos with service functions
5687
5688
5689 The @code{GNUNET_IDENTITY_set} function is used to associate a particular
5690 ego with a service function. The name used by the service and the ego are
5691 given as arguments.
5692 Afterwards, the service can use its name to lookup the associated ego
5693 using @code{GNUNET_IDENTITY_get}.
5694
5695 @node The IDENTITY Client-Service Protocol
5696 @subsection The IDENTITY Client-Service Protocol
5697
5698 @c %**end of header
5699
5700 A client connecting to the identity service first sends a message with
5701 type
5702 @code{GNUNET_MESSAGE_TYPE_IDENTITY_START} to the service. After that, the
5703 client will receive information about changes to the egos by receiving
5704 messages of type @code{GNUNET_MESSAGE_TYPE_IDENTITY_UPDATE}.
5705 Those messages contain the private key of the ego and the user's name of
5706 the ego (or zero bytes for the name to indicate that the ego was deleted).
5707 A special bit @code{end_of_list} is used to indicate the end of the
5708 initial iteration over the identity service's egos.
5709
5710 The client can trigger changes to the egos by sending @code{CREATE},
5711 @code{RENAME} or @code{DELETE} messages.
5712 The CREATE message contains the private key and the desired name.@
5713 The RENAME message contains the old name and the new name.@
5714 The DELETE message only needs to include the name of the ego to delete.@
5715 The service responds to each of these messages with a @code{RESULT_CODE}
5716 message which indicates success or error of the operation, and possibly
5717 a human-readable error message.
5718
5719 Finally, the client can bind the name of a service function to an ego by
5720 sending a @code{SET_DEFAULT} message with the name of the service function
5721 and the private key of the ego.
5722 Such bindings can then be resolved using a @code{GET_DEFAULT} message,
5723 which includes the name of the service function. The identity service
5724 will respond to a GET_DEFAULT request with a SET_DEFAULT message
5725 containing the respective information, or with a RESULT_CODE to
5726 indicate an error.
5727
5728 @cindex NAMESTORE Subsystem
5729 @node NAMESTORE Subsystem
5730 @section NAMESTORE Subsystem
5731
5732 The NAMESTORE subsystem provides persistent storage for local GNS zone
5733 information. All local GNS zone information are managed by NAMESTORE. It
5734 provides both the functionality to administer local GNS information (e.g.
5735 delete and add records) as well as to retrieve GNS information (e.g to
5736 list name information in a client).
5737 NAMESTORE does only manage the persistent storage of zone information
5738 belonging to the user running the service: GNS information from other
5739 users obtained from the DHT are stored by the NAMECACHE subsystem.
5740
5741 NAMESTORE uses a plugin-based database backend to store GNS information
5742 with good performance. Here sqlite, MySQL and PostgreSQL are supported
5743 database backends.
5744 NAMESTORE clients interact with the IDENTITY subsystem to obtain
5745 cryptographic information about zones based on egos as described with the
5746 IDENTITY subsystem, but internally NAMESTORE refers to zones using the
5747 ECDSA private key.
5748 In addition, it collaborates with the NAMECACHE subsystem and
5749 stores zone information when local information are modified in the
5750 GNS cache to increase look-up performance for local information.
5751
5752 NAMESTORE provides functionality to look-up and store records, to iterate
5753 over a specific or all zones and to monitor zones for changes. NAMESTORE
5754 functionality can be accessed using the NAMESTORE api or the NAMESTORE
5755 command line tool.
5756
5757 @menu
5758 * libgnunetnamestore::
5759 @end menu
5760
5761 @cindex libgnunetnamestore
5762 @node libgnunetnamestore
5763 @subsection libgnunetnamestore
5764
5765 To interact with NAMESTORE clients first connect to the NAMESTORE service
5766 using the @code{GNUNET_NAMESTORE_connect} passing a configuration handle.
5767 As a result they obtain a NAMESTORE handle, they can use for operations,
5768 or NULL is returned if the connection failed.
5769
5770 To disconnect from NAMESTORE, clients use
5771 @code{GNUNET_NAMESTORE_disconnect} and specify the handle to disconnect.
5772
5773 NAMESTORE internally uses the ECDSA private key to refer to zones. These
5774 private keys can be obtained from the IDENTITY subsytem.
5775 Here @emph{egos} @emph{can be used to refer to zones or the default ego
5776 assigned to the GNS subsystem can be used to obtained the master zone's
5777 private key.}
5778
5779
5780 @menu
5781 * Editing Zone Information::
5782 * Iterating Zone Information::
5783 * Monitoring Zone Information::
5784 @end menu
5785
5786 @node Editing Zone Information
5787 @subsubsection Editing Zone Information
5788
5789 @c %**end of header
5790
5791 NAMESTORE provides functions to lookup records stored under a label in a
5792 zone and to store records under a label in a zone.
5793
5794 To store (and delete) records, the client uses the
5795 @code{GNUNET_NAMESTORE_records_store} function and has to provide
5796 namestore handle to use, the private key of the zone, the label to store
5797 the records under, the records and number of records plus an callback
5798 function.
5799 After the operation is performed NAMESTORE will call the provided
5800 callback function with the result GNUNET_SYSERR on failure
5801 (including timeout/queue drop/failure to validate), GNUNET_NO if content
5802 was already there or not found GNUNET_YES (or other positive value) on
5803 success plus an additional error message.
5804
5805 Records are deleted by using the store command with 0 records to store.
5806 It is important to note, that records are not merged when records exist
5807 with the label.
5808 So a client has first to retrieve records, merge with existing records
5809 and then store the result.
5810
5811 To perform a lookup operation, the client uses the
5812 @code{GNUNET_NAMESTORE_records_store} function. Here he has to pass the
5813 namestore handle, the private key of the zone and the label. He also has
5814 to provide a callback function which will be called with the result of
5815 the lookup operation:
5816 the zone for the records, the label, and the records including the
5817 number of records included.
5818
5819 A special operation is used to set the preferred nickname for a zone.
5820 This nickname is stored with the zone and is automatically merged with
5821 all labels and records stored in a zone. Here the client uses the
5822 @code{GNUNET_NAMESTORE_set_nick} function and passes the private key of
5823 the zone, the nickname as string plus a the callback with the result of
5824 the operation.
5825
5826 @node Iterating Zone Information
5827 @subsubsection Iterating Zone Information
5828
5829 @c %**end of header
5830
5831 A client can iterate over all information in a zone or all zones managed
5832 by NAMESTORE.
5833 Here a client uses the @code{GNUNET_NAMESTORE_zone_iteration_start}
5834 function and passes the namestore handle, the zone to iterate over and a
5835 callback function to call with the result.
5836 If the client wants to iterate over all the, he passes NULL for the zone.
5837 A @code{GNUNET_NAMESTORE_ZoneIterator} handle is returned to be used to
5838 continue iteration.
5839
5840 NAMESTORE calls the callback for every result and expects the client to
5841 call @code{GNUNET_NAMESTORE_zone_iterator_next} to continue to iterate or
5842 @code{GNUNET_NAMESTORE_zone_iterator_stop} to interrupt the iteration.
5843 When NAMESTORE reached the last item it will call the callback with a
5844 NULL value to indicate.
5845
5846 @node Monitoring Zone Information
5847 @subsubsection Monitoring Zone Information
5848
5849 @c %**end of header
5850
5851 Clients can also monitor zones to be notified about changes. Here the
5852 clients uses the @code{GNUNET_NAMESTORE_zone_monitor_start} function and
5853 passes the private key of the zone and and a callback function to call
5854 with updates for a zone.
5855 The client can specify to obtain zone information first by iterating over
5856 the zone and specify a synchronization callback to be called when the
5857 client and the namestore are synced.
5858
5859 On an update, NAMESTORE will call the callback with the private key of the
5860 zone, the label and the records and their number.
5861
5862 To stop monitoring, the client calls
5863 @code{GNUNET_NAMESTORE_zone_monitor_stop} and passes the handle obtained
5864 from the function to start the monitoring.
5865
5866 @cindex PEERINFO Subsystem
5867 @node PEERINFO Subsystem
5868 @section PEERINFO Subsystem
5869
5870 @c %**end of header
5871
5872 The PEERINFO subsystem is used to store verified (validated) information
5873 about known peers in a persistent way. It obtains these addresses for
5874 example from TRANSPORT service which is in charge of address validation.
5875 Validation means that the information in the HELLO message are checked by
5876 connecting to the addresses and performing a cryptographic handshake to
5877 authenticate the peer instance stating to be reachable with these
5878 addresses.
5879 Peerinfo does not validate the HELLO messages itself but only stores them
5880 and gives them to interested clients.
5881
5882 As future work, we think about moving from storing just HELLO messages to
5883 providing a generic persistent per-peer information store.
5884 More and more subsystems tend to need to store per-peer information in
5885 persistent way.
5886 To not duplicate this functionality we plan to provide a PEERSTORE
5887 service providing this functionality.
5888
5889 @menu
5890 * PEERINFO - Features::
5891 * PEERINFO - Limitations::
5892 * DeveloperPeer Information::
5893 * Startup::
5894 * Managing Information::
5895 * Obtaining Information::
5896 * The PEERINFO Client-Service Protocol::
5897 * libgnunetpeerinfo::
5898 @end menu
5899
5900 @node PEERINFO - Features
5901 @subsection PEERINFO - Features
5902
5903 @c %**end of header
5904
5905 @itemize @bullet
5906 @item Persistent storage
5907 @item Client notification mechanism on update
5908 @item Periodic clean up for expired information
5909 @item Differentiation between public and friend-only HELLO
5910 @end itemize
5911
5912 @node PEERINFO - Limitations
5913 @subsection PEERINFO - Limitations
5914
5915
5916 @itemize @bullet
5917 @item Does not perform HELLO validation
5918 @end itemize
5919
5920 @node DeveloperPeer Information
5921 @subsection DeveloperPeer Information
5922
5923 @c %**end of header
5924
5925 The PEERINFO subsystem stores these information in the form of HELLO
5926 messages you can think of as business cards.
5927 These HELLO messages contain the public key of a peer and the addresses
5928 a peer can be reached under.
5929 The addresses include an expiration date describing how long they are
5930 valid. This information is updated regularly by the TRANSPORT service by
5931 revalidating the address.
5932 If an address is expired and not renewed, it can be removed from the
5933 HELLO message.
5934
5935 Some peer do not want to have their HELLO messages distributed to other
5936 peers, especially when GNUnet's friend-to-friend modus is enabled.
5937 To prevent this undesired distribution. PEERINFO distinguishes between
5938 @emph{public} and @emph{friend-only} HELLO messages.
5939 Public HELLO messages can be freely distributed to other (possibly
5940 unknown) peers (for example using the hostlist, gossiping, broadcasting),
5941 whereas friend-only HELLO messages may not be distributed to other peers.
5942 Friend-only HELLO messages have an additional flag @code{friend_only} set
5943 internally. For public HELLO message this flag is not set.
5944 PEERINFO does and cannot not check if a client is allowed to obtain a
5945 specific HELLO type.
5946
5947 The HELLO messages can be managed using the GNUnet HELLO library.
5948 Other GNUnet systems can obtain these information from PEERINFO and use
5949 it for their purposes.
5950 Clients are for example the HOSTLIST component providing these
5951 information to other peers in form of a hostlist or the TRANSPORT
5952 subsystem using these information to maintain connections to other peers.
5953
5954 @node Startup
5955 @subsection Startup
5956
5957 @c %**end of header
5958
5959 During startup the PEERINFO services loads persistent HELLOs from disk.
5960 First PEERINFO parses the directory configured in the HOSTS value of the
5961 @code{PEERINFO} configuration section to store PEERINFO information.
5962 For all files found in this directory valid HELLO messages are extracted.
5963 In addition it loads HELLO messages shipped with the GNUnet distribution.
5964 These HELLOs are used to simplify network bootstrapping by providing
5965 valid peer information with the distribution.
5966 The use of these HELLOs can be prevented by setting the
5967 @code{USE_INCLUDED_HELLOS} in the @code{PEERINFO} configuration section to
5968 @code{NO}. Files containing invalid information are removed.
5969
5970 @node Managing Information
5971 @subsection Managing Information
5972
5973 @c %**end of header
5974
5975 The PEERINFO services stores information about known PEERS and a single
5976 HELLO message for every peer.
5977 A peer does not need to have a HELLO if no information are available.
5978 HELLO information from different sources, for example a HELLO obtained
5979 from a remote HOSTLIST and a second HELLO stored on disk, are combined
5980 and merged into one single HELLO message per peer which will be given to
5981 clients. During this merge process the HELLO is immediately written to
5982 disk to ensure persistence.
5983
5984 PEERINFO in addition periodically scans the directory where information
5985 are stored for empty HELLO messages with expired TRANSPORT addresses.
5986 This periodic task scans all files in the directory and recreates the
5987 HELLO messages it finds.
5988 Expired TRANSPORT addresses are removed from the HELLO and if the
5989 HELLO does not contain any valid addresses, it is discarded and removed
5990 from the disk.
5991
5992 @node Obtaining Information
5993 @subsection Obtaining Information
5994
5995 @c %**end of header
5996
5997 When a client requests information from PEERINFO, PEERINFO performs a
5998 lookup for the respective peer or all peers if desired and transmits this
5999 information to the client.
6000 The client can specify if friend-only HELLOs have to be included or not
6001 and PEERINFO filters the respective HELLO messages before transmitting
6002 information.
6003
6004 To notify clients about changes to PEERINFO information, PEERINFO
6005 maintains a list of clients interested in this notifications.
6006 Such a notification occurs if a HELLO for a peer was updated (due to a
6007 merge for example) or a new peer was added.
6008
6009 @node The PEERINFO Client-Service Protocol
6010 @subsection The PEERINFO Client-Service Protocol
6011
6012 @c %**end of header
6013
6014 To connect and disconnect to and from the PEERINFO Service PEERINFO
6015 utilizes the util client/server infrastructure, so no special messages
6016 types are used here.
6017
6018 To add information for a peer, the plain HELLO message is transmitted to
6019 the service without any wrapping. All pieces of information required are
6020 stored within the HELLO message.
6021 The PEERINFO service provides a message handler accepting and processing
6022 these HELLO messages.
6023
6024 When obtaining PEERINFO information using the iterate functionality
6025 specific messages are used. To obtain information for all peers, a
6026 @code{struct ListAllPeersMessage} with message type
6027 @code{GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL} and a flag
6028 include_friend_only to indicate if friend-only HELLO messages should be
6029 included are transmitted. If information for a specific peer is required
6030 a @code{struct ListAllPeersMessage} with
6031 @code{GNUNET_MESSAGE_TYPE_PEERINFO_GET} containing the peer identity is
6032 used.
6033
6034 For both variants the PEERINFO service replies for each HELLO message it
6035 wants to transmit with a @code{struct ListAllPeersMessage} with type
6036 @code{GNUNET_MESSAGE_TYPE_PEERINFO_INFO} containing the plain HELLO.
6037 The final message is @code{struct GNUNET_MessageHeader} with type
6038 @code{GNUNET_MESSAGE_TYPE_PEERINFO_INFO}. If the client receives this
6039 message, it can proceed with the next request if any is pending.
6040
6041 @node libgnunetpeerinfo
6042 @subsection libgnunetpeerinfo
6043
6044 @c %**end of header
6045
6046 The PEERINFO API consists mainly of three different functionalities:
6047
6048 @itemize @bullet
6049 @item maintaining a connection to the service
6050 @item adding new information to the PEERINFO service
6051 @item retrieving information from the PEERINFO service
6052 @end itemize
6053
6054 @menu
6055 * Connecting to the PEERINFO Service::
6056 * Adding Information to the PEERINFO Service::
6057 * Obtaining Information from the PEERINFO Service::
6058 @end menu
6059
6060 @node Connecting to the PEERINFO Service
6061 @subsubsection Connecting to the PEERINFO Service
6062
6063 @c %**end of header
6064
6065 To connect to the PEERINFO service the function
6066 @code{GNUNET_PEERINFO_connect} is used, taking a configuration handle as
6067 an argument, and to disconnect from PEERINFO the function
6068 @code{GNUNET_PEERINFO_disconnect}, taking the PEERINFO
6069 handle returned from the connect function has to be called.
6070
6071 @node Adding Information to the PEERINFO Service
6072 @subsubsection Adding Information to the PEERINFO Service
6073
6074 @c %**end of header
6075
6076 @code{GNUNET_PEERINFO_add_peer} adds a new peer to the PEERINFO subsystem
6077 storage. This function takes the PEERINFO handle as an argument, the HELLO
6078 message to store and a continuation with a closure to be called with the
6079 result of the operation.
6080 The @code{GNUNET_PEERINFO_add_peer} returns a handle to this operation
6081 allowing to cancel the operation with the respective cancel function
6082 @code{GNUNET_PEERINFO_add_peer_cancel}. To retrieve information from
6083 PEERINFO you can iterate over all information stored with PEERINFO or you
6084 can tell PEERINFO to notify if new peer information are available.
6085
6086 @node Obtaining Information from the PEERINFO Service
6087 @subsubsection Obtaining Information from the PEERINFO Service
6088
6089 @c %**end of header
6090
6091 To iterate over information in PEERINFO you use
6092 @code{GNUNET_PEERINFO_iterate}.
6093 This function expects the PEERINFO handle, a flag if HELLO messages
6094 intended for friend only mode should be included, a timeout how long the
6095 operation should take and a callback with a callback closure to be called
6096 for the results.
6097 If you want to obtain information for a specific peer, you can specify
6098 the peer identity, if this identity is NULL, information for all peers are
6099 returned. The function returns a handle to allow to cancel the operation
6100 using @code{GNUNET_PEERINFO_iterate_cancel}.
6101
6102 To get notified when peer information changes, you can use
6103 @code{GNUNET_PEERINFO_notify}.
6104 This function expects a configuration handle and a flag if friend-only
6105 HELLO messages should be included. The PEERINFO service will notify you
6106 about every change and the callback function will be called to notify you
6107 about changes. The function returns a handle to cancel notifications
6108 with @code{GNUNET_PEERINFO_notify_cancel}.
6109
6110 @cindex PEERSTORE Subsystem
6111 @node PEERSTORE Subsystem
6112 @section PEERSTORE Subsystem
6113
6114 @c %**end of header
6115
6116 GNUnet's PEERSTORE subsystem offers persistent per-peer storage for other
6117 GNUnet subsystems. GNUnet subsystems can use PEERSTORE to persistently
6118 store and retrieve arbitrary data.
6119 Each data record stored with PEERSTORE contains the following fields:
6120
6121 @itemize @bullet
6122 @item subsystem: Name of the subsystem responsible for the record.
6123 @item peerid: Identity of the peer this record is related to.
6124 @item key: a key string identifying the record.
6125 @item value: binary record value.
6126 @item expiry: record expiry date.
6127 @end itemize
6128
6129 @menu
6130 * Functionality::
6131 * Architecture::
6132 * libgnunetpeerstore::
6133 @end menu
6134
6135 @node Functionality
6136 @subsection Functionality
6137
6138 @c %**end of header
6139
6140 Subsystems can store any type of value under a (subsystem, peerid, key)
6141 combination. A "replace" flag set during store operations forces the
6142 PEERSTORE to replace any old values stored under the same
6143 (subsystem, peerid, key) combination with the new value.
6144 Additionally, an expiry date is set after which the record is *possibly*
6145 deleted by PEERSTORE.
6146
6147 Subsystems can iterate over all values stored under any of the following
6148 combination of fields:
6149
6150 @itemize @bullet
6151 @item (subsystem)
6152 @item (subsystem, peerid)
6153 @item (subsystem, key)
6154 @item (subsystem, peerid, key)
6155 @end itemize
6156
6157 Subsystems can also request to be notified about any new values stored
6158 under a (subsystem, peerid, key) combination by sending a "watch"
6159 request to PEERSTORE.
6160
6161 @node Architecture
6162 @subsection Architecture
6163
6164 @c %**end of header
6165
6166 PEERSTORE implements the following components:
6167
6168 @itemize @bullet
6169 @item PEERSTORE service: Handles store, iterate and watch operations.
6170 @item PEERSTORE API: API to be used by other subsystems to communicate and
6171 issue commands to the PEERSTORE service.
6172 @item PEERSTORE plugins: Handles the persistent storage. At the moment,
6173 only an "sqlite" plugin is implemented.
6174 @end itemize
6175
6176 @cindex libgnunetpeerstore
6177 @node libgnunetpeerstore
6178 @subsection libgnunetpeerstore
6179
6180 @c %**end of header
6181
6182 libgnunetpeerstore is the library containing the PEERSTORE API. Subsystems
6183 wishing to communicate with the PEERSTORE service use this API to open a
6184 connection to PEERSTORE. This is done by calling
6185 @code{GNUNET_PEERSTORE_connect} which returns a handle to the newly
6186 created connection.
6187 This handle has to be used with any further calls to the API.
6188
6189 To store a new record, the function @code{GNUNET_PEERSTORE_store} is to
6190 be used which requires the record fields and a continuation function that
6191 will be called by the API after the STORE request is sent to the
6192 PEERSTORE service.
6193 Note that calling the continuation function does not mean that the record
6194 is successfully stored, only that the STORE request has been successfully
6195 sent to the PEERSTORE service.
6196 @code{GNUNET_PEERSTORE_store_cancel} can be called to cancel the STORE
6197 request only before the continuation function has been called.
6198
6199 To iterate over stored records, the function
6200 @code{GNUNET_PEERSTORE_iterate} is
6201 to be used. @emph{peerid} and @emph{key} can be set to NULL. An iterator
6202 callback function will be called with each matching record found and a
6203 NULL record at the end to signal the end of result set.
6204 @code{GNUNET_PEERSTORE_iterate_cancel} can be used to cancel the ITERATE
6205 request before the iterator callback is called with a NULL record.
6206
6207 To be notified with new values stored under a (subsystem, peerid, key)
6208 combination, the function @code{GNUNET_PEERSTORE_watch} is to be used.
6209 This will register the watcher with the PEERSTORE service, any new
6210 records matching the given combination will trigger the callback
6211 function passed to @code{GNUNET_PEERSTORE_watch}. This continues until
6212 @code{GNUNET_PEERSTORE_watch_cancel} is called or the connection to the
6213 service is destroyed.
6214
6215 After the connection is no longer needed, the function
6216 @code{GNUNET_PEERSTORE_disconnect} can be called to disconnect from the
6217 PEERSTORE service.
6218 Any pending ITERATE or WATCH requests will be destroyed.
6219 If the @code{sync_first} flag is set to @code{GNUNET_YES}, the API will
6220 delay the disconnection until all pending STORE requests are sent to
6221 the PEERSTORE service, otherwise, the pending STORE requests will be
6222 destroyed as well.
6223
6224 @cindex SET Subsystem
6225 @node SET Subsystem
6226 @section SET Subsystem
6227
6228 @c %**end of header
6229
6230 The SET service implements efficient set operations between two peers
6231 over a mesh tunnel.
6232 Currently, set union and set intersection are the only supported
6233 operations. Elements of a set consist of an @emph{element type} and
6234 arbitrary binary @emph{data}.
6235 The size of an element's data is limited to around 62 KB.
6236
6237 @menu
6238 * Local Sets::
6239 * Set Modifications::
6240 * Set Operations::
6241 * Result Elements::
6242 * libgnunetset::
6243 * The SET Client-Service Protocol::
6244 * The SET Intersection Peer-to-Peer Protocol::
6245 * The SET Union Peer-to-Peer Protocol::
6246 @end menu
6247
6248 @node Local Sets
6249 @subsection Local Sets
6250
6251 @c %**end of header
6252
6253 Sets created by a local client can be modified and reused for multiple
6254 operations. As each set operation requires potentially expensive special
6255 auxilliary data to be computed for each element of a set, a set can only
6256 participate in one type of set operation (i.e. union or intersection).
6257 The type of a set is determined upon its creation.
6258 If a the elements of a set are needed for an operation of a different
6259 type, all of the set's element must be copied to a new set of appropriate
6260 type.
6261
6262 @node Set Modifications
6263 @subsection Set Modifications
6264
6265 @c %**end of header
6266
6267 Even when set operations are active, one can add to and remove elements
6268 from a set.
6269 However, these changes will only be visible to operations that have been
6270 created after the changes have taken place. That is, every set operation
6271 only sees a snapshot of the set from the time the operation was started.
6272 This mechanism is @emph{not} implemented by copying the whole set, but by
6273 attaching @emph{generation information} to each element and operation.
6274
6275 @node Set Operations
6276 @subsection Set Operations
6277
6278 @c %**end of header
6279
6280 Set operations can be started in two ways: Either by accepting an
6281 operation request from a remote peer, or by requesting a set operation
6282 from a remote peer.
6283 Set operations are uniquely identified by the involved @emph{peers}, an
6284 @emph{application id} and the @emph{operation type}.
6285
6286 The client is notified of incoming set operations by @emph{set listeners}.
6287 A set listener listens for incoming operations of a specific operation
6288 type and application id.
6289 Once notified of an incoming set request, the client can accept the set
6290 request (providing a local set for the operation) or reject it.
6291
6292 @node Result Elements
6293 @subsection Result Elements
6294
6295 @c %**end of header
6296
6297 The SET service has three @emph{result modes} that determine how an
6298 operation's result set is delivered to the client:
6299
6300 @itemize @bullet
6301 @item @strong{Full Result Set.} All elements of set resulting from the set
6302 operation are returned to the client.
6303 @item @strong{Added Elements.} Only elements that result from the
6304 operation and are not already in the local peer's set are returned.
6305 Note that for some operations (like set intersection) this result mode
6306 will never return any elements.
6307 This can be useful if only the remove peer is actually interested in
6308 the result of the set operation.
6309 @item @strong{Removed Elements.} Only elements that are in the local
6310 peer's initial set but not in the operation's result set are returned.
6311 Note that for some operations (like set union) this result mode will
6312 never return any elements. This can be useful if only the remove peer is
6313 actually interested in the result of the set operation.
6314 @end itemize
6315
6316 @cindex libgnunetset
6317 @node libgnunetset
6318 @subsection libgnunetset
6319
6320 @c %**end of header
6321
6322 @menu
6323 * Sets::
6324 * Listeners::
6325 * Operations::
6326 * Supplying a Set::
6327 * The Result Callback::
6328 @end menu
6329
6330 @node Sets
6331 @subsubsection Sets
6332
6333 @c %**end of header
6334
6335 New sets are created with @code{GNUNET_SET_create}. Both the local peer's
6336 configuration (as each set has its own client connection) and the
6337 operation type must be specified.
6338 The set exists until either the client calls @code{GNUNET_SET_destroy} or
6339 the client's connection to the service is disrupted.
6340 In the latter case, the client is notified by the return value of
6341 functions dealing with sets. This return value must always be checked.
6342
6343 Elements are added and removed with @code{GNUNET_SET_add_element} and
6344 @code{GNUNET_SET_remove_element}.
6345
6346 @node Listeners
6347 @subsubsection Listeners
6348
6349 @c %**end of header
6350
6351 Listeners are created with @code{GNUNET_SET_listen}. Each time time a
6352 remote peer suggests a set operation with an application id and operation
6353 type matching a listener, the listener's callback is invoked.
6354 The client then must synchronously call either @code{GNUNET_SET_accept}
6355 or @code{GNUNET_SET_reject}. Note that the operation will not be started
6356 until the client calls @code{GNUNET_SET_commit}
6357 (see Section "Supplying a Set").
6358
6359 @node Operations
6360 @subsubsection Operations
6361
6362 @c %**end of header
6363
6364 Operations to be initiated by the local peer are created with
6365 @code{GNUNET_SET_prepare}. Note that the operation will not be started
6366 until the client calls @code{GNUNET_SET_commit}
6367 (see Section "Supplying a Set").
6368
6369 @node Supplying a Set
6370 @subsubsection Supplying a Set
6371
6372 @c %**end of header
6373
6374 To create symmetry between the two ways of starting a set operation
6375 (accepting and nitiating it), the operation handles returned by
6376 @code{GNUNET_SET_accept} and @code{GNUNET_SET_prepare} do not yet have a
6377 set to operate on, thus they can not do any work yet.
6378
6379 The client must call @code{GNUNET_SET_commit} to specify a set to use for
6380 an operation. @code{GNUNET_SET_commit} may only be called once per set
6381 operation.
6382
6383 @node The Result Callback
6384 @subsubsection The Result Callback
6385
6386 @c %**end of header
6387
6388 Clients must specify both a result mode and a result callback with
6389 @code{GNUNET_SET_accept} and @code{GNUNET_SET_prepare}. The result
6390 callback with a status indicating either that an element was received, or
6391 the operation failed or succeeded.
6392 The interpretation of the received element depends on the result mode.
6393 The callback needs to know which result mode it is used in, as the
6394 arguments do not indicate if an element is part of the full result set,
6395 or if it is in the difference between the original set and the final set.
6396
6397 @node The SET Client-Service Protocol
6398 @subsection The SET Client-Service Protocol
6399
6400 @c %**end of header
6401
6402 @menu
6403 * Creating Sets::
6404 * Listeners2::
6405 * Initiating Operations::
6406 * Modifying Sets::
6407 * Results and Operation Status::
6408 * Iterating Sets::
6409 @end menu
6410
6411 @node Creating Sets
6412 @subsubsection Creating Sets
6413
6414 @c %**end of header
6415
6416 For each set of a client, there exists a client connection to the service.
6417 Sets are created by sending the @code{GNUNET_SERVICE_SET_CREATE} message
6418 over a new client connection. Multiple operations for one set are
6419 multiplexed over one client connection, using a request id supplied by
6420 the client.
6421
6422 @node Listeners2
6423 @subsubsection Listeners2
6424
6425 @c %**end of header
6426
6427 Each listener also requires a seperate client connection. By sending the
6428 @code{GNUNET_SERVICE_SET_LISTEN} message, the client notifies the service
6429 of the application id and operation type it is interested in. A client
6430 rejects an incoming request by sending @code{GNUNET_SERVICE_SET_REJECT}
6431 on the listener's client connection.
6432 In contrast, when accepting an incoming request, a
6433 @code{GNUNET_SERVICE_SET_ACCEPT} message must be sent over the@ set that
6434 is supplied for the set operation.
6435
6436 @node Initiating Operations
6437 @subsubsection Initiating Operations
6438
6439 @c %**end of header
6440
6441 Operations with remote peers are initiated by sending a
6442 @code{GNUNET_SERVICE_SET_EVALUATE} message to the service. The@ client
6443 connection that this message is sent by determines the set to use.
6444
6445 @node Modifying Sets
6446 @subsubsection Modifying Sets
6447
6448 @c %**end of header
6449
6450 Sets are modified with the @code{GNUNET_SERVICE_SET_ADD} and
6451 @code{GNUNET_SERVICE_SET_REMOVE} messages.
6452
6453
6454 @c %@menu
6455 @c %* Results and Operation Status::
6456 @c %* Iterating Sets::
6457 @c %@end menu   
6458
6459 @node Results and Operation Status
6460 @subsubsection Results and Operation Status
6461 @c %**end of header
6462
6463 The service notifies the client of result elements and success/failure of
6464 a set operation with the @code{GNUNET_SERVICE_SET_RESULT} message.
6465
6466 @node Iterating Sets
6467 @subsubsection Iterating Sets
6468
6469 @c %**end of header
6470
6471 All elements of a set can be requested by sending
6472 @code{GNUNET_SERVICE_SET_ITER_REQUEST}. The server responds with
6473 @code{GNUNET_SERVICE_SET_ITER_ELEMENT} and eventually terminates the
6474 iteration with @code{GNUNET_SERVICE_SET_ITER_DONE}.
6475 After each received element, the client
6476 must send @code{GNUNET_SERVICE_SET_ITER_ACK}. Note that only one set
6477 iteration may be active for a set at any given time.
6478
6479 @node The SET Intersection Peer-to-Peer Protocol
6480 @subsection The SET Intersection Peer-to-Peer Protocol
6481
6482 @c %**end of header
6483
6484 The intersection protocol operates over CADET and starts with a
6485 GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST being sent by the peer
6486 initiating the operation to the peer listening for inbound requests.
6487 It includes the number of elements of the initiating peer, which is used
6488 to decide which side will send a Bloom filter first.
6489
6490 The listening peer checks if the operation type and application
6491 identifier are acceptable for its current state.
6492 If not, it responds with a GNUNET_MESSAGE_TYPE_SET_RESULT and a status of
6493 GNUNET_SET_STATUS_FAILURE (and terminates the CADET channel).
6494
6495 If the application accepts the request, the listener sends back a
6496 @code{GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_ELEMENT_INFO} if it has
6497 more elements in the set than the client.
6498 Otherwise, it immediately starts with the Bloom filter exchange.
6499 If the initiator receives a
6500 @code{GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_ELEMENT_INFO} response,
6501 it beings the Bloom filter exchange, unless the set size is indicated to
6502 be zero, in which case the intersection is considered finished after
6503 just the initial handshake.
6504
6505
6506 @menu
6507 * The Bloom filter exchange::
6508 * Salt::
6509 @end menu
6510
6511 @node The Bloom filter exchange
6512 @subsubsection The Bloom filter exchange
6513
6514 @c %**end of header
6515
6516 In this phase, each peer transmits a Bloom filter over the remaining
6517 keys of the local set to the other peer using a
6518 @code{GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_BF} message. This
6519 message additionally includes the number of elements left in the sender's
6520 set, as well as the XOR over all of the keys in that set.
6521
6522 The number of bits 'k' set per element in the Bloom filter is calculated
6523 based on the relative size of the two sets.
6524 Furthermore, the size of the Bloom filter is calculated based on 'k' and
6525 the number of elements in the set to maximize the amount of data filtered
6526 per byte transmitted on the wire (while avoiding an excessively high
6527 number of iterations).
6528
6529 The receiver of the message removes all elements from its local set that
6530 do not pass the Bloom filter test.
6531 It then checks if the set size of the sender and the XOR over the keys
6532 match what is left of his own set. If they do, he sends a
6533 @code{GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_DONE} back to indicate
6534 that the latest set is the final result.
6535 Otherwise, the receiver starts another Bloom fitler exchange, except
6536 this time as the sender.
6537
6538 @node Salt
6539 @subsubsection Salt
6540
6541 @c %**end of header
6542
6543 Bloomfilter operations are probablistic: With some non-zero probability
6544 the test may incorrectly say an element is in the set, even though it is
6545 not.
6546
6547 To mitigate this problem, the intersection protocol iterates exchanging
6548 Bloom filters using a different random 32-bit salt in each iteration (the
6549 salt is also included in the message).
6550 With different salts, set operations may fail for different elements.
6551 Merging the results from the executions, the probability of failure drops
6552 to zero.
6553
6554 The iterations terminate once both peers have established that they have
6555 sets of the same size, and where the XOR over all keys computes the same
6556 512-bit value (leaving a failure probability of 2-511).
6557
6558 @node The SET Union Peer-to-Peer Protocol
6559 @subsection The SET Union Peer-to-Peer Protocol
6560
6561 @c %**end of header
6562
6563 The SET union protocol is based on Eppstein's efficient set reconciliation
6564 without prior context. You should read this paper first if you want to
6565 understand the protocol.
6566
6567 The union protocol operates over CADET and starts with a
6568 GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST being sent by the peer
6569 initiating the operation to the peer listening for inbound requests.
6570 It includes the number of elements of the initiating peer, which is
6571 currently not used.
6572
6573 The listening peer checks if the operation type and application
6574 identifier are acceptable for its current state. If not, it responds with
6575 a @code{GNUNET_MESSAGE_TYPE_SET_RESULT} and a status of
6576 @code{GNUNET_SET_STATUS_FAILURE} (and terminates the CADET channel).
6577
6578 If the application accepts the request, it sends back a strata estimator
6579 using a message of type GNUNET_MESSAGE_TYPE_SET_UNION_P2P_SE. The
6580 initiator evaluates the strata estimator and initiates the exchange of
6581 invertible Bloom filters, sending a GNUNET_MESSAGE_TYPE_SET_UNION_P2P_IBF.
6582
6583 During the IBF exchange, if the receiver cannot invert the Bloom filter or
6584 detects a cycle, it sends a larger IBF in response (up to a defined
6585 maximum limit; if that limit is reached, the operation fails).
6586 Elements decoded while processing the IBF are transmitted to the other
6587 peer using GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENTS, or requested from the
6588 other peer using GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENT_REQUESTS messages,
6589 depending on the sign observed during decoding of the IBF.
6590 Peers respond to a GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENT_REQUESTS message
6591 with the respective element in a GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENTS
6592 message. If the IBF fully decodes, the peer responds with a
6593 GNUNET_MESSAGE_TYPE_SET_UNION_P2P_DONE message instead of another
6594 GNUNET_MESSAGE_TYPE_SET_UNION_P2P_IBF.
6595
6596 All Bloom filter operations use a salt to mingle keys before hasing them
6597 into buckets, such that future iterations have a fresh chance of
6598 succeeding if they failed due to collisions before.
6599
6600 @cindex STATISTICS Subsystem
6601 @node STATISTICS Subsystem
6602 @section STATISTICS Subsystem
6603
6604 @c %**end of header
6605
6606 In GNUnet, the STATISTICS subsystem offers a central place for all
6607 subsystems to publish unsigned 64-bit integer run-time statistics.
6608 Keeping this information centrally means that there is a unified way for
6609 the user to obtain data on all subsystems, and individual subsystems do
6610 not have to always include a custom data export method for performance
6611 metrics and other statistics. For example, the TRANSPORT system uses
6612 STATISTICS to update information about the number of directly connected
6613 peers and the bandwidth that has been consumed by the various plugins.
6614 This information is valuable for diagnosing connectivity and performance
6615 issues.
6616
6617 Following the GNUnet service architecture, the STATISTICS subsystem is
6618 divided into an API which is exposed through the header
6619 @strong{gnunet_statistics_service.h} and the STATISTICS service
6620 @strong{gnunet-service-statistics}. The @strong{gnunet-statistics}
6621 command-line tool can be used to obtain (and change) information about
6622 the values stored by the STATISTICS service. The STATISTICS service does
6623 not communicate with other peers.
6624
6625 Data is stored in the STATISTICS service in the form of tuples
6626 @strong{(subsystem, name, value, persistence)}. The subsystem determines
6627 to which other GNUnet's subsystem the data belongs. name is the name
6628 through which value is associated. It uniquely identifies the record
6629 from among other records belonging to the same subsystem.
6630 In some parts of the code, the pair @strong{(subsystem, name)} is called
6631 a @strong{statistic} as it identifies the values stored in the STATISTCS
6632 service.The persistence flag determines if the record has to be preserved
6633 across service restarts. A record is said to be persistent if this flag
6634 is set for it; if not, the record is treated as a non-persistent record
6635 and it is lost after service restart. Persistent records are written to
6636 and read from the file @strong{statistics.data} before shutdown
6637 and upon startup. The file is located in the HOME directory of the peer.
6638
6639 An anomaly of the STATISTICS service is that it does not terminate
6640 immediately upon receiving a shutdown signal if it has any clients
6641 connected to it. It waits for all the clients that are not monitors to
6642 close their connections before terminating itself.
6643 This is to prevent the loss of data during peer shutdown --- delaying the
6644 STATISTICS service shutdown helps other services to store important data
6645 to STATISTICS during shutdown.
6646
6647 @menu
6648 * libgnunetstatistics::
6649 * The STATISTICS Client-Service Protocol::
6650 @end menu
6651
6652 @cindex libgnunetstatistics
6653 @node libgnunetstatistics
6654 @subsection libgnunetstatistics
6655
6656 @c %**end of header
6657
6658 @strong{libgnunetstatistics} is the library containing the API for the
6659 STATISTICS subsystem. Any process requiring to use STATISTICS should use
6660 this API by to open a connection to the STATISTICS service.
6661 This is done by calling the function @code{GNUNET_STATISTICS_create()}.
6662 This function takes the subsystem's name which is trying to use STATISTICS
6663 and a configuration.
6664 All values written to STATISTICS with this connection will be placed in
6665 the section corresponding to the given subsystem's name.
6666 The connection to STATISTICS can be destroyed with the function
6667 @code{GNUNET_STATISTICS_destroy()}. This function allows for the
6668 connection to be destroyed immediately or upon transferring all
6669 pending write requests to the service.
6670
6671 Note: STATISTICS subsystem can be disabled by setting @code{DISABLE = YES}
6672 under the @code{[STATISTICS]} section in the configuration. With such a
6673 configuration all calls to @code{GNUNET_STATISTICS_create()} return
6674 @code{NULL} as the STATISTICS subsystem is unavailable and no other
6675 functions from the API can be used.
6676
6677
6678 @menu
6679 * Statistics retrieval::
6680 * Setting statistics and updating them::
6681 * Watches::
6682 @end menu
6683
6684 @node Statistics retrieval
6685 @subsubsection Statistics retrieval
6686
6687 @c %**end of header
6688
6689 Once a connection to the statistics service is obtained, information
6690 about any other system which uses statistics can be retrieved with the
6691 function GNUNET_STATISTICS_get().
6692 This function takes the connection handle, the name of the subsystem
6693 whose information we are interested in (a @code{NULL} value will
6694 retrieve information of all available subsystems using STATISTICS), the
6695 name of the statistic we are interested in (a @code{NULL} value will
6696 retrieve all available statistics), a continuation callback which is
6697 called when all of requested information is retrieved, an iterator
6698 callback which is called for each parameter in the retrieved information
6699 and a closure for the aforementioned callbacks. The library then invokes
6700 the iterator callback for each value matching the request.
6701
6702 Call to @code{GNUNET_STATISTICS_get()} is asynchronous and can be
6703 canceled with the function @code{GNUNET_STATISTICS_get_cancel()}.
6704 This is helpful when retrieving statistics takes too long and especially
6705 when we want to shutdown and cleanup everything.
6706
6707 @node Setting statistics and updating them
6708 @subsubsection Setting statistics and updating them
6709
6710 @c %**end of header
6711
6712 So far we have seen how to retrieve statistics, here we will learn how we
6713 can set statistics and update them so that other subsystems can retrieve
6714 them.
6715
6716 A new statistic can be set using the function
6717 @code{GNUNET_STATISTICS_set()}.
6718 This function takes the name of the statistic and its value and a flag to
6719 make the statistic persistent.
6720 The value of the statistic should be of the type @code{uint64_t}.
6721 The function does not take the name of the subsystem; it is determined
6722 from the previous @code{GNUNET_STATISTICS_create()} invocation. If
6723 the given statistic is already present, its value is overwritten.
6724
6725 An existing statistics can be updated, i.e its value can be increased or
6726 decreased by an amount with the function
6727 @code{GNUNET_STATISTICS_update()}.
6728 The parameters to this function are similar to
6729 @code{GNUNET_STATISTICS_set()}, except that it takes the amount to be
6730 changed as a type @code{int64_t} instead of the value.
6731
6732 The library will combine multiple set or update operations into one
6733 message if the client performs requests at a rate that is faster than the
6734 available IPC with the STATISTICS service. Thus, the client does not have
6735 to worry about sending requests too quickly.
6736
6737 @node Watches
6738 @subsubsection Watches
6739
6740 @c %**end of header
6741
6742 As interesting feature of STATISTICS lies in serving notifications
6743 whenever a statistic of our interest is modified.
6744 This is achieved by registering a watch through the function
6745 @code{GNUNET_STATISTICS_watch()}.
6746 The parameters of this function are similar to those of
6747 @code{GNUNET_STATISTICS_get()}.
6748 Changes to the respective statistic's value will then cause the given
6749 iterator callback to be called.
6750 Note: A watch can only be registered for a specific statistic. Hence
6751 the subsystem name and the parameter name cannot be @code{NULL} in a
6752 call to @code{GNUNET_STATISTICS_watch()}.
6753
6754 A registered watch will keep notifying any value changes until
6755 @code{GNUNET_STATISTICS_watch_cancel()} is called with the same
6756 parameters that are used for registering the watch.
6757
6758 @node The STATISTICS Client-Service Protocol
6759 @subsection The STATISTICS Client-Service Protocol
6760 @c %**end of header
6761
6762
6763 @menu
6764 * Statistics retrieval2::
6765 * Setting and updating statistics::
6766 * Watching for updates::
6767 @end menu
6768
6769 @node Statistics retrieval2
6770 @subsubsection Statistics retrieval2
6771
6772 @c %**end of header
6773
6774 To retrieve statistics, the client transmits a message of type
6775 @code{GNUNET_MESSAGE_TYPE_STATISTICS_GET} containing the given subsystem
6776 name and statistic parameter to the STATISTICS service.
6777 The service responds with a message of type
6778 @code{GNUNET_MESSAGE_TYPE_STATISTICS_VALUE} for each of the statistics
6779 parameters that match the client request for the client. The end of
6780 information retrieved is signaled by the service by sending a message of
6781 type @code{GNUNET_MESSAGE_TYPE_STATISTICS_END}.
6782
6783 @node Setting and updating statistics
6784 @subsubsection Setting and updating statistics
6785
6786 @c %**end of header
6787
6788 The subsystem name, parameter name, its value and the persistence flag are
6789 communicated to the service through the message
6790 @code{GNUNET_MESSAGE_TYPE_STATISTICS_SET}.
6791
6792 When the service receives a message of type
6793 @code{GNUNET_MESSAGE_TYPE_STATISTICS_SET}, it retrieves the subsystem
6794 name and checks for a statistic parameter with matching the name given in
6795 the message.
6796 If a statistic parameter is found, the value is overwritten by the new
6797 value from the message; if not found then a new statistic parameter is
6798 created with the given name and value.
6799
6800 In addition to just setting an absolute value, it is possible to perform a
6801 relative update by sending a message of type
6802 @code{GNUNET_MESSAGE_TYPE_STATISTICS_SET} with an update flag
6803 (@code{GNUNET_STATISTICS_SETFLAG_RELATIVE}) signifying that the value in
6804 the message should be treated as an update value.
6805
6806 @node Watching for updates
6807 @subsubsection Watching for updates
6808
6809 @c %**end of header
6810
6811 The function registers the watch at the service by sending a message of
6812 type @code{GNUNET_MESSAGE_TYPE_STATISTICS_WATCH}. The service then sends
6813 notifications through messages of type
6814 @code{GNUNET_MESSAGE_TYPE_STATISTICS_WATCH_VALUE} whenever the statistic
6815 parameter's value is changed.
6816
6817 @cindex DHT
6818 @cindex Distributed Hash Table
6819 @node Distributed Hash Table (DHT)
6820 @section Distributed Hash Table (DHT)
6821
6822 @c %**end of header
6823
6824 GNUnet includes a generic distributed hash table that can be used by
6825 developers building P2P applications in the framework.
6826 This section documents high-level features and how developers are
6827 expected to use the DHT.
6828 We have a research paper detailing how the DHT works.
6829 Also, Nate's thesis includes a detailed description and performance
6830 analysis (in chapter 6).
6831
6832 Key features of GNUnet's DHT include:
6833
6834 @itemize @bullet
6835 @item stores key-value pairs with values up to (approximately) 63k in size
6836 @item works with many underlay network topologies (small-world, random
6837 graph), underlay does not need to be a full mesh / clique
6838 @item support for extended queries (more than just a simple 'key'),
6839 filtering duplicate replies within the network (bloomfilter) and content
6840 validation (for details, please read the subsection on the block library)
6841 @item can (optionally) return paths taken by the PUT and GET operations
6842 to the application
6843 @item provides content replication to handle churn
6844 @end itemize
6845
6846 GNUnet's DHT is randomized and unreliable. Unreliable means that there is
6847 no strict guarantee that a value stored in the DHT is always
6848 found --- values are only found with high probability.
6849 While this is somewhat true in all P2P DHTs, GNUnet developers should be
6850 particularly wary of this fact (this will help you write secure,
6851 fault-tolerant code). Thus, when writing any application using the DHT,
6852 you should always consider the possibility that a value stored in the
6853 DHT by you or some other peer might simply not be returned, or returned
6854 with a significant delay.
6855 Your application logic must be written to tolerate this (naturally, some
6856 loss of performance or quality of service is expected in this case).
6857
6858 @menu
6859 * Block library and plugins::
6860 * libgnunetdht::
6861 * The DHT Client-Service Protocol::
6862 * The DHT Peer-to-Peer Protocol::
6863 @end menu
6864
6865 @node Block library and plugins
6866 @subsection Block library and plugins
6867
6868 @c %**end of header
6869
6870 @menu
6871 * What is a Block?::
6872 * The API of libgnunetblock::
6873 * Queries::
6874 * Sample Code::
6875 * Conclusion2::
6876 @end menu
6877
6878 @node What is a Block?
6879 @subsubsection What is a Block?
6880
6881 @c %**end of header
6882
6883 Blocks are small (< 63k) pieces of data stored under a key (struct
6884 GNUNET_HashCode). Blocks have a type (enum GNUNET_BlockType) which defines
6885 their data format. Blocks are used in GNUnet as units of static data
6886 exchanged between peers and stored (or cached) locally.
6887 Uses of blocks include file-sharing (the files are broken up into blocks),
6888 the VPN (DNS information is stored in blocks) and the DHT (all
6889 information in the DHT and meta-information for the maintenance of the
6890 DHT are both stored using blocks).
6891 The block subsystem provides a few common functions that must be
6892 available for any type of block.
6893
6894 @cindex libgnunetblock API
6895 @node The API of libgnunetblock
6896 @subsubsection The API of libgnunetblock
6897
6898 @c %**end of header
6899
6900 The block library requires for each (family of) block type(s) a block
6901 plugin (implementing @file{gnunet_block_plugin.h}) that provides basic
6902 functions that are needed by the DHT (and possibly other subsystems) to
6903 manage the block.
6904 These block plugins are typically implemented within their respective
6905 subsystems.
6906 The main block library is then used to locate, load and query the
6907 appropriate block plugin.
6908 Which plugin is appropriate is determined by the block type (which is
6909 just a 32-bit integer). Block plugins contain code that specifies which
6910 block types are supported by a given plugin. The block library loads all
6911 block plugins that are installed at the local peer and forwards the
6912 application request to the respective plugin.
6913
6914 The central functions of the block APIs (plugin and main library) are to
6915 allow the mapping of blocks to their respective key (if possible) and the
6916 ability to check that a block is well-formed and matches a given
6917 request (again, if possible).
6918 This way, GNUnet can avoid storing invalid blocks, storing blocks under
6919 the wrong key and forwarding blocks in response to a query that they do
6920 not answer.
6921
6922 One key function of block plugins is that it allows GNUnet to detect
6923 duplicate replies (via the Bloom filter). All plugins MUST support
6924 detecting duplicate replies (by adding the current response to the
6925 Bloom filter and rejecting it if it is encountered again).
6926 If a plugin fails to do this, responses may loop in the network.
6927
6928 @node Queries
6929 @subsubsection Queries
6930 @c %**end of header
6931
6932 The query format for any block in GNUnet consists of four main components.
6933 First, the type of the desired block must be specified. Second, the query
6934 must contain a hash code. The hash code is used for lookups in hash
6935 tables and databases and must not be unique for the block (however, if
6936 possible a unique hash should be used as this would be best for
6937 performance).
6938 Third, an optional Bloom filter can be specified to exclude known results;
6939 replies that hash to the bits set in the Bloom filter are considered
6940 invalid. False-positives can be eliminated by sending the same query
6941 again with a different Bloom filter mutator value, which parameterizes
6942 the hash function that is used.
6943 Finally, an optional application-specific "eXtended query" (xquery) can
6944 be specified to further constrain the results. It is entirely up to
6945 the type-specific plugin to determine whether or not a given block
6946 matches a query (type, hash, Bloom filter, and xquery).
6947 Naturally, not all xquery's are valid and some types of blocks may not
6948 support Bloom filters either, so the plugin also needs to check if the
6949 query is valid in the first place.
6950
6951 Depending on the results from the plugin, the DHT will then discard the
6952 (invalid) query, forward the query, discard the (invalid) reply, cache the
6953 (valid) reply, and/or forward the (valid and non-duplicate) reply.
6954
6955 @node Sample Code
6956 @subsubsection Sample Code
6957
6958 @c %**end of header
6959
6960 The source code in @strong{plugin_block_test.c} is a good starting point
6961 for new block plugins --- it does the minimal work by implementing a
6962 plugin that performs no validation at all.
6963 The respective @strong{Makefile.am} shows how to build and install a
6964 block plugin.
6965
6966 @node Conclusion2
6967 @subsubsection Conclusion2
6968
6969 @c %**end of header
6970
6971 In conclusion, GNUnet subsystems that want to use the DHT need to define a
6972 block format and write a plugin to match queries and replies. For testing,
6973 the @code{GNUNET_BLOCK_TYPE_TEST} block type can be used; it accepts
6974 any query as valid and any reply as matching any query.
6975 This type is also used for the DHT command line tools.
6976 However, it should NOT be used for normal applications due to the lack
6977 of error checking that results from this primitive implementation.
6978
6979 @cindex libgnunetdht
6980 @node libgnunetdht
6981 @subsection libgnunetdht
6982
6983 @c %**end of header
6984
6985 The DHT API itself is pretty simple and offers the usual GET and PUT
6986 functions that work as expected. The specified block type refers to the
6987 block library which allows the DHT to run application-specific logic for
6988 data stored in the network.
6989
6990
6991 @menu
6992 * GET::
6993 * PUT::
6994 * MONITOR::
6995 * DHT Routing Options::
6996 @end menu
6997
6998 @node GET
6999 @subsubsection GET
7000
7001 @c %**end of header
7002
7003 When using GET, the main consideration for developers (other than the
7004 block library) should be that after issuing a GET, the DHT will
7005 continuously cause (small amounts of) network traffic until the operation
7006 is explicitly canceled.
7007 So GET does not simply send out a single network request once; instead,
7008 the DHT will continue to search for data. This is needed to achieve good
7009 success rates and also handles the case where the respective PUT
7010 operation happens after the GET operation was started.
7011 Developers should not cancel an existing GET operation and then
7012 explicitly re-start it to trigger a new round of network requests;
7013 this is simply inefficient, especially as the internal automated version
7014 can be more efficient, for example by filtering results in the network
7015 that have already been returned.
7016
7017 If an application that performs a GET request has a set of replies that it
7018 already knows and would like to filter, it can call@
7019 @code{GNUNET_DHT_get_filter_known_results} with an array of hashes over
7020 the respective blocks to tell the DHT that these results are not
7021 desired (any more).
7022 This way, the DHT will filter the respective blocks using the block
7023 library in the network, which may result in a significant reduction in
7024 bandwidth consumption.
7025
7026 @node PUT
7027 @subsubsection PUT
7028
7029 @c %**end of header
7030
7031 @c inconsistent use of ``must'' above it's written ``MUST''
7032 In contrast to GET operations, developers @strong{must} manually re-run
7033 PUT operations periodically (if they intend the content to continue to be
7034 available). Content stored in the DHT expires or might be lost due to
7035 churn.
7036 Furthermore, GNUnet's DHT typically requires multiple rounds of PUT
7037 operations before a key-value pair is consistently available to all
7038 peers (the DHT randomizes paths and thus storage locations, and only
7039 after multiple rounds of PUTs there will be a sufficient number of
7040 replicas in large DHTs). An explicit PUT operation using the DHT API will
7041 only cause network traffic once, so in order to ensure basic availability
7042 and resistance to churn (and adversaries), PUTs must be repeated.
7043 While the exact frequency depends on the application, a rule of thumb is
7044 that there should be at least a dozen PUT operations within the content
7045 lifetime. Content in the DHT typically expires after one day, so
7046 DHT PUT operations should be repeated at least every 1-2 hours.
7047
7048 @node MONITOR
7049 @subsubsection MONITOR
7050
7051 @c %**end of header
7052
7053 The DHT API also allows applications to monitor messages crossing the
7054 local DHT service.
7055 The types of messages used by the DHT are GET, PUT and RESULT messages.
7056 Using the monitoring API, applications can choose to monitor these
7057 requests, possibly limiting themselves to requests for a particular block
7058 type.
7059
7060 The monitoring API is not only useful for diagnostics, it can also be
7061 used to trigger application operations based on PUT operations.
7062 For example, an application may use PUTs to distribute work requests to
7063 other peers.
7064 The workers would then monitor for PUTs that give them work, instead of
7065 looking for work using GET operations.
7066 This can be beneficial, especially if the workers have no good way to
7067 guess the keys under which work would be stored.
7068 Naturally, additional protocols might be needed to ensure that the desired
7069 number of workers will process the distributed workload.
7070
7071 @node DHT Routing Options
7072 @subsubsection DHT Routing Options
7073
7074 @c %**end of header
7075
7076 There are two important options for GET and PUT requests:
7077
7078 @table @asis
7079 @item GNUNET_DHT_RO_DEMULITPLEX_EVERYWHERE This option means that all
7080 peers should process the request, even if their peer ID is not closest to
7081 the key. For a PUT request, this means that all peers that a request
7082 traverses may make a copy of the data.
7083 Similarly for a GET request, all peers will check their local database
7084 for a result. Setting this option can thus significantly improve caching
7085 and reduce bandwidth consumption --- at the expense of a larger DHT
7086 database. If in doubt, we recommend that this option should be used.
7087 @item GNUNET_DHT_RO_RECORD_ROUTE This option instructs the DHT to record
7088 the path that a GET or a PUT request is taking through the overlay
7089 network. The resulting paths are then returned to the application with
7090 the respective result. This allows the receiver of a result to construct
7091 a path to the originator of the data, which might then be used for
7092 routing. Naturally, setting this option requires additional bandwidth
7093 and disk space, so applications should only set this if the paths are
7094 needed by the application logic.
7095 @item GNUNET_DHT_RO_FIND_PEER This option is an internal option used by
7096 the DHT's peer discovery mechanism and should not be used by applications.
7097 @item GNUNET_DHT_RO_BART This option is currently not implemented. It may
7098 in the future offer performance improvements for clique topologies.
7099 @end table
7100
7101 @node The DHT Client-Service Protocol
7102 @subsection The DHT Client-Service Protocol
7103
7104 @c %**end of header
7105
7106 @menu
7107 * PUTting data into the DHT::
7108 * GETting data from the DHT::
7109 * Monitoring the DHT::
7110 @end menu
7111
7112 @node PUTting data into the DHT
7113 @subsubsection PUTting data into the DHT
7114
7115 @c %**end of header
7116
7117 To store (PUT) data into the DHT, the client sends a
7118 @code{struct GNUNET_DHT_ClientPutMessage} to the service.
7119 This message specifies the block type, routing options, the desired
7120 replication level, the expiration time, key,
7121 value and a 64-bit unique ID for the operation. The service responds with
7122 a @code{struct GNUNET_DHT_ClientPutConfirmationMessage} with the same
7123 64-bit unique ID. Note that the service sends the confirmation as soon as
7124 it has locally processed the PUT request. The PUT may still be
7125 propagating through the network at this time.
7126
7127 In the future, we may want to change this to provide (limited) feedback
7128 to the client, for example if we detect that the PUT operation had no
7129 effect because the same key-value pair was already stored in the DHT.
7130 However, changing this would also require additional state and messages
7131 in the P2P interaction.
7132
7133 @node GETting data from the DHT
7134 @subsubsection GETting data from the DHT
7135
7136 @c %**end of header
7137
7138 To retrieve (GET) data from the DHT, the client sends a
7139 @code{struct GNUNET_DHT_ClientGetMessage} to the service. The message
7140 specifies routing options, a replication level (for replicating the GET,
7141 not the content), the desired block type, the key, the (optional)
7142 extended query and unique 64-bit request ID.
7143
7144 Additionally, the client may send any number of
7145 @code{struct GNUNET_DHT_ClientGetResultSeenMessage}s to notify the
7146 service about results that the client is already aware of.
7147 These messages consist of the key, the unique 64-bit ID of the request,
7148 and an arbitrary number of hash codes over the blocks that the client is
7149 already aware of. As messages are restricted to 64k, a client that
7150 already knows more than about a thousand blocks may need to send
7151 several of these messages. Naturally, the client should transmit these
7152 messages as quickly as possible after the original GET request such that
7153 the DHT can filter those results in the network early on. Naturally, as
7154 these messages are sent after the original request, it is conceivalbe
7155 that the DHT service may return blocks that match those already known
7156 to the client anyway.
7157
7158 In response to a GET request, the service will send @code{struct
7159 GNUNET_DHT_ClientResultMessage}s to the client. These messages contain the
7160 block type, expiration, key, unique ID of the request and of course the
7161 value (a block). Depending on the options set for the respective
7162 operations, the replies may also contain the path the GET and/or the PUT
7163 took through the network.
7164
7165 A client can stop receiving replies either by disconnecting or by sending
7166 a @code{struct GNUNET_DHT_ClientGetStopMessage} which must contain the
7167 key and the 64-bit unique ID of the original request. Using an
7168 explicit "stop" message is more common as this allows a client to run
7169 many concurrent GET operations over the same connection with the DHT
7170 service --- and to stop them individually.
7171
7172 @node Monitoring the DHT
7173 @subsubsection Monitoring the DHT
7174
7175 @c %**end of header
7176
7177 To begin monitoring, the client sends a
7178 @code{struct GNUNET_DHT_MonitorStartStop} message to the DHT service.
7179 In this message, flags can be set to enable (or disable) monitoring of
7180 GET, PUT and RESULT messages that pass through a peer. The message can
7181 also restrict monitoring to a particular block type or a particular key.
7182 Once monitoring is enabled, the DHT service will notify the client about
7183 any matching event using @code{struct GNUNET_DHT_MonitorGetMessage}s for
7184 GET events, @code{struct GNUNET_DHT_MonitorPutMessage} for PUT events
7185 and @code{struct GNUNET_DHT_MonitorGetRespMessage} for RESULTs. Each of
7186 these messages contains all of the information about the event.
7187
7188 @node The DHT Peer-to-Peer Protocol
7189 @subsection The DHT Peer-to-Peer Protocol
7190 @c %**end of header
7191
7192
7193 @menu
7194 * Routing GETs or PUTs::
7195 * PUTting data into the DHT2::
7196 * GETting data from the DHT2::
7197 @end menu
7198
7199 @node Routing GETs or PUTs
7200 @subsubsection Routing GETs or PUTs
7201
7202 @c %**end of header
7203
7204 When routing GETs or PUTs, the DHT service selects a suitable subset of
7205 neighbours for forwarding. The exact number of neighbours can be zero or
7206 more and depends on the hop counter of the query (initially zero) in
7207 relation to the (log of) the network size estimate, the desired
7208 replication level and the peer's connectivity.
7209 Depending on the hop counter and our network size estimate, the selection
7210 of the peers maybe randomized or by proximity to the key.
7211 Furthermore, requests include a set of peers that a request has already
7212 traversed; those peers are also excluded from the selection.
7213
7214 @node PUTting data into the DHT2
7215 @subsubsection PUTting data into the DHT2
7216
7217 @c %**end of header
7218
7219 To PUT data into the DHT, the service sends a @code{struct PeerPutMessage}
7220 of type @code{GNUNET_MESSAGE_TYPE_DHT_P2P_PUT} to the respective
7221 neighbour.
7222 In addition to the usual information about the content (type, routing
7223 options, desired replication level for the content, expiration time, key
7224 and value), the message contains a fixed-size Bloom filter with
7225 information about which peers (may) have already seen this request.
7226 This Bloom filter is used to ensure that DHT messages never loop back to
7227 a peer that has already processed the request.
7228 Additionally, the message includes the current hop counter and, depending
7229 on the routing options, the message may include the full path that the
7230 message has taken so far.
7231 The Bloom filter should already contain the identity of the previous hop;
7232 however, the path should not include the identity of the previous hop and
7233 the receiver should append the identity of the sender to the path, not
7234 its own identity (this is done to reduce bandwidth).
7235
7236 @node GETting data from the DHT2
7237 @subsubsection GETting data from the DHT2
7238
7239 @c %**end of header
7240
7241 A peer can search the DHT by sending @code{struct PeerGetMessage}s of type
7242 @code{GNUNET_MESSAGE_TYPE_DHT_P2P_GET} to other peers. In addition to the
7243 usual information about the request (type, routing options, desired
7244 replication level for the request, the key and the extended query), a GET
7245 request also contains a hop counter, a Bloom filter over the peers
7246 that have processed the request already and depending on the routing
7247 options the full path traversed by the GET.
7248 Finally, a GET request includes a variable-size second Bloom filter and a
7249 so-called Bloom filter mutator value which together indicate which
7250 replies the sender has already seen. During the lookup, each block that
7251 matches they block type, key and extended query is additionally subjected
7252 to a test against this Bloom filter.
7253 The block plugin is expected to take the hash of the block and combine it
7254 with the mutator value and check if the result is not yet in the Bloom
7255 filter. The originator of the query will from time to time modify the
7256 mutator to (eventually) allow false-positives filtered by the Bloom filter
7257 to be returned.
7258
7259 Peers that receive a GET request perform a local lookup (depending on
7260 their proximity to the key and the query options) and forward the request
7261 to other peers.
7262 They then remember the request (including the Bloom filter for blocking
7263 duplicate results) and when they obtain a matching, non-filtered response
7264 a @code{struct PeerResultMessage} of type
7265 @code{GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT} is forwarded to the previous
7266 hop.
7267 Whenver a result is forwarded, the block plugin is used to update the
7268 Bloom filter accordingly, to ensure that the same result is never
7269 forwarded more than once.
7270 The DHT service may also cache forwarded results locally if the
7271 "CACHE_RESULTS" option is set to "YES" in the configuration.
7272
7273 @cindex GNS
7274 @cindex GNU Name System
7275 @node GNU Name System (GNS)
7276 @section GNU Name System (GNS)
7277
7278 @c %**end of header
7279
7280 The GNU Name System (GNS) is a decentralized database that enables users
7281 to securely resolve names to values.
7282 Names can be used to identify other users (for example, in social
7283 networking), or network services (for example, VPN services running at a
7284 peer in GNUnet, or purely IP-based services on the Internet).
7285 Users interact with GNS by typing in a hostname that ends in ".gnu"
7286 or ".zkey".
7287
7288 Videos giving an overview of most of the GNS and the motivations behind
7289 it is available here and here.
7290 The remainder of this chapter targets developers that are familiar with
7291 high level concepts of GNS as presented in these talks.
7292 @c TODO: Add links to here and here and to these.
7293
7294 GNS-aware applications should use the GNS resolver to obtain the
7295 respective records that are stored under that name in GNS.
7296 Each record consists of a type, value, expiration time and flags.
7297
7298 The type specifies the format of the value. Types below 65536 correspond
7299 to DNS record types, larger values are used for GNS-specific records.
7300 Applications can define new GNS record types by reserving a number and
7301 implementing a plugin (which mostly needs to convert the binary value
7302 representation to a human-readable text format and vice-versa).
7303 The expiration time specifies how long the record is to be valid.
7304 The GNS API ensures that applications are only given non-expired values.
7305 The flags are typically irrelevant for applications, as GNS uses them
7306 internally to control visibility and validity of records.
7307
7308 Records are stored along with a signature.
7309 The signature is generated using the private key of the authoritative
7310 zone. This allows any GNS resolver to verify the correctness of a
7311 name-value mapping.
7312
7313 Internally, GNS uses the NAMECACHE to cache information obtained from
7314 other users, the NAMESTORE to store information specific to the local
7315 users, and the DHT to exchange data between users.
7316 A plugin API is used to enable applications to define new GNS
7317 record types.
7318
7319 @menu
7320 * libgnunetgns::
7321 * libgnunetgnsrecord::
7322 * GNS plugins::
7323 * The GNS Client-Service Protocol::
7324 * Hijacking the DNS-Traffic using gnunet-service-dns::
7325 * Serving DNS lookups via GNS on W32::
7326 @end menu
7327
7328 @node libgnunetgns
7329 @subsection libgnunetgns
7330
7331 @c %**end of header
7332
7333 The GNS API itself is extremely simple. Clients first connec to the
7334 GNS service using @code{GNUNET_GNS_connect}.
7335 They can then perform lookups using @code{GNUNET_GNS_lookup} or cancel
7336 pending lookups using @code{GNUNET_GNS_lookup_cancel}.
7337 Once finished, clients disconnect using @code{GNUNET_GNS_disconnect}.
7338
7339 @menu
7340 * Looking up records::
7341 * Accessing the records::
7342 * Creating records::
7343 * Future work::
7344 @end menu
7345
7346 @node Looking up records
7347 @subsubsection Looking up records
7348
7349 @c %**end of header
7350
7351 @code{GNUNET_GNS_lookup} takes a number of arguments:
7352
7353 @table @asis
7354 @item handle This is simply the GNS connection handle from
7355 @code{GNUNET_GNS_connect}.
7356 @item name The client needs to specify the name to
7357 be resolved. This can be any valid DNS or GNS hostname.
7358 @item zone The client
7359 needs to specify the public key of the GNS zone against which the
7360 resolution should be done (the ".gnu" zone).
7361 Note that a key must be provided, even if the name ends in ".zkey".
7362 This should typically be the public key of the master-zone of the user.
7363 @item type This is the desired GNS or DNS record type
7364 to look for. While all records for the given name will be returned, this
7365 can be important if the client wants to resolve record types that
7366 themselves delegate resolution, such as CNAME, PKEY or GNS2DNS.
7367 Resolving a record of any of these types will only work if the respective
7368 record type is specified in the request, as the GNS resolver will
7369 otherwise follow the delegation and return the records from the
7370 respective destination, instead of the delegating record.
7371 @item only_cached This argument should typically be set to
7372 @code{GNUNET_NO}. Setting it to @code{GNUNET_YES} disables resolution via
7373 the overlay network.
7374 @item shorten_zone_key If GNS encounters new names during resolution,
7375 their respective zones can automatically be learned and added to the
7376 "shorten zone". If this is desired, clients must pass the private key of
7377 the shorten zone. If NULL is passed, shortening is disabled.
7378 @item proc This argument identifies
7379 the function to call with the result. It is given proc_cls, the number of
7380 records found (possilby zero) and the array of the records as arguments.
7381 proc will only be called once. After proc,> has been called, the lookup
7382 must no longer be cancelled.
7383 @item proc_cls The closure for proc.
7384 @end table
7385
7386 @node Accessing the records
7387 @subsubsection Accessing the records
7388
7389 @c %**end of header
7390
7391 The @code{libgnunetgnsrecord} library provides an API to manipulate the
7392 GNS record array that is given to proc. In particular, it offers
7393 functions such as converting record values to human-readable
7394 strings (and back). However, most @code{libgnunetgnsrecord} functions are
7395 not interesting to GNS client applications.
7396
7397 For DNS records, the @code{libgnunetdnsparser} library provides
7398 functions for parsing (and serializing) common types of DNS records.
7399
7400 @node Creating records
7401 @subsubsection Creating records
7402
7403 @c %**end of header
7404
7405 Creating GNS records is typically done by building the respective record
7406 information (possibly with the help of @code{libgnunetgnsrecord} and
7407 @code{libgnunetdnsparser}) and then using the @code{libgnunetnamestore} to
7408 publish the information. The GNS API is not involved in this
7409 operation.
7410
7411 @node Future work
7412 @subsubsection Future work
7413
7414 @c %**end of header
7415
7416 In the future, we want to expand @code{libgnunetgns} to allow
7417 applications to observe shortening operations performed during GNS
7418 resolution, for example so that users can receive visual feedback when
7419 this happens.
7420
7421 @node libgnunetgnsrecord
7422 @subsection libgnunetgnsrecord
7423
7424 @c %**end of header
7425
7426 The @code{libgnunetgnsrecord} library is used to manipulate GNS
7427 records (in plaintext or in their encrypted format).
7428 Applications mostly interact with @code{libgnunetgnsrecord} by using the
7429 functions to convert GNS record values to strings or vice-versa, or to
7430 lookup a GNS record type number by name (or vice-versa).
7431 The library also provides various other functions that are mostly
7432 used internally within GNS, such as converting keys to names, checking for
7433 expiration, encrypting GNS records to GNS blocks, verifying GNS block
7434 signatures and decrypting GNS records from GNS blocks.
7435
7436 We will now discuss the four commonly used functions of the API.@
7437 @code{libgnunetgnsrecord} does not perform these operations itself,
7438 but instead uses plugins to perform the operation.
7439 GNUnet includes plugins to support common DNS record types as well as
7440 standard GNS record types.
7441
7442 @menu
7443 * Value handling::
7444 * Type handling::
7445 @end menu
7446
7447 @node Value handling
7448 @subsubsection Value handling
7449
7450 @c %**end of header
7451
7452 @code{GNUNET_GNSRECORD_value_to_string} can be used to convert
7453 the (binary) representation of a GNS record value to a human readable,
7454 0-terminated UTF-8 string.
7455 NULL is returned if the specified record type is not supported by any
7456 available plugin.
7457
7458 @code{GNUNET_GNSRECORD_string_to_value} can be used to try to convert a
7459 human readable string to the respective (binary) representation of
7460 a GNS record value.
7461
7462 @node Type handling
7463 @subsubsection Type handling
7464
7465 @c %**end of header
7466
7467 @code{GNUNET_GNSRECORD_typename_to_number} can be used to obtain the
7468 numeric value associated with a given typename. For example, given the
7469 typename "A" (for DNS A reocrds), the function will return the number 1.
7470 A list of common DNS record types is
7471 @uref{http://en.wikipedia.org/wiki/List_of_DNS_record_types, here}.
7472 Note that not all DNS record types are supported by GNUnet GNSRECORD
7473 plugins at this time.
7474
7475 @code{GNUNET_GNSRECORD_number_to_typename} can be used to obtain the
7476 typename associated with a given numeric value.
7477 For example, given the type number 1, the function will return the
7478 typename "A".
7479
7480 @node GNS plugins
7481 @subsection GNS plugins
7482
7483 @c %**end of header
7484
7485 Adding a new GNS record type typically involves writing (or extending) a
7486 GNSRECORD plugin. The plugin needs to implement the
7487 @code{gnunet_gnsrecord_plugin.h} API which provides basic functions that
7488 are needed by GNSRECORD to convert typenames and values of the respective
7489 record type to strings (and back).
7490 These gnsrecord plugins are typically implemented within their respective
7491 subsystems.
7492 Examples for such plugins can be found in the GNSRECORD, GNS and
7493 CONVERSATION subsystems.
7494
7495 The @code{libgnunetgnsrecord} library is then used to locate, load and
7496 query the appropriate gnsrecord plugin.
7497 Which plugin is appropriate is determined by the record type (which is
7498 just a 32-bit integer). The @code{libgnunetgnsrecord} library loads all
7499 block plugins that are installed at the local peer and forwards the
7500 application request to the plugins. If the record type is not
7501 supported by the plugin, it should simply return an error code.
7502
7503 The central functions of the block APIs (plugin and main library) are the
7504 same four functions for converting between values and strings, and
7505 typenames and numbers documented in the previous subsection.
7506
7507 @node The GNS Client-Service Protocol
7508 @subsection The GNS Client-Service Protocol
7509 @c %**end of header
7510
7511 The GNS client-service protocol consists of two simple messages, the
7512 @code{LOOKUP} message and the @code{LOOKUP_RESULT}. Each @code{LOOKUP}
7513 message contains a unique 32-bit identifier, which will be included in the
7514 corresponding response. Thus, clients can send many lookup requests in
7515 parallel and receive responses out-of-order.
7516 A @code{LOOKUP} request also includes the public key of the GNS zone,
7517 the desired record type and fields specifying whether shortening is
7518 enabled or networking is disabled. Finally, the @code{LOOKUP} message
7519 includes the name to be resolved.
7520
7521 The response includes the number of records and the records themselves
7522 in the format created by @code{GNUNET_GNSRECORD_records_serialize}.
7523 They can thus be deserialized using
7524 @code{GNUNET_GNSRECORD_records_deserialize}.
7525
7526 @node Hijacking the DNS-Traffic using gnunet-service-dns
7527 @subsection Hijacking the DNS-Traffic using gnunet-service-dns
7528
7529 @c %**end of header
7530
7531 This section documents how the gnunet-service-dns (and the
7532 gnunet-helper-dns) intercepts DNS queries from the local system.
7533 This is merely one method for how we can obtain GNS queries.
7534 It is also possible to change @code{resolv.conf} to point to a machine
7535 running @code{gnunet-dns2gns} or to modify libc's name system switch
7536 (NSS) configuration to include a GNS resolution plugin.
7537 The method described in this chaper is more of a last-ditch catch-all
7538 approach.
7539
7540 @code{gnunet-service-dns} enables intercepting DNS traffic using policy
7541 based routing.
7542 We MARK every outgoing DNS-packet if it was not sent by our application.
7543 Using a second routing table in the Linux kernel these marked packets are
7544 then routed through our virtual network interface and can thus be
7545 captured unchanged.
7546
7547 Our application then reads the query and decides how to handle it: A
7548 query to an address ending in ".gnu" or ".zkey" is hijacked by
7549 @code{gnunet-service-gns} and resolved internally using GNS.
7550 In the future, a reverse query for an address of the configured virtual
7551 network could be answered with records kept about previous forward
7552 queries.
7553 Queries that are not hijacked by some application using the DNS service
7554 will be sent to the original recipient.
7555 The answer to the query will always be sent back through the virtual
7556 interface with the original nameserver as source address.
7557
7558
7559 @menu
7560 * Network Setup Details::
7561 @end menu
7562
7563 @node Network Setup Details
7564 @subsubsection Network Setup Details
7565
7566 @c %**end of header
7567
7568 The DNS interceptor adds the following rules to the Linux kernel:
7569 @example
7570 iptables -t mangle -I OUTPUT 1 -p udp --sport $LOCALPORT --dport 53 \
7571 -j ACCEPT iptables -t mangle -I OUTPUT 2 -p udp --dport 53 -j MARK \
7572 --set-mark 3 ip rule add fwmark 3 table2 ip route add default via \
7573 $VIRTUALDNS table2
7574 @end example
7575
7576 @c FIXME: Rewrite to reflect display which is no longer content by line
7577 @c FIXME: due to the < 74 characters limit.
7578 Line 1 makes sure that all packets coming from a port our application
7579 opened beforehand (@code{$LOCALPORT}) will be routed normally.
7580 Line 2 marks every other packet to a DNS-Server with mark 3 (chosen
7581 arbitrarily). The third line adds a routing policy based on this mark
7582 3 via the routing table.
7583
7584 @node Serving DNS lookups via GNS on W32
7585 @subsection Serving DNS lookups via GNS on W32
7586
7587 @c %**end of header
7588
7589 This section documents how the libw32nsp (and
7590 gnunet-gns-helper-service-w32) do DNS resolutions of DNS queries on the
7591 local system. This only applies to GNUnet running on W32.
7592
7593 W32 has a concept of "Namespaces" and "Namespace providers".
7594 These are used to present various name systems to applications in a
7595 generic way.
7596 Namespaces include DNS, mDNS, NLA and others. For each namespace any
7597 number of providers could be registered, and they are queried in an order
7598 of priority (which is adjustable).
7599
7600 Applications can resolve names by using WSALookupService*() family of
7601 functions.
7602
7603 However, these are WSA-only facilities. Common BSD socket functions for
7604 namespace resolutions are gethostbyname and getaddrinfo (among others).
7605 These functions are implemented internally (by default - by mswsock,
7606 which also implements the default DNS provider) as wrappers around
7607 WSALookupService*() functions (see "Sample Code for a Service Provider"
7608 on MSDN).
7609
7610 On W32 GNUnet builds a libw32nsp - a namespace provider, which can then be
7611 installed into the system by using w32nsp-install (and uninstalled by
7612 w32nsp-uninstall), as described in "Installation Handbook".
7613
7614 libw32nsp is very simple and has almost no dependencies. As a response to
7615 NSPLookupServiceBegin(), it only checks that the provider GUID passed to
7616 it by the caller matches GNUnet DNS Provider GUID, checks that name being
7617 resolved ends in ".gnu" or ".zkey", then connects to
7618 gnunet-gns-helper-service-w32 at 127.0.0.1:5353 (hardcoded) and sends the
7619 name resolution request there, returning the connected socket to the
7620 caller.
7621
7622 When the caller invokes NSPLookupServiceNext(), libw32nsp reads a
7623 completely formed reply from that socket, unmarshalls it, then gives
7624 it back to the caller.
7625
7626 At the moment gnunet-gns-helper-service-w32 is implemented to ever give
7627 only one reply, and subsequent calls to NSPLookupServiceNext() will fail
7628 with WSA_NODATA (first call to NSPLookupServiceNext() might also fail if
7629 GNS failed to find the name, or there was an error connecting to it).
7630
7631 gnunet-gns-helper-service-w32 does most of the processing:
7632
7633 @itemize @bullet
7634 @item Maintains a connection to GNS.
7635 @item Reads GNS config and loads appropriate keys.
7636 @item Checks service GUID and decides on the type of record to look up,
7637 refusing to make a lookup outright when unsupported service GUID is
7638 passed.
7639 @item Launches the lookup
7640 @end itemize
7641
7642 When lookup result arrives, gnunet-gns-helper-service-w32 forms a complete
7643 reply (including filling a WSAQUERYSETW structure and, possibly, a binary
7644 blob with a hostent structure for gethostbyname() client), marshalls it,
7645 and sends it back to libw32nsp. If no records were found, it sends an
7646 empty header.
7647
7648 This works for most normal applications that use gethostbyname() or
7649 getaddrinfo() to resolve names, but fails to do anything with
7650 applications that use alternative means of resolving names (such as
7651 sending queries to a DNS server directly by themselves).
7652 This includes some of well known utilities, like "ping" and "nslookup".
7653
7654 @cindex GNS Namecache
7655 @node GNS Namecache
7656 @section GNS Namecache
7657
7658 @c %**end of header
7659
7660 The NAMECACHE subsystem is responsible for caching (encrypted) resolution
7661 results of the GNU Name System (GNS). GNS makes zone information available
7662 to other users via the DHT. However, as accessing the DHT for every
7663 lookup is expensive (and as the DHT's local cache is lost whenever the
7664 peer is restarted), GNS uses the NAMECACHE as a more persistent cache for
7665 DHT lookups.
7666 Thus, instead of always looking up every name in the DHT, GNS first
7667 checks if the result is already available locally in the NAMECACHE.
7668 Only if there is no result in the NAMECACHE, GNS queries the DHT.
7669 The NAMECACHE stores data in the same (encrypted) format as the DHT.
7670 It thus makes no sense to iterate over all items in the
7671 NAMECACHE --- the NAMECACHE does not have a way to provide the keys
7672 required to decrypt the entries.
7673
7674 Blocks in the NAMECACHE share the same expiration mechanism as blocks in
7675 the DHT --- the block expires wheneever any of the records in
7676 the (encrypted) block expires.
7677 The expiration time of the block is the only information stored in
7678 plaintext. The NAMECACHE service internally performs all of the required
7679 work to expire blocks, clients do not have to worry about this.
7680 Also, given that NAMECACHE stores only GNS blocks that local users
7681 requested, there is no configuration option to limit the size of the
7682 NAMECACHE. It is assumed to be always small enough (a few MB) to fit on
7683 the drive.
7684
7685 The NAMECACHE supports the use of different database backends via a
7686 plugin API.
7687
7688 @menu
7689 * libgnunetnamecache::
7690 * The NAMECACHE Client-Service Protocol::
7691 * The NAMECACHE Plugin API::
7692 @end menu
7693
7694 @node libgnunetnamecache
7695 @subsection libgnunetnamecache
7696
7697 @c %**end of header
7698
7699 The NAMECACHE API consists of five simple functions. First, there is
7700 @code{GNUNET_NAMECACHE_connect} to connect to the NAMECACHE service.
7701 This returns the handle required for all other operations on the
7702 NAMECACHE. Using @code{GNUNET_NAMECACHE_block_cache} clients can insert a
7703 block into the cache.
7704 @code{GNUNET_NAMECACHE_lookup_block} can be used to lookup blocks that
7705 were stored in the NAMECACHE. Both operations can be cancelled using
7706 @code{GNUNET_NAMECACHE_cancel}. Note that cancelling a
7707 @code{GNUNET_NAMECACHE_block_cache} operation can result in the block
7708 being stored in the NAMECACHE --- or not. Cancellation primarily ensures
7709 that the continuation function with the result of the operation will no
7710 longer be invoked.
7711 Finally, @code{GNUNET_NAMECACHE_disconnect} closes the connection to the
7712 NAMECACHE.
7713
7714 The maximum size of a block that can be stored in the NAMECACHE is
7715 @code{GNUNET_NAMECACHE_MAX_VALUE_SIZE}, which is defined to be 63 kB.
7716
7717 @node The NAMECACHE Client-Service Protocol
7718 @subsection The NAMECACHE Client-Service Protocol
7719
7720 @c %**end of header
7721
7722 All messages in the NAMECACHE IPC protocol start with the
7723 @code{struct GNUNET_NAMECACHE_Header} which adds a request
7724 ID (32-bit integer) to the standard message header.
7725 The request ID is used to match requests with the
7726 respective responses from the NAMECACHE, as they are allowed to happen
7727 out-of-order.
7728
7729
7730 @menu
7731 * Lookup::
7732 * Store::
7733 @end menu
7734
7735 @node Lookup
7736 @subsubsection Lookup
7737
7738 @c %**end of header
7739
7740 The @code{struct LookupBlockMessage} is used to lookup a block stored in
7741 the cache.
7742 It contains the query hash. The NAMECACHE always responds with a
7743 @code{struct LookupBlockResponseMessage}. If the NAMECACHE has no
7744 response, it sets the expiration time in the response to zero.
7745 Otherwise, the response is expected to contain the expiration time, the
7746 ECDSA signature, the derived key and the (variable-size) encrypted data
7747 of the block.
7748
7749 @node Store
7750 @subsubsection Store
7751
7752 @c %**end of header
7753
7754 The @code{struct BlockCacheMessage} is used to cache a block in the
7755 NAMECACHE.
7756 It has the same structure as the @code{struct LookupBlockResponseMessage}.
7757 The service responds with a @code{struct BlockCacheResponseMessage} which
7758 contains the result of the operation (success or failure).
7759 In the future, we might want to make it possible to provide an error
7760 message as well.
7761
7762 @node The NAMECACHE Plugin API
7763 @subsection The NAMECACHE Plugin API
7764 @c %**end of header
7765
7766 The NAMECACHE plugin API consists of two functions, @code{cache_block} to
7767 store a block in the database, and @code{lookup_block} to lookup a block
7768 in the database.
7769
7770
7771 @menu
7772 * Lookup2::
7773 * Store2::
7774 @end menu
7775
7776 @node Lookup2
7777 @subsubsection Lookup2
7778
7779 @c %**end of header
7780
7781 The @code{lookup_block} function is expected to return at most one block
7782 to the iterator, and return @code{GNUNET_NO} if there were no non-expired
7783 results.
7784 If there are multiple non-expired results in the cache, the lookup is
7785 supposed to return the result with the largest expiration time.
7786
7787 @node Store2
7788 @subsubsection Store2
7789
7790 @c %**end of header
7791
7792 The @code{cache_block} function is expected to try to store the block in
7793 the database, and return @code{GNUNET_SYSERR} if this was not possible
7794 for any reason.
7795 Furthermore, @code{cache_block} is expected to implicitly perform cache
7796 maintenance and purge blocks from the cache that have expired. Note that
7797 @code{cache_block} might encounter the case where the database already has
7798 another block stored under the same key. In this case, the plugin must
7799 ensure that the block with the larger expiration time is preserved.
7800 Obviously, this can done either by simply adding new blocks and selecting
7801 for the most recent expiration time during lookup, or by checking which
7802 block is more recent during the store operation.
7803
7804 @cindex REVOCATION Subsystem
7805 @node REVOCATION Subsystem
7806 @section REVOCATION Subsystem
7807 @c %**end of header
7808
7809 The REVOCATION subsystem is responsible for key revocation of Egos.
7810 If a user learns that theis private key has been compromised or has lost
7811 it, they can use the REVOCATION system to inform all of the other users
7812 that their private key is no longer valid.
7813 The subsystem thus includes ways to query for the validity of keys and to
7814 propagate revocation messages.
7815
7816 @menu
7817 * Dissemination::
7818 * Revocation Message Design Requirements::
7819 * libgnunetrevocation::
7820 * The REVOCATION Client-Service Protocol::
7821 * The REVOCATION Peer-to-Peer Protocol::
7822 @end menu
7823
7824 @node Dissemination
7825 @subsection Dissemination
7826
7827 @c %**end of header
7828
7829 When a revocation is performed, the revocation is first of all
7830 disseminated by flooding the overlay network.
7831 The goal is to reach every peer, so that when a peer needs to check if a
7832 key has been revoked, this will be purely a local operation where the
7833 peer looks at his local revocation list. Flooding the network is also the
7834 most robust form of key revocation --- an adversary would have to control
7835 a separator of the overlay graph to restrict the propagation of the
7836 revocation message. Flooding is also very easy to implement --- peers that
7837 receive a revocation message for a key that they have never seen before
7838 simply pass the message to all of their neighbours.
7839
7840 Flooding can only distribute the revocation message to peers that are
7841 online.
7842 In order to notify peers that join the network later, the revocation
7843 service performs efficient set reconciliation over the sets of known
7844 revocation messages whenever two peers (that both support REVOCATION
7845 dissemination) connect.
7846 The SET service is used to perform this operation efficiently.
7847
7848 @node Revocation Message Design Requirements
7849 @subsection Revocation Message Design Requirements
7850
7851 @c %**end of header
7852
7853 However, flooding is also quite costly, creating O(|E|) messages on a
7854 network with |E| edges.
7855 Thus, revocation messages are required to contain a proof-of-work, the
7856 result of an expensive computation (which, however, is cheap to verify).
7857 Only peers that have expended the CPU time necessary to provide
7858 this proof will be able to flood the network with the revocation message.
7859 This ensures that an attacker cannot simply flood the network with
7860 millions of revocation messages. The proof-of-work required by GNUnet is
7861 set to take days on a typical PC to compute; if the ability to quickly
7862 revoke a key is needed, users have the option to pre-compute revocation
7863 messages to store off-line and use instantly after their key has expired.
7864
7865 Revocation messages must also be signed by the private key that is being
7866 revoked. Thus, they can only be created while the private key is in the
7867 possession of the respective user. This is another reason to create a
7868 revocation message ahead of time and store it in a secure location.
7869
7870 @node libgnunetrevocation
7871 @subsection libgnunetrevocation
7872
7873 @c %**end of header
7874
7875 The REVOCATION API consists of two parts, to query and to issue
7876 revocations.
7877
7878
7879 @menu
7880 * Querying for revoked keys::
7881 * Preparing revocations::
7882 * Issuing revocations::
7883 @end menu
7884
7885 @node Querying for revoked keys
7886 @subsubsection Querying for revoked keys
7887
7888 @c %**end of header
7889
7890 @code{GNUNET_REVOCATION_query} is used to check if a given ECDSA public
7891 key has been revoked.
7892 The given callback will be invoked with the result of the check.
7893 The query can be cancelled using @code{GNUNET_REVOCATION_query_cancel} on
7894 the return value.
7895
7896 @node Preparing revocations
7897 @subsubsection Preparing revocations
7898
7899 @c %**end of header
7900
7901 It is often desirable to create a revocation record ahead-of-time and
7902 store it in an off-line location to be used later in an emergency.
7903 This is particularly true for GNUnet revocations, where performing the
7904 revocation operation itself is computationally expensive and thus is
7905 likely to take some time.
7906 Thus, if users want the ability to perform revocations quickly in an
7907 emergency, they must pre-compute the revocation message.
7908 The revocation API enables this with two functions that are used to
7909 compute the revocation message, but not trigger the actual revocation
7910 operation.
7911
7912 @code{GNUNET_REVOCATION_check_pow} should be used to calculate the
7913 proof-of-work required in the revocation message. This function takes the
7914 public key, the required number of bits for the proof of work (which in
7915 GNUnet is a network-wide constant) and finally a proof-of-work number as
7916 arguments.
7917 The function then checks if the given proof-of-work number is a valid
7918 proof of work for the given public key. Clients preparing a revocation
7919 are expected to call this function repeatedly (typically with a
7920 monotonically increasing sequence of numbers of the proof-of-work number)
7921 until a given number satisfies the check.
7922 That number should then be saved for later use in the revocation
7923 operation.
7924
7925 @code{GNUNET_REVOCATION_sign_revocation} is used to generate the
7926 signature that is required in a revocation message.
7927 It takes the private key that (possibly in the future) is to be revoked
7928 and returns the signature.
7929 The signature can again be saved to disk for later use, which will then
7930 allow performing a revocation even without access to the private key.
7931
7932 @node Issuing revocations
7933 @subsubsection Issuing revocations
7934
7935
7936 Given a ECDSA public key, the signature from @code{GNUNET_REVOCATION_sign}
7937 and the proof-of-work,
7938 @code{GNUNET_REVOCATION_revoke} can be used to perform the
7939 actual revocation. The given callback is called upon completion of the
7940 operation. @code{GNUNET_REVOCATION_revoke_cancel} can be used to stop the
7941 library from calling the continuation; however, in that case it is
7942 undefined whether or not the revocation operation will be executed.
7943
7944 @node The REVOCATION Client-Service Protocol
7945 @subsection The REVOCATION Client-Service Protocol
7946
7947
7948 The REVOCATION protocol consists of four simple messages.
7949
7950 A @code{QueryMessage} containing a public ECDSA key is used to check if a
7951 particular key has been revoked. The service responds with a
7952 @code{QueryResponseMessage} which simply contains a bit that says if the
7953 given public key is still valid, or if it has been revoked.
7954
7955 The second possible interaction is for a client to revoke a key by
7956 passing a @code{RevokeMessage} to the service. The @code{RevokeMessage}
7957 contains the ECDSA public key to be revoked, a signature by the
7958 corresponding private key and the proof-of-work, The service responds
7959 with a @code{RevocationResponseMessage} which can be used to indicate
7960 that the @code{RevokeMessage} was invalid (i.e. proof of work incorrect),
7961 or otherwise indicates that the revocation has been processed
7962 successfully.
7963
7964 @node The REVOCATION Peer-to-Peer Protocol
7965 @subsection The REVOCATION Peer-to-Peer Protocol
7966
7967 @c %**end of header
7968
7969 Revocation uses two disjoint ways to spread revocation information among
7970 peers.
7971 First of all, P2P gossip exchanged via CORE-level neighbours is used to
7972 quickly spread revocations to all connected peers.
7973 Second, whenever two peers (that both support revocations) connect,
7974 the SET service is used to compute the union of the respective revocation
7975 sets.
7976
7977 In both cases, the exchanged messages are @code{RevokeMessage}s which
7978 contain the public key that is being revoked, a matching ECDSA signature,
7979 and a proof-of-work.
7980 Whenever a peer learns about a new revocation this way, it first
7981 validates the signature and the proof-of-work, then stores it to disk
7982 (typically to a file $GNUNET_DATA_HOME/revocation.dat) and finally
7983 spreads the information to all directly connected neighbours.
7984
7985 For computing the union using the SET service, the peer with the smaller
7986 hashed peer identity will connect (as a "client" in the two-party set
7987 protocol) to the other peer after one second (to reduce traffic spikes
7988 on connect) and initiate the computation of the set union.
7989 All revocation services use a common hash to identify the SET operation
7990 over revocation sets.
7991
7992 The current implementation accepts revocation set union operations from
7993 all peers at any time; however, well-behaved peers should only initiate
7994 this operation once after establishing a connection to a peer with a
7995 larger hashed peer identity.
7996
7997 @cindex FS
7998 @cindex FS Subsystem
7999 @node File-sharing (FS) Subsystem
8000 @section File-sharing (FS) Subsystem
8001
8002 @c %**end of header
8003
8004 This chapter describes the details of how the file-sharing service works.
8005 As with all services, it is split into an API (libgnunetfs), the service
8006 process (gnunet-service-fs) and user interface(s).
8007 The file-sharing service uses the datastore service to store blocks and
8008 the DHT (and indirectly datacache) for lookups for non-anonymous
8009 file-sharing.
8010 Furthermore, the file-sharing service uses the block library (and the
8011 block fs plugin) for validation of DHT operations.
8012
8013 In contrast to many other services, libgnunetfs is rather complex since
8014 the client library includes a large number of high-level abstractions;
8015 this is necessary since the Fs service itself largely only operates on
8016 the block level.
8017 The FS library is responsible for providing a file-based abstraction to
8018 applications, including directories, meta data, keyword search,
8019 verification, and so on.
8020
8021 The method used by GNUnet to break large files into blocks and to use
8022 keyword search is called the
8023 "Encoding for Censorship Resistant Sharing" (ECRS).
8024 ECRS is largely implemented in the fs library; block validation is also
8025 reflected in the block FS plugin and the FS service.
8026 ECRS on-demand encoding is implemented in the FS service.
8027
8028 NOTE: The documentation in this chapter is quite incomplete.
8029
8030 @menu
8031 * Encoding for Censorship-Resistant Sharing (ECRS)::
8032 * File-sharing persistence directory structure::
8033 @end menu
8034
8035 @cindex ECRS
8036 @cindex Encoding for Censorship-Resistant Sharing
8037 @node Encoding for Censorship-Resistant Sharing (ECRS)
8038 @subsection Encoding for Censorship-Resistant Sharing (ECRS)
8039
8040 @c %**end of header
8041
8042 When GNUnet shares files, it uses a content encoding that is called ECRS,
8043 the Encoding for Censorship-Resistant Sharing.
8044 Most of ECRS is described in the (so far unpublished) research paper
8045 attached to this page. ECRS obsoletes the previous ESED and ESED II
8046 encodings which were used in GNUnet before version 0.7.0.
8047 The rest of this page assumes that the reader is familiar with the
8048 attached paper. What follows is a description of some minor extensions
8049 that GNUnet makes over what is described in the paper.
8050 The reason why these extensions are not in the paper is that we felt
8051 that they were obvious or trivial extensions to the original scheme and
8052 thus did not warrant space in the research report.
8053
8054 @menu
8055 * Namespace Advertisements::
8056 * KSBlocks::
8057 @end menu
8058
8059 @node Namespace Advertisements
8060 @subsubsection Namespace Advertisements
8061
8062 @c %**end of header
8063 @c %**FIXME: all zeroses -> ?
8064
8065 An @code{SBlock} with identifier all zeros is a signed
8066 advertisement for a namespace. This special @code{SBlock} contains
8067 metadata describing the content of the namespace.
8068 Instead of the name of the identifier for a potential update, it contains
8069 the identifier for the root of the namespace.
8070 The URI should always be empty. The @code{SBlock} is signed with the
8071 content provder's RSA private key (just like any other SBlock). Peers
8072 can search for @code{SBlock}s in order to find out more about a namespace.
8073
8074 @node KSBlocks
8075 @subsubsection KSBlocks
8076
8077 @c %**end of header
8078
8079 GNUnet implements @code{KSBlocks} which are @code{KBlocks} that, instead
8080 of encrypting a CHK and metadata, encrypt an @code{SBlock} instead.
8081 In other words, @code{KSBlocks} enable GNUnet to find @code{SBlocks}
8082 using the global keyword search.
8083 Usually the encrypted @code{SBlock} is a namespace advertisement.
8084 The rationale behind @code{KSBlock}s and @code{SBlock}s is to enable
8085 peers to discover namespaces via keyword searches, and, to associate
8086 useful information with namespaces. When GNUnet finds @code{KSBlocks}
8087 during a normal keyword search, it adds the information to an internal
8088 list of discovered namespaces. Users looking for interesting namespaces
8089 can then inspect this list, reducing the need for out-of-band discovery
8090 of namespaces.
8091 Naturally, namespaces (or more specifically, namespace advertisements) can
8092 also be referenced from directories, but @code{KSBlock}s should make it
8093 easier to advertise namespaces for the owner of the pseudonym since they
8094 eliminate the need to first create a directory.
8095
8096 Collections are also advertised using @code{KSBlock}s.
8097
8098 @c https://gnunet.org/sites/default/files/ecrs.pdf
8099
8100 @node File-sharing persistence directory structure
8101 @subsection File-sharing persistence directory structure
8102
8103 @c %**end of header
8104
8105 This section documents how the file-sharing library implements
8106 persistence of file-sharing operations and specifically the resulting
8107 directory structure.
8108 This code is only active if the @code{GNUNET_FS_FLAGS_PERSISTENCE} flag
8109 was set when calling @code{GNUNET_FS_start}.
8110 In this case, the file-sharing library will try hard to ensure that all
8111 major operations (searching, downloading, publishing, unindexing) are
8112 persistent, that is, can live longer than the process itself.
8113 More specifically, an operation is supposed to live until it is
8114 explicitly stopped.
8115
8116 If @code{GNUNET_FS_stop} is called before an operation has been stopped, a
8117 @code{SUSPEND} event is generated and then when the process calls
8118 @code{GNUNET_FS_start} next time, a @code{RESUME} event is generated.
8119 Additionally, even if an application crashes (segfault, SIGKILL, system
8120 crash) and hence @code{GNUNET_FS_stop} is never called and no
8121 @code{SUSPEND} events are generated, operations are still resumed (with
8122 @code{RESUME} events).
8123 This is implemented by constantly writing the current state of the
8124 file-sharing operations to disk.
8125 Specifically, the current state is always written to disk whenever
8126 anything significant changes (the exception are block-wise progress in
8127 publishing and unindexing, since those operations would be slowed down
8128 significantly and can be resumed cheaply even without detailed
8129 accounting).
8130 Note that if the process crashes (or is killed) during a serialization
8131 operation, FS does not guarantee that this specific operation is
8132 recoverable (no strict transactional semantics, again for performance
8133 reasons). However, all other unrelated operations should resume nicely.
8134
8135 Since we need to serialize the state continuously and want to recover as
8136 much as possible even after crashing during a serialization operation,
8137 we do not use one large file for serialization.
8138 Instead, several directories are used for the various operations.
8139 When @code{GNUNET_FS_start} executes, the master directories are scanned
8140 for files describing operations to resume.
8141 Sometimes, these operations can refer to related operations in child
8142 directories which may also be resumed at this point.
8143 Note that corrupted files are cleaned up automatically.
8144 However, dangling files in child directories (those that are not
8145 referenced by files from the master directories) are not automatically
8146 removed.
8147
8148 Persistence data is kept in a directory that begins with the "STATE_DIR"
8149 prefix from the configuration file
8150 (by default, "$SERVICEHOME/persistence/") followed by the name of the
8151 client as given to @code{GNUNET_FS_start} (for example, "gnunet-gtk")
8152 followed by the actual name of the master or child directory.
8153
8154 The names for the master directories follow the names of the operations:
8155
8156 @itemize @bullet
8157 @item "search"
8158 @item "download"
8159 @item "publish"
8160 @item "unindex"
8161 @end itemize
8162
8163 Each of the master directories contains names (chosen at random) for each
8164 active top-level (master) operation.
8165 Note that a download that is associated with a search result is not a
8166 top-level operation.
8167
8168 In contrast to the master directories, the child directories are only
8169 consulted when another operation refers to them.
8170 For each search, a subdirectory (named after the master search
8171 synchronization file) contains the search results.
8172 Search results can have an associated download, which is then stored in
8173 the general "download-child" directory.
8174 Downloads can be recursive, in which case children are stored in
8175 subdirectories mirroring the structure of the recursive download
8176 (either starting in the master "download" directory or in the
8177 "download-child" directory depending on how the download was initiated).
8178 For publishing operations, the "publish-file" directory contains
8179 information about the individual files and directories that are part of
8180 the publication.
8181 However, this directory structure is flat and does not mirror the
8182 structure of the publishing operation.
8183 Note that unindex operations cannot have associated child operations.
8184
8185 @cindex REGEX subsystem
8186 @node REGEX Subsystem
8187 @section REGEX Subsystem
8188
8189 @c %**end of header
8190
8191 Using the REGEX subsystem, you can discover peers that offer a particular
8192 service using regular expressions.
8193 The peers that offer a service specify it using a regular expressions.
8194 Peers that want to patronize a service search using a string.
8195 The REGEX subsystem will then use the DHT to return a set of matching
8196 offerers to the patrons.
8197
8198 For the technical details, we have Max's defense talk and Max's Master's
8199 thesis.
8200
8201 @c An additional publication is under preparation and available to
8202 @c team members (in Git).
8203 @c FIXME: Where is the file? Point to it. Assuming that it's szengel2012ms
8204
8205 @menu
8206 * How to run the regex profiler::
8207 @end menu
8208
8209 @node How to run the regex profiler
8210 @subsection How to run the regex profiler
8211
8212 @c %**end of header
8213
8214 The gnunet-regex-profiler can be used to profile the usage of mesh/regex
8215 for a given set of regular expressions and strings.
8216 Mesh/regex allows you to announce your peer ID under a certain regex and
8217 search for peers matching a particular regex using a string.
8218 See @uref{https://gnunet.org/szengel2012ms, szengel2012ms} for a full
8219 introduction.
8220
8221 First of all, the regex profiler uses GNUnet testbed, thus all the
8222 implications for testbed also apply to the regex profiler
8223 (for example you need password-less ssh login to the machines listed in
8224 your hosts file).
8225
8226 @strong{Configuration}
8227
8228 Moreover, an appropriate configuration file is needed.
8229 Generally you can refer to the
8230 @file{contrib/regex_profiler_infiniband.conf} file in the sourcecode
8231 of GNUnet for an example configuration.
8232 In the following paragraph the important details are highlighted.
8233
8234 Announcing of the regular expressions is done by the
8235 gnunet-daemon-regexprofiler, therefore you have to make sure it is
8236 started, by adding it to the AUTOSTART set of ARM:
8237
8238 @example
8239 [regexprofiler]
8240 AUTOSTART = YES
8241 @end example
8242
8243 @noindent
8244 Furthermore you have to specify the location of the binary:
8245
8246 @example
8247 [regexprofiler]
8248 # Location of the gnunet-daemon-regexprofiler binary.
8249 BINARY = /home/szengel/gnunet/src/mesh/.libs/gnunet-daemon-regexprofiler
8250 # Regex prefix that will be applied to all regular expressions and
8251 # search string.
8252 REGEX_PREFIX = "GNVPN-0001-PAD"
8253 @end example
8254
8255 @noindent
8256 When running the profiler with a large scale deployment, you probably
8257 want to reduce the workload of each peer.
8258 Use the following options to do this.
8259
8260 @example
8261 [dht]
8262 # Force network size estimation
8263 FORCE_NSE = 1
8264
8265 [dhtcache]
8266 DATABASE = heap
8267 # Disable RC-file for Bloom filter? (for benchmarking with limited IO
8268 # availability)
8269 DISABLE_BF_RC = YES
8270 # Disable Bloom filter entirely
8271 DISABLE_BF = YES
8272
8273 [nse]
8274 # Minimize proof-of-work CPU consumption by NSE
8275 WORKBITS = 1
8276 @end example
8277
8278 @noindent
8279 @strong{Options}
8280
8281 To finally run the profiler some options and the input data need to be
8282 specified on the command line.
8283
8284 @example
8285 gnunet-regex-profiler -c config-file -d log-file -n num-links \
8286 -p path-compression-length -s search-delay -t matching-timeout \
8287 -a num-search-strings hosts-file policy-dir search-strings-file
8288 @end example
8289
8290 @noindent
8291 Where...
8292
8293 @itemize @bullet
8294 @item ... @code{config-file} means the configuration file created earlier.
8295 @item ... @code{log-file} is the file where to write statistics output.
8296 @item ... @code{num-links} indicates the number of random links between
8297 started peers.
8298 @item ... @code{path-compression-length} is the maximum path compression
8299 length in the DFA.
8300 @item ... @code{search-delay} time to wait between peers finished linking
8301 and starting to match strings.
8302 @item ... @code{matching-timeout} timeout after which to cancel the
8303 searching.
8304 @item ... @code{num-search-strings} number of strings in the
8305 search-strings-file.
8306 @item ... the @code{hosts-file} should contain a list of hosts for the
8307 testbed, one per line in the following format:
8308
8309 @itemize @bullet
8310 @item @code{user@@host_ip:port}
8311 @end itemize
8312 @item ... the @code{policy-dir} is a folder containing text files
8313 containing one or more regular expressions. A peer is started for each
8314 file in that folder and the regular expressions in the corresponding file
8315 are announced by this peer.
8316 @item ... the @code{search-strings-file} is a text file containing search
8317 strings, one in each line.
8318 @end itemize
8319
8320 @noindent
8321 You can create regular expressions and search strings for every AS in the
8322 Internet using the attached scripts. You need one of the
8323 @uref{http://data.caida.org/datasets/routing/routeviews-prefix2as/, CAIDA routeviews prefix2as}
8324 data files for this. Run
8325
8326 @example
8327 create_regex.py <filename> <output path>
8328 @end example
8329
8330 @noindent
8331 to create the regular expressions and
8332
8333 @example
8334 create_strings.py <input path> <outfile>
8335 @end example
8336
8337 @noindent
8338 to create a search strings file from the previously created
8339 regular expressions.